forked from Room-11/Jeeves
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Reminder.php
613 lines (523 loc) · 23.9 KB
/
Reminder.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
<?php declare(strict_types=1);
namespace Room11\Jeeves\Plugins;
use Amp\Promise;
use IntervalParser\IntervalParser;
use Room11\Jeeves\Chat\Client\Chars;
use Room11\Jeeves\Chat\Client\ChatClient;
use Room11\Jeeves\Chat\Client\PostFlags;
use Room11\Jeeves\Chat\Message\Command;
use Room11\Jeeves\Chat\Room\Room as ChatRoom;
use Room11\Jeeves\Storage\Admin as AdminStore;
use Room11\Jeeves\Storage\KeyValue as KeyValueStore;
use Room11\Jeeves\System\PluginCommandEndpoint;
use function Amp\cancel;
use function Amp\once;
use function Amp\resolve;
class Reminder extends BasePlugin
{
private $chatClient;
private $storage;
private $watchers;
private $admin;
const USAGE = "Usage: `!!reminder [ examples | list | <text> [ at <time> | in <delay> ] | unset <id> ]` Try `!!reminder examples`" ;
const REMINDER_REGEX = "/(.*)\s+(?:in|at)\s+(.*)/ui";
const TIME_FORMAT_REGEX = "/(?<time>(?:\d|[01]\d|2[0-3]):[0-5]\d)[+-]?(?&time)?/ui";
public function __construct(ChatClient $chatClient, KeyValueStore $storage, AdminStore $admin, array $watchers = []) {
$this->chatClient = $chatClient;
$this->watchers = $watchers;
$this->storage = $storage;
$this->admin = $admin;
}
private function nuke(Command $command) {
return resolve(function() use($command) {
if (!yield $this->admin->isAdmin($command->getRoom(), $command->getUserId())) {
return $this->chatClient->postReply($command, "One cannot simply nuke the reminders without asking Dave.");
}
$reminders = yield $this->storage->getKeys($command->getRoom());
if ($reminders) {
foreach ($reminders as $key){
$key = (string) $key;
yield $this->storage->unset($key, $command->getRoom());
}
}
return $this->chatClient->postMessage($command->getRoom(), "Reminders are gone.");
});
}
private function unset(Command $command) {
$messageId = (string) $command->getParameter(1);
return resolve(function() use($command, $messageId) {
if (!yield $this->admin->isAdmin($command->getRoom(), $command->getUserId())) {
return $this->chatClient->postReply($command, "Only an admin can unset a reminder.");
}
if (yield $this->storage->exists($messageId, $command->getRoom())) {
yield $this->storage->unset($messageId, $command->getRoom());
return $this->chatClient->postMessage($command->getRoom(), "Reminder unset.");
}
return $this->chatClient->postReply($command, "I'm sorry, I couldn't find that key.");
});
}
private function getAllReminders(Command $command): Promise
{
return resolve(function() use($command) {
$message = "Registered reminders are:";
$reminders = yield $this->storage->getAll($command->getRoom());
if(!$reminders){
return $this->chatClient->postMessage($command->getRoom(), "There aren't any scheduled reminders.");
}
$timeouts = [];
foreach ($reminders as $key => $value) {
$text = $value['text'];
$user = $value['username'];
$timestamp = $value['timestamp'];
$seconds = $timestamp - time();
if ($seconds <= 0) {
$timeouts[] = $key;
continue;
}
$message .= sprintf(
"\n%s %s %s %s %s %s - %s - %s ",
Chars::BULLET,
$text,
Chars::RIGHTWARDS_ARROW,
"Id: :" . $key,
Chars::RIGHTWARDS_ARROW,
date('l, dS F Y H:i (e)', $timestamp),
'Set by ' . $user,
'Seconds left: ' . $seconds
);
}
if(count($timeouts) !== count($reminders)){
return $this->chatClient->postMessage($command->getRoom(), $message);
}
});
}
private function setReminder(Command $command, string $commandName): Promise
{
return resolve(function() use($command, $commandName) {
$intervalParser = new IntervalParser();
switch ($commandName){
case 'in':
$parameters = $intervalParser->normalizeTimeInterval(implode(" ", $command->getParameters()));
$expression = IntervalParser::$intervalSeparatorDefinitions . IntervalParser::$intervalWithTrailingData;
if(preg_match($expression, $parameters, $matches)){
$time = $matches['interval'] ?? false;
$text = $matches['trailing'] ?? false;
}
break;
case 'at':
$time = $command->getParameter(0) ?? false; // 24hrs
if($time && preg_match(self::TIME_FORMAT_REGEX, $time)){
$text = implode(" ", array_diff($command->getParameters(), array($time)));
}
break;
case 'reminder':
$parameters = implode(" ", $command->getParameters());
if(!preg_match(self::REMINDER_REGEX, $parameters, $matches)){
return $this->chatClient->postMessage($command->getRoom(), self::USAGE);
}
$time = $matches[2] ?? false;
$string = $matches[1] ?? false;
if(!$string || !$time) break;
$textOrUser = $command->getParameter(0);
$setBy = $command->getUserName();
# Find the target for message
$output = $this->findTargetAndMessage($textOrUser, $string, $setBy);
$target = $output['target'];
$message = $output['message'];
#if(null !== yield $this->chatClient->getPingableName($command->getRoom(), $target)){}
# Decide what to say and to whom
$message = $this->prepareReply($command, $target, $message);
# Only an admin can set a reminder for someone else
if(!in_array($textOrUser, ['me', 'everyone', 'yourself']) && strtolower($setBy) !== strtolower($target)){
if (!yield $this->admin->isAdmin($command->getRoom(), $command->getUserId())) {
return $this->chatClient->postReply($command, "Only an admin can set a reminder for someone else.");
}
}
# Assemble full string/sentence of reminder ping
$text = $this->buildReminderMessage($target, trim($message), $setBy);
# Normalize interval string
if ($time) $time = $intervalParser->normalizeTimeInterval($time);
break;
}
$for = $textOrUser ?? '';
if(empty($time)) return $this->chatClient->postMessage($command->getRoom(), "Have a look at the time again, yo!");
if(empty($text)) return $this->chatClient->postMessage($command->getRoom(), self::USAGE);
$timestamp = strtotime($time) ?: strtotime("+{$time}"); // false|int
if (!$timestamp) return $this->chatClient->postMessage($command->getRoom(), "Have a look at the time again, yo!");
$key = (string) $command->getId();
$value = [
'id' => $key,
'text' => $text,
'delay' => $time,
'userId' => $command->getUserId(),
'username' => $command->getUserName(),
'timestamp' => $timestamp,
'for' => $for
];
$seconds = $timestamp - time();
if ($seconds <= 0) return $this->chatClient->postReply($command, "I guess I'm late: " . $text);
if(yield $this->storage->set($key, $value, $command->getRoom())){
$watcher = once(function () use ($command, $value, $key) {
yield $this->storage->unset($key, $command->getRoom());
if(in_array($value['for'], ["everyone","yourself"])){
return $this->chatClient->postMessage($command->getRoom(), $value['text']);
} elseif ($value['for'] !== $value['username']){
return $this->chatClient->postMessage($command->getRoom(), $value['text'], PostFlags::ALLOW_PINGS);
}
# else reply to the setter
return $this->chatClient->postReply($command, $value['text']);
}, $seconds * 1000);
$this->watchers[] = $watcher;
return $this->chatClient->postMessage($command->getRoom(), "Reminder set.");
}
return $this->chatClient->postMessage($command->getRoom(), "Dunno what happened but I couldn't set the reminder.");
});
}
/**
* Find the intended target of message
*
* @param string $textOrTarget First parameter of message
* @param string $message Reminder text
* @param string $setBy $setBy
* @return array
*/
private function findTargetAndMessage(string $textOrTarget, string $message, string $setBy): array
{
$substring = false;
switch ($textOrTarget){
case 'me':
$target = $setBy;
break;
case 'everyone':
$target = "everyone";
break;
case 'yourself':
$target = 'myself';
break;
default:
if(preg_match("/^@(?<username>.*)/ui", $textOrTarget, $matches)){
$target = $matches['username'];
break;
}
$target = $setBy;
$substring = true;
break;
}
return (!$substring)
? [ 'target' => $target, 'message' => substr($message, strlen($textOrTarget)) ]
: [ 'target' => $target, 'message' => $message ];
}
/**
* Check parameters for context and decide what to say and to whom.
* !!remind @someone|me|yourself|everyone|you that|about|to foo in <time>
*
* @param Command $command
* @param string $target
* @param string $message
* @return string
*/
private function prepareReply(Command $command, string $target, string $message): string
{
$username = $command->getUserName();
$parameters = $command->getParameters();
# remind me [ to grab a beer | that Ace is waiting me | I am late ] in 2hrs
foreach ($parameters as $key => $param){
if($key == 0) $username = null;
switch (strtolower($param)) {
case 'to':
case 'not':
if($parameters[$key - 1] != 'do' && $key < 3){
# [ to not do something | not to miss ]
if (in_array($parameters[$key + 1], ['to', 'not']) && $param != $parameters[$key +1]) {
$param .= '\s' . $parameters[$key + 1];
$message = preg_replace("/{$param}/", "don't", $message, 1);
break;
}
$username = ($target == $command->getUserName()) ? null : $command->getUserName();
$message = ($username == null || $target == 'everyone') ? preg_replace("/{$param}/", "", $message, 1) : $message;
}
break;
case 'i': # remind everyone I hate strtotime
$username = ($target == $command->getUserName()) ? null : $command->getUserName();
$message = $this->translatePronouns($message, $username);
if($username) $message = $this->translateVerbs($message, $parameters[$key + 1]); # this... needs proper NLP
return $message;
case 'that':
if($parameters[$key - 1] != 'about') $message = preg_replace("/{$param}/", '', $message, 1);
break;
case 'yourself': # remind yourself that you are a bot, jeez.
$message = preg_replace("/{$param}/", '', $message, 1);
return "I don't need to be reminded " . $this->translatePronouns($message);
case 'she':
case 'he':
$username = null;
return $this->translatePronouns($message, $username, $command->getUserName());
default:
$username = ($target == $command->getUserName()) ? null : $command->getUserName();
break;
}
}
return $this->translatePronouns($message, $username) ?? $message;
}
/**
* Assemble final sentence for reminder ping.
*
* @param string $target Target found by findTargetAndMessage()
* @param string $message Message found by findTargetAndMessage()
* @param string $setBy $command->getUsername()
* @return string
*/
private function buildReminderMessage(string $target, string $message, string $setBy): string
{
static $starters = [
' wanted me to remind you ', ' asked me to remind you '
];
static $grumble = [
' So get on that, would ya?', " It's about time you get on that."
];
# Check whether the sentence is terminated already
if(!in_array(substr(trim($message), -1), [ '.', '!', '?' ])) $message .= '. ';
if ($target == "everyone") {
$message = 'o/ everyone, ' . $message;
} elseif ($target == 'myself') {
$message = ':-) ' . $message;
} elseif ($setBy == $target) {
if(random_int(0, 100) > 95) $message .= $grumble[array_rand($grumble)];
$message = "@{$target}" . ', '. $message;
} else {
$message = "@{$target}" . ', ' . 'earlier ' . $setBy . $starters[array_rand($starters)]. $message;
}
return $message;
}
# this... needs a better solution / proper NLP
public function translateVerbs(string $message, string $verb): string
{
$verbs = ['can', 'shall', 'am', 'was', 'were', 'haz', 'said', 'made'];
$isOK = (in_array(substr($verb, -1), ['d', 't', 'w']) || in_array($verb, $verbs));
switch ($verb){
case 'do':
case 'go':
$p = "{$verb}es";
break;
case 'have':
$p = "has";
break;
default:
$p = ($isOK) ? $verb : "{$verb}s";
break;
}
return preg_replace("/{$verb}/", $p, $message, 1);
}
# Translate pronouns and the form of to be, if found any.
# $username = null means translatePronouns will translate sentence object to 'you', otherwise to a 3rd person view
public function translatePronouns(string $message, string $username = null, string $setBy = null): string
{
static $expression = "/(?J)
\b(?:
(?<obj>i)(?:(?<part>'m)|\s(?<part>am|was)(?<neg>n't)?)?
|(?<obj>you|they)(?:(?<part>'re)|\s(?<part>are|were)(?<neg>n't)?)?
|(?<obj>it|he|she)(?:(?<part>'s)|\s(?<part>is|was)(?<neg>n't)?)?
|(?<obj>(mine|me|yours?))
|(?<obj>(my|your|it|him|her)(self)?)
)\b
/uix";
$output = preg_replace_callback($expression,
function ($matches) use($username, $setBy) {
$matches = array_filter($matches);
$object = strtolower($matches['obj']);
switch($object){
case 'i':
if($setBy){
$o = $setBy;
break;
}
$o = ($username) ?: 'you';
break;
case 'you':
$o = (isset($matches['part'])) ? 'I ' : 'me';
break;
case 'me':
$o = ($username) ?: 'you';
break;
case 'my':
$o = ($username) ? $username."'s " : 'your ';
break;
case 'yourself': $o = 'myself';
break;
case 'myself':
$o = ($username) ? 'him/herself ' : 'yourself ';
break;
case 'mine':
$o = ($username) ? $username."'s " : 'yours ';
break;
case 'your': $o = 'my ';
break;
case 'yours': $o = 'mine ';
break;
case 'he':
case 'she':
$o = (!$username) ? ' you ' : ' '.$object;
break;
case 'himself':
case 'herself':
$o = (!$username) ? ' yourself ' : ' '.$object;
break;
default: $o = $object;
break;
}
if(isset($matches['part'])){
switch($part = strtolower($matches['part'])){
case "'re":
case "are":
$o .= ($object != 'you') ? ' '.$part : 'am ';
break;
case 'am':
case "'m":
$o .= ($username) ? ' is ' : ' are';
break;
case 'was':
$o .= (in_array($object, ['she','he']) || $o == 'you') ? ' were' : ' '.$part;
break;
case 'were':
$o .= ($object != 'you') ? ' '.$part : ' was';
break;
case "'s":
case "is":
$o .= (in_array($object, ['he', 'she'])) ? ' are ' : ' is';
break;
default:
$o .= $part;
break;
}
}
if(isset($matches['neg'])) $o .= ' not ';
return $o;
}, $message
);
return $output ?? $message;
}
public function apologizeForExpiredReminders(ChatRoom $room, array $reminders): \Generator
{
if(!$reminders) return;
foreach ($reminders as $key) {
$key = (string) $key;
$value = yield $this->storage->get($key, $room);
$text = $value['text'];
$stamp = $value['timestamp'];
$seconds = $stamp - time();
if($seconds > 0) continue;
$reply = "I guess I'm late but, " . $text;
$this->watchers[] = once(function () use ($room, $key, $reply) {
yield $this->storage->unset($key, $room);
return $this->chatClient->postMessage($room, $reply, PostFlags::ALLOW_PINGS);
}, 1000);
}
}
public function rescheduleUpcomingReminders(ChatRoom $room, array $reminders): \Generator
{
if(!$reminders) return;
$this->watchers = [];
foreach ($reminders as $key){
$key = (string) $key;
$value = yield $this->storage->get($key, $room);
$text = $value['text'];
$stamp = $value['timestamp'];
$seconds = $stamp - time();
if ($seconds <= 0) continue;
$this->watchers[] = once(function () use ($room, $key, $text) {
yield $this->storage->unset($key, $room);
return $this->chatClient->postMessage($room, $text, PostFlags::ALLOW_PINGS);
}, $seconds * 1000);
}
}
/**
* Handle a command message
*
* According to http://www.strawpoll.me/11212318/r this plugin will support the following commands
* !!<reminder|remind> remind this <in|at> <time>
* !!at <time> remind this
* !!in <time> remind this
*
* @param Command $command
* @return Promise
*/
public function handleCommand(Command $command): Promise
{
return resolve(function() use($command) {
if ($command->hasParameters() === false) {
return $this->chatClient->postMessage($command->getRoom(), self::USAGE);
}
/* $command->getParameter(0) can be: list | examples | flush | unset | <text> | <time> */
$textOrCommand = $command->getParameter(0);
$commandName = $command->getCommandName(); // <reminder|in|at>
switch ($commandName){
case 'in':
return yield $this->setReminder($command, 'in');
case 'at':
return yield $this->setReminder($command, 'at');
case 'reminder':
break;
}
if (count(array_diff($command->getParameters(), array($textOrCommand))) < 1){
switch ($textOrCommand){
case 'list':
return yield $this->getAllReminders($command);
case 'examples':
return yield $this->getExamples($command);
case 'nuke': // nukes all reminders
return yield $this->nuke($command);
}
}
if( $command->getParameter(0) === 'unset'
&& $command->getParameter(1) !== null
&& count($command->getParameters()) <= 2
){ return yield $this->unset($command); }
return yield $this->setReminder($command, 'reminder');
});
}
public function enableForRoom(ChatRoom $room, bool $persist = true){
$reminders = yield $this->storage->getKeys($room);
yield from $this->rescheduleUpcomingReminders($room, $reminders);
yield from $this->apologizeForExpiredReminders($room, $reminders);
}
public function disableForRoom(ChatRoom $room, bool $persist = false){
if(!$this->watchers) return;
foreach ($this->watchers as $key => $id){
cancel($id);
}
}
public function getExamples(Command $command): Promise
{
$examples = "Examples: \n"
. Chars::BULLET . " !!reminder foo at 18:00 \n"
. Chars::BULLET . " With timezone: (ie. UTC-3) !!reminder foo at 18:00-3:00 \n"
. Chars::BULLET . " !!at 22:00 Grab a beer! \n"
. Chars::BULLET . " !!reminder do something in 2 hours \n"
. Chars::BULLET . " !!remind me to grab a beer in 2 hours \n"
. Chars::BULLET . " !!remind everyone that strpbrk is a thing... in 12 hours \n"
. Chars::BULLET . " !!remind @anAdmin to unpin that last xkcd in 2 days\n"
. Chars::BULLET . " !!remind yourself that you are a bot... in 5 secs\n"
. Chars::BULLET . " !!in 2 days 42 hours 42 minutes 42 seconds 42! \n"
. Chars::BULLET . " !!reminder unset 32901146 \n"
. Chars::BULLET . " !!reminder list \n";
return resolve(function () use($command, $examples) {
return $this->chatClient->postMessage($command->getRoom(), $examples);
});
}
public function getName(): string
{
return 'Reminders';
}
public function getDescription(): string
{
return 'Get reminded by an elephpant because, why not?';
}
public function getCommandEndpoints(): array
{
return [
new PluginCommandEndpoint('reminder', [$this, 'handleCommand'], 'reminder'),
new PluginCommandEndpoint('in', [$this, 'handleCommand'], 'in'),
new PluginCommandEndpoint('at', [$this, 'handleCommand'], 'at')
];
}
}