17f68008de7a4308e8773147925bc9a2d764c742
[SonOfLokstallBot.git] / common.php
1 <?php declare(strict_types=1);
2
3 namespace Common;
4
5 require 'vendor/autoload.php';
6 require 'Commands/MyBills.php';
7 require '../../config.php';
8
9 use Telegram\Bot\Api;
10 use DateTimeImmutable;
11
12 function getTelegram() {
13 STATIC $tg;
14 return $tg = $tg ?? new \Telegram\Bot\Api(BOT_TOKEN);
15 }
16
17 function splitBill($amount) {
18 return floor($amount/2);
19 }
20
21 function identity($x) {
22 return $x;
23 }
24
25 function getMessageSender($update) {
26 return PARTICIPANT_IDS[$update->get('message')->get('from')->get('id')];
27 }
28
29 function getMessageSenderDisplayName($update) {
30 return $update->get('message')->get('from')->get('first_name');
31 }
32
33 function canChatWith($update) {
34 return in_array($update->get('message')->get('from')->get('id'), array_keys(PARTICIPANT_IDS));
35 }
36
37 function debug($whatever) {
38 echo '<pre>';
39 print_r($whatever);
40 echo '</pre>';
41 }
42
43 function getInbox($inbox) {
44 STATIC $inboxes;
45
46 if (!isset($inboxes[$inbox])) {
47 $inboxes[$inbox] = imap_open(
48 '{imap.gmail.com:993/debug/imap/ssl/novalidate-cert}' . $inbox,
49 EMAIL,
50 PASSWORD
51 );
52 }
53
54 return $inboxes[$inbox];
55 }
56
57 function getMessagesFromInbox($inbox, array $rules, $unseenOnly = true) {
58 return array_filter(
59 array_map(
60 function($rule, $service) use ($inbox, $unseenOnly) {
61 $emails = imap_search($inbox, ['SEEN ', 'UNSEEN '][$unseenOnly] . $rule['imapQuery'], SE_UID);
62
63 if(!$emails) {
64 return [];
65 }
66
67 $body = imap_fetchbody($inbox, $emails[0], '1', FT_UID);
68 preg_match($rule['regex'], $rule['messageTransform']($body), $matches);
69
70 return [
71 'service' => $service,
72 'id' => substr(md5($body), 0, 6),
73 'uid' => $emails[0],
74 'telegramMessage' => $rule['telegramMessage'],
75 'due' => new DateTimeImmutable($rule['dateTransform']($matches['due'])),
76 'amount' => $matches['amount']
77 ];
78 },
79 $rules,
80 array_keys($rules)
81 ),
82 function($e) {
83 return !!$e;
84 }
85 );
86 }