-
Notifications
You must be signed in to change notification settings - Fork 237
/
Discord.php
1549 lines (1316 loc) · 46.1 KB
/
Discord.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
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/*
* This file is a part of the DiscordPHP project.
*
* Copyright (c) 2015-present David Cole <[email protected]>
*
* This file is subject to the MIT license that is bundled
* with this source code in the LICENSE.md file.
*/
namespace Discord;
use Discord\Exceptions\IntentException;
use Discord\Factory\Factory;
use Discord\Helpers\Bitwise;
use Discord\Http\Http;
use Discord\Parts\Guild\Guild;
use Discord\Parts\OAuth\Application;
use Discord\Parts\Part;
use Discord\Repository\AbstractRepository;
use Discord\Repository\GuildRepository;
use Discord\Repository\PrivateChannelRepository;
use Discord\Repository\UserRepository;
use Discord\Parts\Channel\Channel;
use Discord\Parts\User\Activity;
use Discord\Parts\User\Client;
use Discord\Parts\User\Member;
use Discord\Parts\User\User;
use Discord\Voice\VoiceClient;
use Discord\WebSockets\Event;
use Discord\WebSockets\Events\GuildCreate;
use Discord\WebSockets\Handlers;
use Discord\WebSockets\Intents;
use Discord\WebSockets\Op;
use Monolog\Handler\StreamHandler;
use Monolog\Logger as Monolog;
use Ratchet\Client\Connector;
use Ratchet\Client\WebSocket;
use Ratchet\RFC6455\Messaging\Message;
use React\EventLoop\Factory as LoopFactory;
use React\EventLoop\LoopInterface;
use React\EventLoop\TimerInterface;
use Discord\Helpers\Deferred;
use Discord\Http\Drivers\React;
use Discord\Http\Endpoint;
use Evenement\EventEmitterTrait;
use Psr\Log\LoggerInterface;
use React\Promise\ExtendedPromiseInterface;
use React\Promise\PromiseInterface;
use React\Socket\Connector as SocketConnector;
use Symfony\Component\OptionsResolver\OptionsResolver;
/**
* The Discord client class.
*
* @property string $id The unique identifier of the client.
* @property string $username The username of the client.
* @property string $password The password of the client (if they have provided it).
* @property string $email The email of the client.
* @property bool $verified Whether the client has verified their email.
* @property string $avatar The avatar URL of the client.
* @property string $avatar_hash The avatar hash of the client.
* @property string $discriminator The unique discriminator of the client.
* @property bool $bot Whether the client is a bot.
* @property User $user The user instance of the client.
* @property Application $application The OAuth2 application of the bot.
* @property GuildRepository $guilds
* @property PrivateChannelRepository $private_channels
* @property UserRepository $users
*/
class Discord
{
use EventEmitterTrait;
/**
* The gateway version the client uses.
*
* @var int Gateway version.
*/
public const GATEWAY_VERSION = 9;
/**
* The client version.
*
* @var string Version.
*/
public const VERSION = 'v7.0.0';
/**
* The logger.
*
* @var LoggerInterface Logger.
*/
protected $logger;
/**
* An array of loggers for voice clients.
*
* @var array Loggers.
*/
protected $voiceLoggers = [];
/**
* An array of options passed to the client.
*
* @var array Options.
*/
protected $options;
/**
* The authentication token.
*
* @var string Token.
*/
protected $token;
/**
* The ReactPHP event loop.
*
* @var LoopInterface Event loop.
*/
protected $loop;
/**
* The WebSocket client factory.
*
* @var Connector Factory.
*/
protected $wsFactory;
/**
* The WebSocket instance.
*
* @var WebSocket Instance.
*/
protected $ws;
/**
* The event handlers.
*
* @var Handlers Handlers.
*/
protected $handlers;
/**
* The packet sequence that the client is up to.
*
* @var int Sequence.
*/
protected $seq;
/**
* Whether the client is currently reconnecting.
*
* @var bool Reconnecting.
*/
protected $reconnecting = false;
/**
* Whether the client is connected to the gateway.
*
* @var bool Connected.
*/
protected $connected = false;
/**
* Whether the client is closing.
*
* @var bool Closing.
*/
protected $closing = false;
/**
* The session ID of the current session.
*
* @var string Session ID.
*/
protected $sessionId;
/**
* An array of voice clients that are currently connected.
*
* @var array Voice Clients.
*/
protected $voiceClients = [];
/**
* An array of large guilds that need to be requested for
* members.
*
* @var array Large guilds.
*/
protected $largeGuilds = [];
/**
* An array of large guilds that have been requested for members.
*
* @var array Large guilds.
*/
protected $largeSent = [];
/**
* An array of unparsed packets.
*
* @var array Unparsed packets.
*/
protected $unparsedPackets = [];
/**
* How many times the client has reconnected.
*
* @var int Reconnect count.
*/
protected $reconnectCount = 0;
/**
* The heartbeat interval.
*
* @var int Heartbeat interval.
*/
protected $heartbeatInterval;
/**
* The timer that sends the heartbeat packet.
*
* @var TimerInterface Timer.
*/
protected $heartbeatTimer;
/**
* The timer that resends the heartbeat packet if
* a HEARTBEAT_ACK packet is not received in 5 seconds.
*
* @var TimerInterface Timer.
*/
protected $heartbeatAckTimer;
/**
* The time that the last heartbeat packet was sent.
*
* @var int Epoch time.
*/
protected $heartbeatTime;
/**
* Whether `ready` has been emitted.
*
* @var bool Emitted.
*/
protected $emittedReady = false;
/**
* The gateway URL that the WebSocket client will connect to.
*
* @var string Gateway URL.
*/
protected $gateway;
/**
* What encoding the client will use, either `json` or `etf`.
*
* @var string Encoding.
*/
protected $encoding = 'json';
/**
* Tracks the number of payloads the client
* has sent in the past 60 seconds.
*
* @var int
*/
protected $payloadCount = 0;
/**
* Payload count reset timer.
*
* @var TimerInterface
*/
protected $payloadTimer;
/**
* The HTTP client.
*
* @var Http Client.
*/
protected $http;
/**
* The part/repository factory.
*
* @var Factory Part factory.
*/
protected $factory;
/**
* The Client class.
*
* @var Client Discord client.
*/
protected $client;
/**
* Creates a Discord client instance.
*
* @param array $options Array of options.
* @throws IntentException
*/
public function __construct(array $options = [])
{
if (php_sapi_name() !== 'cli') {
trigger_error('DiscordPHP will not run on a webserver. Please use PHP CLI to run a DiscordPHP bot.', E_USER_ERROR);
}
// x86 need gmp extension for big integer operation
if (PHP_INT_SIZE === 4 && ! Bitwise::init()) {
trigger_error('ext-gmp is not loaded. Permissions will NOT work correctly!', E_USER_WARNING);
}
$options = $this->resolveOptions($options);
$this->options = $options;
$this->token = $options['token'];
$this->loop = $options['loop'];
$this->logger = $options['logger'];
$connector = new SocketConnector($this->loop, $options['socket_options']);
$this->wsFactory = new Connector($this->loop, $connector);
$this->handlers = new Handlers();
foreach ($options['disabledEvents'] as $event) {
$this->handlers->removeHandler($event);
}
$function = function () use (&$function) {
$this->emittedReady = true;
$this->removeListener('ready', $function);
};
$this->on('ready', $function);
$this->http = new Http(
'Bot '.$this->token,
$this->loop,
$this->options['logger'],
new React($this->loop, $options['socket_options'])
);
$this->factory = new Factory($this, $this->http);
$this->client = $this->factory->create(Client::class, [], true);
$this->connectWs();
}
/**
* Handles `VOICE_SERVER_UPDATE` packets.
*
* @param object $data Packet data.
*/
protected function handleVoiceServerUpdate(object $data): void
{
if (isset($this->voiceClients[$data->d->guild_id])) {
$this->logger->debug('voice server update received', ['guild' => $data->d->guild_id, 'data' => $data->d]);
$this->voiceClients[$data->d->guild_id]->handleVoiceServerChange((array) $data->d);
}
}
/**
* Handles `RESUME` packets.
*
* @param object $data Packet data.
*/
protected function handleResume(object $data): void
{
$this->logger->info('websocket reconnected to discord');
$this->emit('reconnected', [$this]);
}
/**
* Handles `READY` packets.
*
* @param object $data Packet data.
*
* @return false|void
* @throws \Exception
*/
protected function handleReady(object $data)
{
$this->logger->debug('ready packet received');
// If this is a reconnect we don't want to
// reparse the READY packet as it would remove
// all the data cached.
if ($this->reconnecting) {
$this->reconnecting = false;
$this->logger->debug('websocket reconnected to discord through identify');
$this->emit('reconnected', [$this]);
return;
}
$content = $data->d;
$this->emit('trace', $data->d->_trace);
$this->logger->debug('discord trace received', ['trace' => $content->_trace]);
// Setup the user account
$this->client->fill((array) $content->user);
$this->sessionId = $content->session_id;
$this->logger->debug('client created and session id stored', ['session_id' => $content->session_id, 'user' => $this->client->user->getPublicAttributes()]);
// Private Channels
if ($this->options['pmChannels']) {
foreach ($content->private_channels as $channel) {
$channelPart = $this->factory->create(Channel::class, $channel, true);
$this->private_channels->push($channelPart);
}
$this->logger->info('stored private channels', ['count' => $this->private_channels->count()]);
} else {
$this->logger->info('did not parse private channels');
}
// Guilds
$event = new GuildCreate(
$this->http,
$this->factory,
$this
);
$unavailable = [];
foreach ($content->guilds as $guild) {
$deferred = new Deferred();
$deferred->promise()->done(null, function ($d) use (&$unavailable) {
list($status, $data) = $d;
if ($status == 'unavailable') {
$unavailable[$data] = $data;
}
});
$event->handle($deferred, $guild);
}
$this->logger->info('stored guilds', ['count' => $this->guilds->count(), 'unavailable' => count($unavailable)]);
if (count($unavailable) < 1) {
return $this->ready();
}
// Emit ready after 60 seconds
$this->loop->addTimer(60, function () {
$this->ready();
});
$function = function ($guild) use (&$function, &$unavailable) {
$this->logger->debug('guild available', ['guild' => $guild->id, 'unavailable' => count($unavailable)]);
if (array_key_exists($guild->id, $unavailable)) {
unset($unavailable[$guild->id]);
}
// todo setup timer to continue after x amount of time
if (count($unavailable) < 1) {
$this->logger->info('all guilds are now available', ['count' => $this->guilds->count()]);
$this->removeListener(Event::GUILD_CREATE, $function);
$this->setupChunking();
}
};
$this->on(Event::GUILD_CREATE, $function);
}
/**
* Handles `GUILD_MEMBERS_CHUNK` packets.
*
* @param object $data Packet data.
* @throws \Exception
*/
protected function handleGuildMembersChunk(object $data): void
{
$guild = $this->guilds->offsetGet($data->d->guild_id);
$members = $data->d->members;
$this->logger->debug('received guild member chunk', ['guild_id' => $guild->id, 'guild_name' => $guild->name, 'chunk_count' => count($members), 'member_collection' => $guild->members->count(), 'member_count' => $guild->member_count]);
$count = 0;
$skipped = 0;
foreach ($members as $member) {
if ($guild->members->has($member->user->id)) {
++$skipped;
continue;
}
$member = (array) $member;
$member['guild_id'] = $guild->id;
$member['status'] = 'offline';
if (! $this->users->has($member['user']->id)) {
$userPart = $this->factory->create(User::class, $member['user'], true);
$this->users->offsetSet($userPart->id, $userPart);
}
$memberPart = $this->factory->create(Member::class, $member, true);
$guild->members->offsetSet($memberPart->id, $memberPart);
++$count;
}
$this->logger->debug('parsed '.$count.' members (skipped '.$skipped.')', ['repository_count' => $guild->members->count(), 'actual_count' => $guild->member_count]);
if ($guild->members->count() >= $guild->member_count) {
$this->largeSent = array_diff($this->largeSent, [$guild->id]);
$this->logger->debug('all users have been loaded', ['guild' => $guild->id, 'member_collection' => $guild->members->count(), 'member_count' => $guild->member_count]);
$this->guilds->offsetSet($guild->id, $guild);
}
if (count($this->largeSent) < 1) {
$this->ready();
}
}
/**
* Handles `VOICE_STATE_UPDATE` packets.
*
* @param object $data Packet data.
*/
protected function handleVoiceStateUpdate(object $data): void
{
if (isset($this->voiceClients[$data->d->guild_id])) {
$this->logger->debug('voice state update received', ['guild' => $data->d->guild_id, 'data' => $data->d]);
$this->voiceClients[$data->d->guild_id]->handleVoiceStateUpdate($data->d);
}
}
/**
* Handles WebSocket connections received by the client.
*
* @param WebSocket $ws WebSocket client.
*/
public function handleWsConnection(WebSocket $ws): void
{
$this->ws = $ws;
$this->connected = true;
$this->logger->info('websocket connection has been created');
$this->payloadCount = 0;
$this->payloadTimer = $this->loop->addPeriodicTimer(60, function () {
$this->logger->debug('resetting payload count', ['count' => $this->payloadCount]);
$this->payloadCount = 0;
$this->emit('payload_count_reset');
});
$ws->on('message', [$this, 'handleWsMessage']);
$ws->on('close', [$this, 'handleWsClose']);
$ws->on('error', [$this, 'handleWsError']);
}
/**
* Handles WebSocket messages received by the client.
*
* @param Message $message Message object.
*/
public function handleWsMessage(Message $message): void
{
if ($message->isBinary()) {
$data = zlib_decode($message->getPayload());
} else {
$data = $message->getPayload();
}
$data = json_decode($data);
$this->emit('raw', [$data, $this]);
if (isset($data->s)) {
$this->seq = $data->s;
}
$op = [
Op::OP_DISPATCH => 'handleDispatch',
Op::OP_HEARTBEAT => 'handleHeartbeat',
Op::OP_RECONNECT => 'handleReconnect',
Op::OP_INVALID_SESSION => 'handleInvalidSession',
Op::OP_HELLO => 'handleHello',
Op::OP_HEARTBEAT_ACK => 'handleHeartbeatAck',
];
if (isset($op[$data->op])) {
$this->{$op[$data->op]}($data);
}
}
/**
* Handles WebSocket closes received by the client.
*
* @param int $op The close code.
* @param string $reason The reason the WebSocket closed.
*/
public function handleWsClose(int $op, string $reason): void
{
$this->connected = false;
if (! is_null($this->heartbeatTimer)) {
$this->loop->cancelTimer($this->heartbeatTimer);
$this->heartbeatTimer = null;
}
if (! is_null($this->heartbeatAckTimer)) {
$this->loop->cancelTimer($this->heartbeatAckTimer);
$this->heartbeatAckTimer = null;
}
if (! is_null($this->payloadTimer)) {
$this->loop->cancelTimer($this->payloadTimer);
$this->payloadTimer = null;
}
if ($this->closing) {
return;
}
$this->logger->warning('websocket closed', ['op' => $op, 'reason' => $reason]);
if (in_array($op, Op::getCriticalCloseCodes())) {
$this->logger->error('not reconnecting - critical op code', ['op' => $op, 'reason' => $reason]);
} else {
$this->logger->warning('reconnecting in 2 seconds');
$this->loop->addTimer(2, function () {
++$this->reconnectCount;
$this->reconnecting = true;
$this->logger->info('starting reconnect', ['reconnect_count' => $this->reconnectCount]);
$this->connectWs();
});
}
}
/**
* Handles WebSocket errors received by the client.
*
* @param \Exception $e The error.
*/
public function handleWsError(\Exception $e): void
{
// Pawl pls
if (strpos($e->getMessage(), 'Tried to write to closed stream') !== false) {
return;
}
$this->logger->error('websocket error', ['e' => $e->getMessage()]);
$this->emit('error', [$e, $this]);
$this->ws->close(Op::CLOSE_ABNORMAL, $e->getMessage());
}
/**
* Handles cases when the WebSocket cannot be connected to.
*
* @param \Throwable $e
*/
public function handleWsConnectionFailed(\Throwable $e)
{
$this->logger->error('failed to connect to websocket, retry in 5 seconds', ['e' => $e->getMessage()]);
$this->loop->addTimer(5, function () {
$this->connectWs();
});
}
/**
* Handles dispatch events received by the WebSocket.
*
* @param object $data Packet data.
*/
protected function handleDispatch(object $data): void
{
$handlers = [
Event::VOICE_SERVER_UPDATE => 'handleVoiceServerUpdate',
Event::RESUMED => 'handleResume',
Event::READY => 'handleReady',
Event::GUILD_MEMBERS_CHUNK => 'handleGuildMembersChunk',
Event::VOICE_STATE_UPDATE => 'handleVoiceStateUpdate',
];
if (! is_null($hData = $this->handlers->getHandler($data->t))) {
$handler = new $hData['class'](
$this->http,
$this->factory,
$this
);
$deferred = new Deferred();
$deferred->promise()->done(function ($d) use ($data, $hData) {
if (is_array($d) && count($d) == 2) {
list($new, $old) = $d;
} else {
$new = $d;
$old = null;
}
$this->emit($data->t, [$new, $this, $old]);
foreach ($hData['alternatives'] as $alternative) {
$this->emit($alternative, [$d, $this]);
}
if ($data->t == Event::MESSAGE_CREATE && mentioned($this->client->user, $new)) {
$this->emit('mention', [$new, $this, $old]);
}
}, function ($e) use ($data) {
$this->logger->warning('error while trying to handle dispatch packet', ['packet' => $data->t, 'error' => $e]);
}, function ($d) use ($data) {
$this->logger->warning('notified from event', ['data' => $d, 'packet' => $data->t]);
});
$parse = [
Event::GUILD_CREATE,
];
if (! $this->emittedReady && (! in_array($data->t, $parse))) {
$this->unparsedPackets[] = function () use (&$handler, &$deferred, &$data) {
$handler->handle($deferred, $data->d);
};
} else {
$handler->handle($deferred, $data->d);
}
} elseif (isset($handlers[$data->t])) {
$this->{$handlers[$data->t]}($data);
}
}
/**
* Handles heartbeat packets received by the client.
*
* @param object $data Packet data.
*/
protected function handleHeartbeat(object $data): void
{
$this->logger->debug('received heartbeat', ['seq' => $data->d]);
$payload = [
'op' => Op::OP_HEARTBEAT,
'd' => $data->d,
];
$this->send($payload);
}
/**
* Handles heartbeat ACK packets received by the client.
*
* @param object $data Packet data.
*/
protected function handleHeartbeatAck(object $data): void
{
$received = microtime(true);
$diff = $received - $this->heartbeatTime;
$time = $diff * 1000;
if (! is_null($this->heartbeatAckTimer)) {
$this->loop->cancelTimer($this->heartbeatAckTimer);
$this->heartbeatAckTimer = null;
}
$this->emit('heartbeat-ack', [$time, $this]);
$this->logger->debug('received heartbeat ack', ['response_time' => $time]);
}
/**
* Handles reconnect packets received by the client.
*
* @param object $data Packet data.
*/
protected function handleReconnect(object $data): void
{
$this->logger->warning('received opcode 7 for reconnect');
$this->ws->close(
Op::CLOSE_UNKNOWN_ERROR,
'gateway redirecting - opcode 7'
);
}
/**
* Handles invalid session packets received by the client.
*
* @param object $data Packet data.
*/
protected function handleInvalidSession(object $data): void
{
$this->logger->warning('invalid session, re-identifying', ['resumable' => $data->d]);
$this->loop->addTimer(2, function () use ($data) {
$this->identify($data->d);
});
}
/**
* Handles HELLO packets received by the websocket.
*
* @param object $data Packet data.
*/
protected function handleHello(object $data): void
{
$this->logger->info('received hello');
$this->setupHeartbeat($data->d->heartbeat_interval);
$this->identify();
}
/**
* Identifies with the Discord gateway with `IDENTIFY` or `RESUME` packets.
*
* @param bool $resume Whether resume should be enabled.
* @return bool
*/
protected function identify(bool $resume = true): bool
{
if ($resume && $this->reconnecting && ! is_null($this->sessionId)) {
$payload = [
'op' => Op::OP_RESUME,
'd' => [
'session_id' => $this->sessionId,
'seq' => $this->seq,
'token' => $this->token,
],
];
$reason = 'resuming connection';
} else {
$payload = [
'op' => Op::OP_IDENTIFY,
'd' => [
'token' => $this->token,
'properties' => [
'$os' => PHP_OS,
'$browser' => $this->http->getUserAgent(),
'$device' => $this->http->getUserAgent(),
'$referrer' => 'https://github.com/discord-php/DiscordPHP',
'$referring_domain' => 'https://github.com/discord-php/DiscordPHP',
],
'compress' => true,
'intents' => $this->options['intents'],
],
];
if (
array_key_exists('shardId', $this->options) &&
array_key_exists('shardCount', $this->options)
) {
$payload['d']['shard'] = [
(int) $this->options['shardId'],
(int) $this->options['shardCount'],
];
}
$reason = 'identifying';
}
$safePayload = $payload;
$safePayload['d']['token'] = 'xxxxxx';
$this->logger->info($reason, ['payload' => $safePayload]);
$this->send($payload);
return $payload['op'] == Op::OP_RESUME;
}
/**
* Sends a heartbeat packet to the Discord gateway.
*/
public function heartbeat(): void
{
$this->logger->debug('sending heartbeat', ['seq' => $this->seq]);
$payload = [
'op' => Op::OP_HEARTBEAT,
'd' => $this->seq,
];
$this->send($payload, true);
$this->heartbeatTime = microtime(true);
$this->emit('heartbeat', [$this->seq, $this]);
$this->heartbeatAckTimer = $this->loop->addTimer($this->heartbeatInterval / 1000, function () {
if (! $this->connected) {
return;
}
$this->logger->warning('did not receive heartbeat ACK within heartbeat interval, closing connection');
$this->ws->close(1001, 'did not receive heartbeat ack');
});
}
/**
* Sets guild member chunking up.
*
* @return false|void
*/
protected function setupChunking()
{
if ($this->options['loadAllMembers'] === false) {
$this->logger->info('loadAllMembers option is disabled, not setting chunking up');
return $this->ready();
}
$checkForChunks = function () {
if ((count($this->largeGuilds) < 1) && (count($this->largeSent) < 1)) {
$this->ready();
return;
}
if (count($this->largeGuilds) < 1) {
$this->logger->debug('unprocessed chunks', $this->largeSent);
return;
}
if (is_array($this->options['loadAllMembers'])) {
foreach ($this->largeGuilds as $key => $guild) {
if (! in_array($guild, $this->options['loadAllMembers'])) {
$this->logger->debug('not fetching members for guild ID '.$guild);
unset($this->largeGuilds[$key]);
}
}
}
$chunks = array_chunk($this->largeGuilds, 50);
$this->logger->debug('sending '.count($chunks).' chunks with '.count($this->largeGuilds).' large guilds overall');
$this->largeSent = array_merge($this->largeGuilds, $this->largeSent);
$this->largeGuilds = [];
$sendChunks = function () use (&$sendChunks, &$chunks) {
$chunk = array_pop($chunks);
if (is_null($chunk)) {
return;
}
$this->logger->debug('sending chunk with '.count($chunk).' large guilds');
foreach ($chunk as $guild_id) {
$payload = [
'op' => Op::OP_GUILD_MEMBER_CHUNK,
'd' => [
'guild_id' => $guild_id,
'query' => '',
'limit' => 0,
],
];
$this->send($payload);
}
$this->loop->addTimer(1, $sendChunks);
};
$sendChunks();
};
$this->loop->addPeriodicTimer(5, $checkForChunks);
$this->logger->info('set up chunking, checking for chunks every 5 seconds');
$checkForChunks();
}
/**
* Sets the heartbeat timer up.
*
* @param int $interval The heartbeat interval in milliseconds.
*/
protected function setupHeartbeat(int $interval): void
{
$this->heartbeatInterval = $interval;
if (isset($this->heartbeatTimer)) {
$this->loop->cancelTimer($this->heartbeatTimer);
}
$interval = $interval / 1000;
$this->heartbeatTimer = $this->loop->addPeriodicTimer($interval, [$this, 'heartbeat']);
$this->heartbeat();
$this->logger->info('heartbeat timer initilized', ['interval' => $interval * 1000]);
}
/**
* Initializes the connection with the Discord gateway.
*/
protected function connectWs(): void
{
$this->setGateway()->done(function ($gateway) {
if (isset($gateway['session']) && $session = $gateway['session']) {
if ($session['remaining'] < 2) {
$this->logger->error('exceeded number of reconnects allowed, waiting before attempting reconnect', $session);
$this->loop->addTimer($session['reset_after'] / 1000, function () {
$this->connectWs();
});