-
Notifications
You must be signed in to change notification settings - Fork 0
/
MessageHandler.php
400 lines (353 loc) · 17.3 KB
/
MessageHandler.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
<?php
/*
* This file is a part of the PZ Bot project.
*
* Copyright (c) 2024-present Valithor Obsidion <[email protected]>
*/
namespace PZ\Interfaces;
use Discord\Parts\Channel\Message;
use React\Promise\PromiseInterface;
interface MessageHandlerInterface extends HandlerInterface
{
public function handle(Message $message): ?PromiseInterface;
}
interface MessageHandlerCallbackInterface
{
public function __invoke(Message $message, array $message_filtered, string $command): ?PromiseInterface;
}
namespace PZ;
use PZ\Interfaces\MessageHandlerCallbackInterface;
use Discord\Builders\MessageBuilder;
use Discord\Parts\Channel\Message;
use Discord\Parts\Embed\Embed;
use Discord\Helpers\Collection;
use React\Promise\PromiseInterface;
class MessageHandlerCallback implements MessageHandlerCallbackInterface
{
private \Closure $callback;
/**
* Class constructor.
*
* @param callable $callback The callback function to be executed.
* @throws \InvalidArgumentException If the callback does not have the expected number of parameters or if any parameter does not have a type hint or is of the wrong type.
*/
public function __construct(callable $callback)
{
$reflection = new \ReflectionFunction($callback);
$parameters = $reflection->getParameters();
$expectedParameterTypes = [Message::class, 'array', 'string'];
if (count($parameters) !== $count = count($expectedParameterTypes)) throw new \InvalidArgumentException("The callback must take exactly $count parameters: " . implode(', ', $expectedParameterTypes));
foreach ($parameters as $index => $parameter) {
if (! $parameter->hasType()) throw new \InvalidArgumentException("Parameter $index must have a type hint.");
$type = $parameter->getType(); // This could be done all on one line, but it's easier to read this way and makes the compiler happy
if ($type !== null && $type instanceof \ReflectionNamedType) $type = $type->getName();
if ($type !== $expectedParameterTypes[$index]) throw new \InvalidArgumentException("Parameter $index must be of type {$expectedParameterTypes[$index]}.");
}
$this->callback = $callback;
}
public function __invoke(Message $message, array $message_filtered = [], string $command = ''): ?PromiseInterface
{
return call_user_func($this->callback, $message, $message_filtered, $command);
}
}
use PZ\Interfaces\MessageHandlerInterface;
class MessageHandler extends Handler implements MessageHandlerInterface
{
protected array $required_permissions;
protected array $match_methods;
protected array $descriptions;
public function __construct(BOT &$pz, array $handlers = [], array $required_permissions = [], array $match_methods = [], array $descriptions = [])
{
parent::__construct($pz, $handlers);
$this->required_permissions = $required_permissions;
$this->match_methods = $match_methods;
$this->descriptions = $descriptions;
}
public function get(): array
{
return [$this->handlers, $this->required_permissions, $this->match_methods, $this->descriptions];
}
public function set(array $handlers, array $required_permissions = [], array $match_methods = [], array $descriptions = []): self
{
parent::set($handlers);
$this->required_permissions = $required_permissions;
$this->match_methods = $match_methods;
$this->descriptions = $descriptions;
return $this;
}
public function pull(int|string $index, ?callable $defaultCallables = null, array $default_required_permissions = null, array $default_match_methods = null, array $default_descriptions = null): array
{
$return = [];
$return[] = parent::pull($index, $defaultCallables);
if (isset($this->required_permissions[$index])) {
$default_required_permissions = $this->required_permissions[$index];
unset($this->required_permissions[$index]);
}
$return[] = $default_required_permissions;
if (isset($this->match_methods[$index])) {
$default_match_methods = $this->match_methods[$index];
unset($this->match_methods[$index]);
}
$return[] = $default_match_methods;
if (isset($this->descriptions[$index])) {
$default_descriptions = $this->descriptions[$index];
unset($this->descriptions[$index]);
}
$return[] = $default_descriptions;
return $return;
}
public function fill(array $commands, array $handlers, array $required_permissions = [], array $match_methods = [], array $descriptions = []): self
{
if (count($commands) !== count($handlers)) {
throw new \Exception('Commands and Handlers must be the same length.');
return $this;
}
foreach($commands as $command) {
parent::pushHandler(array_shift($handlers), $command);
$this->pushPermission(array_shift($required_permissions), $command);
$this->pushMethod(array_shift($match_methods), $command);
$this->pushDescription(array_shift($descriptions), $command);
}
return $this;
}
public function pushPermission(array $required_permissions, int|string|null $command = null): ?self
{
if ($command) $this->required_permissions[$command] = $required_permissions;
else $this->required_permissions[] = $required_permissions;
return $this;
}
public function pushMethod(string $method, int|string|null $command = null): ?self
{
if ($command) $this->match_methods[$command] = $method;
else $this->match_methods[] = $method;
return $this;
}
public function pushDescription(string $description, int|string|null $command = null): ?self
{
if ($command) $this->descriptions[$command] = $description;
else $this->descriptions[] = $description;
return $this;
}
public function first(): array
{
$toArray = $this->toArray();
$return = [];
$return[] = array_shift(array_shift($toArray) ?? []);
$return[] = array_shift(array_shift($toArray) ?? []);
$return[] = array_shift(array_shift($toArray) ?? []);
return $return;
}
public function last(): array
{
$toArray = $this->toArray();
$return = [];
$return[] = array_pop(array_shift($toArray) ?? []);
$return[] = array_pop(array_shift($toArray) ?? []);
$return[] = array_pop(array_shift($toArray) ?? []);
return $return;
}
public function find(callable $callback): array
{
foreach ($this->handlers as $index => $handler)
if ($callback($handler))
return [$handler, $this->required_permissions[$index] ?? [], $this->match_methods[$index] ?? 'str_starts_with', $this->descriptions[$index] ?? ''];
return [];
}
public function clear(): self
{
parent::clear();
$this->required_permissions = [];
$this->match_methods = [];
$this->descriptions = [];
return $this;
}
// TODO: Review this method
public function map(callable $callback): static
{
$arr = array_combine(array_keys($this->handlers), array_map($callback, array_values($this->toArray())));
return new static($this->pz, array_shift($arr) ?? [], array_shift($arr) ?? [], array_shift($arr) ?? [], array_shift($arr) ?? []);
}
/**
* @throws Exception if toArray property does not exist
*/
public function merge(object $handler): self
{
if (! property_exists($handler, 'toArray')) {
throw new \Exception('Handler::merge() expects parameter 1 to be an object with a method named "toArray", ' . gettype($handler) . ' given');
return $this;
}
$toArray = $handler->toArray();
$this->handlers = array_merge($this->handlers, array_shift($toArray) ?? []);
$this->required_permissions = array_merge($this->required_permissions, array_shift($toArray) ?? []);
$this->match_methods = array_merge($this->match_methods, array_shift($toArray) ?? []);
$this->descriptions = array_merge($this->descriptions, array_shift($toArray) ?? []);
return $this;
}
public function toArray(): array
{
$toArray = parent::toArray();
$toArray[] = $this->required_permissions ?? [];
$toArray[] = $this->match_methods ?? [];
$toArray[] = $this->descriptions ?? [];
return $toArray;
}
public function offsetGet(int|string $offset): array
{
$return = parent::offsetGet($offset);
$return[] = $this->required_permissions[$offset] ?? null;
$return[] = $this->match_methods[$offset] ?? null;
$return[] = $this->descriptions[$offset] ?? null;
return $return;
}
public function offsetSet(int|string $offset, callable $callback, ?array $required_permissions = [], ?string $method = 'str_starts_with', ?string $description = ''): self
{
parent::offsetSet($offset, $callback);
$this->required_permissions[$offset] = $required_permissions;
$this->match_methods[$offset] = $method;
$this->descriptions[$offset] = $description;
return $this;
}
public function setOffset(int|string $newOffset, callable $callback, ?array $required_permissions = [], ?string $method = 'str_starts_with', ?string $description = ''): self
{
parent::setOffset($newOffset, $callback);
if ($offset = $this->getOffset($callback) === false) $offset = $newOffset;
unset($this->required_permissions[$offset]);
unset($this->match_methods[$offset]);
unset($this->descriptions[$offset]);
$this->required_permissions[$newOffset] = $required_permissions;
$this->match_methods[$newOffset] = $method;
$this->descriptions[$newOffset] = $description;
return $this;
}
public function __debugInfo(): array
{
return ['pz' => isset($this->pz) ? $this->pz instanceof BOT : false, 'handlers' => array_keys($this->handlers)];
}
//Unique to MessageHandler
public function handle(Message $message): ?PromiseInterface
{
// if (! $message->member) return $message->reply('Unable to get Discord Member class. Commands are only available in guilds.');
$message_filtered = $this->filterMessage($message);
foreach ($this->handlers as $command => $callback) {
switch ($this->match_methods[$command]) {
case 'exact':
$method_func = function () use ($callback, $message_filtered, $command): ?callable
{
if ($message_filtered['message_content_lower'] == $command)
return $callback; // This is where the magic happens
return null;
};
break;
case 'str_contains':
$method_func = function () use ($callback, $message_filtered, $command): ?callable
{
if (str_contains($message_filtered['message_content_lower'], $command))
return $callback; // This is where the magic happens
return null;
};
break;
case 'str_ends_with':
$method_func = function () use ($callback, $message_filtered, $command): ?callable
{
if (str_ends_with($message_filtered['message_content_lower'], $command))
return $callback; // This is where the magic happens
return null;
};
break;
case 'str_starts_with':
default:
$method_func = function () use ($callback, $message_filtered, $command): ?callable
{
if (str_starts_with($message_filtered['message_content_lower'], $command))
return $callback; // This is where the magic happens
return null;
};
}
if (! $message->member) return null;
if ($callback = $method_func()) { // Command triggered
$required_permissions = $this->required_permissions[$command] ?? [];
if ($lowest_rank = array_pop($required_permissions)) {
if (! isset($this->pz->role_ids[$lowest_rank])) {
$this->pz->logger->warning("Unable to find role ID for rank `$lowest_rank`");
throw new \Exception("Unable to find role ID for rank `$lowest_rank`");
} elseif (! $this->checkRank($message->member->roles, $this->required_permissions[$command] ?? [])) return $this->reply($message, 'Rejected! You need to have at least the <@&' . $this->pz->role_ids[$lowest_rank] . '> rank.');
}
return $callback($message, $message_filtered, $command);
}
}
if (empty($this->handlers)) $this->pz->logger->info('No message handlers found!');
return null;
}
// Don't forget to use ->setAllowedMentions(['parse'=>[]]) on the MessageBuilder object to prevent all roles being pinged
public function generateHelp(?Collection $roles = null): string
{
$ranks = array_keys($this->pz->role_ids);
$ranks[] = 'everyone';
$array = [];
foreach (array_keys($this->handlers) as $command) {
$required_permissions = $this->required_permissions[$command] ?? [];
$lowest_rank = array_pop($required_permissions) ?? 'everyone';
if (! $roles) $array[$lowest_rank][] = $command;
elseif ($lowest_rank == 'everyone' || $this->checkRank($roles, $this->required_permissions[$command])) $array[$lowest_rank][] = $command;
}
$string = '';
foreach ($ranks as $rank) {
if (! isset($array[$rank]) || ! $array[$rank]) continue;
if (is_numeric($rank)) $string .= '<@&' . $this->pz->role_ids[$rank] . '>: `';
else $string .= '@' . $rank . ': `'; // everyone
asort($array[$rank]);
$string .= implode('`, `', $array[$rank]);
$string .= '`' . PHP_EOL;
}
return $string;
}
public function sendMessage($channel, string $content, string $file_name = 'message.txt', $prevent_mentions = false): ?PromiseInterface
{
// $this->logger->debug("Sending message to {$channel->name} ({$channel->id}): {$message}");
if (is_string($channel)) $channel = $this->pz->discord->getChannel($channel);
if (! $channel) {
$this->pz->logger->error("Channel not found: {$channel}");
return null;
}
$builder = MessageBuilder::new();
if ($prevent_mentions) $builder->setAllowedMentions(['parse'=>[]]);
if (strlen($content)<=2000) return $channel->sendMessage($builder->setContent($content));
if (strlen($content)<=4096) {
$embed = new Embed($this->pz->discord);
$embed->setDescription($content);
$builder->addEmbed($embed);
return $channel->sendMessage($builder);
}
return $channel->sendMessage($builder->addFileFromContent($file_name, $content));
}
public function reply(Message $message, string $content, string $file_name = 'message.txt', bool $prevent_mentions = false): ?PromiseInterface
{
// $this->logger->debug("Sending message to {$channel->name} ({$channel->id}): {$message}");
$builder = MessageBuilder::new();
if ($prevent_mentions) $builder->setAllowedMentions(['parse'=>[]]);
if (strlen($content)<=2000) return $message->reply($builder->setContent($content));
if (strlen($content)<=4096) {
$embed = new Embed($this->pz->discord);
$embed->setDescription($content);
$builder->addEmbed($embed);
return $message->reply($builder);
}
return $message->reply($builder->addFileFromContent($file_name, $content));
}
public function filterMessage(Message $message): array
{
if (! $message->guild || $message->guild->owner_id != $this->pz->owner_id) return ['message_content' => '', 'message_content_lower' => '', 'called' => false]; // Only process commands from a guild that Taislin owns
$message_content = '';
$prefix = $this->pz->command_symbol;
$called = false;
if (str_starts_with($message->content, $call = $prefix . ' ')) { $message_content = trim(substr($message->content, strlen($call))); $called = true; }
elseif (str_starts_with($message->content, $call = "<@!{$this->pz->discord->id}>")) { $message_content = trim(substr($message->content, strlen($call))); $called = true; }
elseif (str_starts_with($message->content, $call = "<@{$this->pz->discord->id}>")) { $message_content = trim(substr($message->content, strlen($call))); $called = true; }
return ['message_content' => $message_content, 'message_content_lower' => strtolower($message_content), 'called' => $called];
}
// Don't forget to use ->setAllowedMentions(['parse'=>[]]) on the MessageBuilder object to prevent all roles being pinged
public function __toString(): string
{
return $this->generateHelp();
}
}