-
Notifications
You must be signed in to change notification settings - Fork 1
/
bot.php
64 lines (51 loc) · 1.98 KB
/
bot.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
<?php
$token = getenv('TELEGRAM_BOT_TOKEN');
if (empty($token)) {
die('No token');
}
require 'src/bootstrap.php';
use Telegram\Bot\Api;
use WeightLog\WeightLog;
use WeightLog\Db;
$db = Db::getInstance();
$telegram = new Api($token);
$weightLog = new WeightLog($db);
$telegram->addCommand(\WeightLog\TelegramCommands\OutputCommand::class);
$telegram->addCommand(\WeightLog\TelegramCommands\ApiCommand::class);
$telegram->addCommand(\WeightLog\TelegramCommands\HelpCommand::class);
$run = true;
$lastUpdateId = 0;
while ($run) {
sleep(1);
$updates = $telegram->commandsHandler(false);
if (empty($updates)) {
continue;
}
foreach ($updates as $update) {
$lastUpdateId = $update['update_id'];
if (substr(trim($update['message']['text']), 0, 1) == '/') {
continue;
}
$weightGiven = preg_replace('/[^0-9\.]/', '', $update['message']['text']);
$person = $weightLog->getPersonFromUpdate($update);
$lastWeight = $person['currentweight'];
if (empty($weightGiven)) {
$message = "Huh? I'm afraid that wasn't a valid weight :(";
} else {
$result = $db->perform("INSERT INTO weights (timestamp, weight, personid) VALUES (?, ?, ?)", [
time(),
$weightGiven,
$person['id'],
]);
$weightLog->setCurrentWeight($person, $weightGiven);
if (!empty($lastWeight) && $lastWeight > $weightGiven) {
$diff = round($lastWeight - $weightGiven, 1);
$message = "That's been logged for you. You've lost {$diff} lbs or kgs since last time, that's awesome";
} else {
$message = "That's been logged for you. Keep on keeping on!";
}
}
$message .= "\nYou can view all of your logs here: http://weightlog.ashleyhindle.com/?token=" . urlencode($person['token']);
$telegram->sendMessage($update['message']['chat']['id'], $message);
}
}