/
Channel.php
1592 lines (1406 loc) · 62.7 KB
/
Channel.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 <david.cole1340@gmail.com>
*
* This file is subject to the MIT license that is bundled
* with this source code in the LICENSE.md file.
*/
namespace Discord\Parts\Channel;
use Carbon\Carbon;
use Discord\Builders\MessageBuilder;
use Discord\Exceptions\InvalidOverwriteException;
use Discord\Helpers\Collection;
use Discord\Parts\Embed\Embed;
use Discord\Parts\Guild\Guild;
use Discord\Parts\Guild\Role;
use Discord\Parts\Part;
use Discord\Parts\Permissions\ChannelPermission;
use Discord\Parts\User\Member;
use Discord\Parts\User\User;
use Discord\Repository\Channel\MessageRepository;
use Discord\Repository\Channel\OverwriteRepository;
use Discord\Repository\Channel\VoiceMemberRepository as MemberRepository;
use Discord\Repository\Channel\WebhookRepository;
use Discord\WebSockets\Event;
use Discord\Helpers\Deferred;
use Discord\Helpers\Multipart;
use Discord\Http\Endpoint;
use Discord\Http\Exceptions\NoPermissionsException;
use Discord\Parts\Channel\Forum\Reaction;
use Discord\Parts\Channel\Forum\Tag;
use Discord\Parts\Permissions\RolePermission;
use Discord\Parts\Thread\Thread;
use Discord\Repository\Channel\InviteRepository;
use Discord\Repository\Channel\StageInstanceRepository;
use Discord\Repository\Channel\ThreadRepository;
use React\Promise\ExtendedPromiseInterface;
use Stringable;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Traversable;
use function Discord\getSnowflakeTimestamp;
use function Discord\nowait;
use function React\Promise\all;
use function React\Promise\reject;
use function React\Promise\resolve;
/**
* A Channel can be either a text or voice channel on a Discord guild.
*
* @link https://discord.com/developers/docs/resources/channel#channel-object
*
* @since 2.0.0 Refactored as Part
* @since 1.0.0
*
* @property string $id The unique identifier of the Channel.
* @property int $type The type of the channel.
* @property string|null $guild_id The unique identifier of the guild that the channel belongs to. Only for text or voice channels.
* @property-read Guild|null $guild The guild that the channel belongs to. Only for text or voice channels.
* @property int|null $position The position of the channel on the sidebar.
* @property OverwriteRepository $overwrites Permission overwrites
* @property ?string|null $name The name of the channel.
* @property ?string|null $topic The topic of the channel (0-4096 characters for forum channels, 0-1024 characters for all others).
* @property bool|null $nsfw Whether the channel is NSFW.
* @property ?string|null $last_message_id The unique identifier of the last message sent in the channel (or thread for forum channels) (may not point to an existing or valid message or thread).
* @property int|null $bitrate The bitrate of the channel. Only for voice channels.
* @property int|null $user_limit The user limit of the channel. Max 99 for voice channels and 10000 for stage channels (0 refers to no limit).
* @property int|null $rate_limit_per_user Amount of seconds a user has to wait before sending a new message (slow mode).
* @property Collection|User[] $recipients A collection of all the recipients in the channel. Only for DM or group channels.
* @property-read User|null $recipient The first recipient of the channel. Only for DM or group channels.
* @property-read string|null $recipient_id The ID of the recipient of the channel, if it is a DM channel.
* @property ?string|null $icon Icon hash.
* @property string|null $owner_id The ID of the DM creator. Only for DM or group channels.
* @property string|null $application_id ID of the group DM creator if it is a bot.
* @property bool|null $managed Whether the channel is managed by an application via the `gdm.join` OAuth2 scope. Only for group DM channels.
* @property ?string|null $parent_id ID of the parent channel.
* @property Carbon|null $last_pin_timestamp When the last message was pinned.
* @property ?string|null $rtc_region Voice region id for the voice channel, automatic when set to null.
* @property int|null $video_quality_mode The camera video quality mode of the voice channel, 1 when not present.
* @property int|null $default_auto_archive_duration Default duration for newly created threads, in minutes, to automatically archive the thread after recent activity, can be set to: 60, 1440, 4320, 10080.
* @property string|null $permissions Computed permissions for the invoking user in the channel, including overwrites, only included when part of the resolved data received on an application command interaction.
* @property int|null $flags Channel flags combined as a bitfield.
* @property Collection|Tag[] $available_tags Set of tags that can be used in a forum channel, limited to 20.
* @property ?Reaction|null $default_reaction_emoji Emoji to show in the add reaction button on a thread in a forum channel.
* @property int|null $default_thread_rate_limit_per_user The initial rate_limit_per_user to set on newly created threads in a forum channel. this field is copied to the thread at creation time and does not live update.
* @property ?int|null $default_sort_order The default sort order type used to order posts in forum channels.
* @property int|null $default_forum_layout The default layout type used to display posts in a forum channel. Defaults to `0`, which indicates a layout view has not been set by a channel admin.
*
* @property bool $is_private Whether the channel is a private channel.
* @property MemberRepository $members Voice channel only - members in the channel.
* @property MessageRepository $messages Text channel only - messages sent in the channel.
* @property WebhookRepository $webhooks Webhooks in the channel.
* @property ThreadRepository $threads Threads that belong to the channel.
* @property InviteRepository $invites Invites in the channel.
* @property StageInstanceRepository $stage_instances Stage instances in the channel.
*
* @method ExtendedPromiseInterface<Message> sendMessage(MessageBuilder $builder)
*/
class Channel extends Part implements Stringable
{
public const TYPE_GUILD_TEXT = 0;
public const TYPE_DM = 1;
public const TYPE_GUILD_VOICE = 2;
public const TYPE_GROUP_DM = 3;
public const TYPE_GUILD_CATEGORY = 4;
public const TYPE_GUILD_ANNOUNCEMENT = 5;
public const TYPE_ANNOUNCEMENT_THREAD = 10;
public const TYPE_PUBLIC_THREAD = 11;
public const TYPE_PRIVATE_THREAD = 12;
public const TYPE_GUILD_STAGE_VOICE = 13;
public const TYPE_GUILD_DIRECTORY = 14;
public const TYPE_GUILD_FORUM = 15;
/** @deprecated 10.0.0 Use `Channel::TYPE_GUILD_TEXT` */
public const TYPE_TEXT = self::TYPE_GUILD_TEXT;
/** @deprecated 10.0.0 Use `Channel::TYPE_GUILD_VOICE` */
public const TYPE_VOICE = self::TYPE_GUILD_VOICE;
/** @deprecated 10.0.0 Use `Channel::TYPE_GROUP_DM` */
public const TYPE_GROUP = self::TYPE_GROUP_DM;
/** @deprecated 10.0.0 Use `Channel::TYPE_GUILD_CATEGORY` */
public const TYPE_CATEGORY = self::TYPE_GUILD_CATEGORY;
/** @deprecated 10.0.0 Use `Channel::TYPE_GUILD_ANNOUNCEMENT` */
public const TYPE_NEWS = self::TYPE_GUILD_ANNOUNCEMENT;
/** @deprecated 10.0.0 Use `Channel::TYPE_GUILD_ANNOUNCEMENT` */
public const TYPE_ANNOUNCEMENT = self::TYPE_GUILD_ANNOUNCEMENT;
/** @deprecated 10.0.0 Use `Channel::TYPE_ANNOUNCEMENT_THREAD` */
public const TYPE_NEWS_THREAD = self::TYPE_ANNOUNCEMENT_THREAD;
/** @deprecated 10.0.0 Use `Channel::TYPE_GUILD_STAGE_VOICE` */
public const TYPE_STAGE_CHANNEL = self::TYPE_GUILD_STAGE_VOICE;
/** @deprecated 10.0.0 Use `Channel::TYPE_GUILD_DIRECTORY` */
public const TYPE_DIRECTORY = self::TYPE_GUILD_DIRECTORY;
/** @deprecated 10.0.0 Use `Channel::TYPE_GUILD_FORUM` */
public const TYPE_FORUM = self::TYPE_GUILD_FORUM;
public const VIDEO_QUALITY_AUTO = 1;
public const VIDEO_QUALITY_FULL = 2;
/** @deprecated 10.0.0 Use `Thread::FLAG_PINNED` */
public const FLAG_PINNED = (1 << 1);
public const FLAG_REQUIRE_TAG = (1 << 4);
public const SORT_ORDER_LATEST_ACTIVITY = 0;
public const SORT_ORDER_CREATION_DATE = 1;
public const FORUM_LAYOUT_NOT_SET = 0;
public const FORUM_LAYOUT_LIST_VIEW = 1;
public const FORUM_LAYOUT_GRID_VIEW = 2;
/**
* {@inheritDoc}
*/
protected $fillable = [
'id',
'type',
'guild_id',
'position',
'name',
'topic',
'nsfw',
'last_message_id',
'bitrate',
'user_limit',
'rate_limit_per_user',
'recipients',
'icon',
'owner_id',
'application_id',
'managed',
'parent_id',
'last_pin_timestamp',
'rtc_region',
'video_quality_mode',
'default_auto_archive_duration',
'permissions',
'flags',
'available_tags',
'default_reaction_emoji',
'default_thread_rate_limit_per_user',
'default_sort_order',
'default_forum_layout',
// @internal
'is_private',
// repositories
'permission_overwrites',
];
/**
* {@inheritDoc}
*/
protected $repositories = [
'overwrites' => OverwriteRepository::class,
'members' => MemberRepository::class,
'messages' => MessageRepository::class,
'webhooks' => WebhookRepository::class,
'threads' => ThreadRepository::class,
'invites' => InviteRepository::class,
'stage_instances' => StageInstanceRepository::class,
];
/**
* {@inheritDoc}
*/
protected function afterConstruct(): void
{
if (! array_key_exists('bitrate', $this->attributes) && $this->isVoiceBased()) {
$this->bitrate = 64000;
}
}
/**
* Gets the is_private attribute.
*
* @return bool Whether the channel is private.
*/
protected function getIsPrivateAttribute(): bool
{
return in_array($this->type, [self::TYPE_DM, self::TYPE_GROUP_DM]);
}
/**
* Gets the recipient attribute.
*
* @return User|null The recipient.
*/
protected function getRecipientAttribute(): ?User
{
return $this->recipients->first();
}
/**
* Gets the recipient ID attribute.
*
* @return string|null
*/
protected function getRecipientIdAttribute(): ?string
{
if ($recipient = $this->recipient) {
return $recipient->id;
}
return null;
}
/**
* Gets the recipients attribute.
*
* @return Collection A collection of recipients.
*/
protected function getRecipientsAttribute(): Collection
{
$recipients = Collection::for(User::class);
foreach ($this->attributes['recipients'] ?? [] as $recipient) {
$recipients->pushItem($this->discord->users->get('id', $recipient->id) ?: $this->factory->part(User::class, (array) $recipient, true));
}
return $recipients;
}
/**
* Returns the guild attribute.
*
* @return Guild|null The guild attribute.
*/
protected function getGuildAttribute(): ?Guild
{
return $this->discord->guilds->get('id', $this->guild_id);
}
/**
* Gets the last pinned message timestamp.
*
* @return Carbon|null
*
* @throws \Exception
*/
protected function getLastPinTimestampAttribute(): ?Carbon
{
if (! isset($this->attributes['last_pin_timestamp'])) {
return null;
}
return Carbon::parse($this->attributes['last_pin_timestamp']);
}
/**
* Returns the channels pinned messages.
*
* @link https://discord.com/developers/docs/resources/channel#get-pinned-messages
*
* @return ExtendedPromiseInterface<Collection|Message[]>
*/
public function getPinnedMessages(): ExtendedPromiseInterface
{
return $this->http->get(Endpoint::bind(Endpoint::CHANNEL_PINS, $this->id))
->then(function ($responses) {
$messages = Collection::for(Message::class);
foreach ($responses as $response) {
$messages->pushItem($this->messages->get('id', $response->id) ?: $this->messages->create($response, true));
}
return $messages;
});
}
/**
* Sets permissions in a channel.
*
* @link https://discord.com/developers/docs/resources/channel#edit-channel-permissions
*
* @param Part $part A role or member.
* @param array $allow An array of permissions to allow.
* @param array $deny An array of permissions to deny.
* @param string|null $reason Reason for Audit Log.
*
* @throws InvalidOverwriteException
*
* @return ExtendedPromiseInterface
*/
public function setPermissions(Part $part, array $allow = [], array $deny = [], ?string $reason = null): ExtendedPromiseInterface
{
if ($part instanceof Member) {
$type = Overwrite::TYPE_MEMBER;
} elseif ($part instanceof Role) {
$type = Overwrite::TYPE_ROLE;
} else {
return reject(new InvalidOverwriteException('Given part was not one of member or role.'));
}
$allow = array_fill_keys($allow, true);
$deny = array_fill_keys($deny, true);
$allowPart = $this->factory->part(ChannelPermission::class, $allow, $this->created);
$denyPart = $this->factory->part(ChannelPermission::class, $deny, $this->created);
$overwrite = $this->factory->part(Overwrite::class, [
'id' => $part->id,
'channel_id' => $this->id,
'type' => $type,
'allow' => $allowPart->bitwise,
'deny' => $denyPart->bitwise,
], $this->created);
return $this->setOverwrite($part, $overwrite, $reason);
}
/**
* Sets an overwrite to the channel.
*
* @link https://discord.com/developers/docs/resources/channel#edit-channel-permissions
*
* @param Part $part A role or member.
* @param Overwrite $overwrite An overwrite object.
* @param string|null $reason Reason for Audit Log.
*
* @throws NoPermissionsException Missing manage_roles permission.
* @throws InvalidOverwriteException Overwrite type is not member or role.
*
* @return ExtendedPromiseInterface
*/
public function setOverwrite(Part $part, Overwrite $overwrite, ?string $reason = null): ExtendedPromiseInterface
{
if ($this->guild_id && $botperms = $this->getBotPermissions()) {
if (! $botperms->manage_roles) {
return reject(new NoPermissionsException("You do not have permission to manage roles in the channel {$this->id}."));
}
}
if ($part instanceof Member) {
$type = Overwrite::TYPE_MEMBER;
} elseif ($part instanceof Role) {
$type = Overwrite::TYPE_ROLE;
} else {
return reject(new InvalidOverwriteException('Given part was not one of member or role.'));
}
$payload = [
'id' => $part->id,
'type' => $type,
'allow' => (string) $overwrite->allow->bitwise,
'deny' => (string) $overwrite->deny->bitwise,
];
if (! $this->created) {
$this->attributes['permission_overwrites'][] = $payload;
return resolve();
}
$headers = [];
if (isset($reason)) {
$headers['X-Audit-Log-Reason'] = $reason;
}
return $this->http->put(Endpoint::bind(Endpoint::CHANNEL_PERMISSIONS, $this->id, $part->id), $payload, $headers);
}
/**
* Change category of a channel.
*
* @param Channel|string|null $category The category channel to set it to (either a Channel part or the channel ID or null for none).
* @param int|null $position The new channel position, not relative to category.
* @param string|null $reason Reason for Audit Log.
*
* @return ExtendedPromiseInterface<static>
*
* @throws \RuntimeException
* @throws \InvalidArgumentException
* @throws NoPermissionsException Missing manage_channels permission in either channel.
*/
public function setCategory($category, ?int $position = null, ?string $reason = null): ExtendedPromiseInterface
{
if (! in_array($this->type, [self::TYPE_GUILD_TEXT, self::TYPE_GUILD_VOICE, self::TYPE_GUILD_ANNOUNCEMENT, self::TYPE_GUILD_FORUM])) {
return reject(new \RuntimeException('You can only move Text, Voice, Announcement or Forum channel type.'));
}
if ($botperms = $this->getBotPermissions()) {
if (! $botperms->manage_channels) {
return reject(new NoPermissionsException("You do not have permission to manage the channel {$this->id}."));
}
}
if (is_string($category)) {
if ($cachedCategory = $this->guild->channels->get('id', $category)) {
$category = $cachedCategory;
}
}
if ($category instanceof Channel) {
if ($category->type !== self::TYPE_GUILD_CATEGORY) {
return reject(new \InvalidArgumentException('You can only move channel into a category.'));
}
if ($botperms = $category->getBotPermissions()) {
if (! $botperms->manage_channels) {
return reject(new NoPermissionsException("You do not have permission to manage the category channel {$category->id}."));
}
}
$category = $category->id;
}
$payload = ['parent_id' => $category];
if (null !== $position) {
$payload['position'] = $position;
}
$headers = [];
if (isset($reason)) {
$headers['X-Audit-Log-Reason'] = $reason;
}
return $this->http->patch(Endpoint::bind(Endpoint::CHANNEL, $this->id), $payload, $headers)->then(function ($response) {
$this->parent_id = $response->parent_id;
$this->position = $response->position;
return $this;
});
}
/**
* Moves a member to another voice channel.
*
* @param Member|string $member The member to move. (either a Member part or the member ID)
* @param string|null $reason Reason for Audit Log.
*
* @throws \RuntimeException
* @throws NoPermissionsException Missing move_members permission.
*
* @return ExtendedPromiseInterface
*/
public function moveMember($member, ?string $reason = null): ExtendedPromiseInterface
{
if (! $this->isVoiceBased()) {
return reject(new \RuntimeException('You cannot move a member in a text channel.'));
}
if ($botperms = $this->getBotPermissions()) {
if (! $botperms->move_members) {
return reject(new NoPermissionsException("You do not have permission to move members in the channel {$this->id}."));
}
}
if ($member instanceof Member) {
$member = $member->id;
}
$headers = [];
if (isset($reason)) {
$headers['X-Audit-Log-Reason'] = $reason;
}
return $this->http->patch(Endpoint::bind(Endpoint::GUILD_MEMBER, $this->guild_id, $member), ['channel_id' => $this->id], $headers);
}
/**
* Mutes a member on a voice channel.
*
* @param Member|string $member The member to mute. (either a Member part or the member ID)
* @param string|null $reason Reason for Audit Log.
*
* @throws \RuntimeException
* @throws NoPermissionsException Missing mute_members permission.
*
* @return ExtendedPromiseInterface
*/
public function muteMember($member, ?string $reason = null): ExtendedPromiseInterface
{
if (! $this->isVoiceBased()) {
return reject(new \RuntimeException('You cannot mute a member in a text channel.'));
}
if ($botperms = $this->getBotPermissions()) {
if (! $botperms->mute_members) {
return reject(new NoPermissionsException("You do not have permission to mute members in the channel {$this->id}."));
}
}
if ($member instanceof Member) {
$member = $member->id;
}
$headers = [];
if (isset($reason)) {
$headers['X-Audit-Log-Reason'] = $reason;
}
return $this->http->patch(Endpoint::bind(Endpoint::GUILD_MEMBER, $this->guild_id, $member), ['mute' => true], $headers);
}
/**
* Unmutes a member on a voice channel.
*
* @param Member|string $member The member to unmute. (either a Member part or the member ID)
* @param string|null $reason Reason for Audit Log.
*
* @throws \RuntimeException
* @throws NoPermissionsException Missing mute_members permission.
*
* @return ExtendedPromiseInterface
*/
public function unmuteMember($member, ?string $reason = null): ExtendedPromiseInterface
{
if (! $this->isVoiceBased()) {
return reject(new \RuntimeException('You cannot unmute a member in a text channel.'));
}
if ($botperms = $this->getBotPermissions()) {
if (! $botperms->mute_members) {
return reject(new NoPermissionsException("You do not have permission to unmute members in the channel {$this->id}."));
}
}
if ($member instanceof Member) {
$member = $member->id;
}
$headers = [];
if (isset($reason)) {
$headers['X-Audit-Log-Reason'] = $reason;
}
return $this->http->patch(Endpoint::bind(Endpoint::GUILD_MEMBER, $this->guild_id, $member), ['mute' => false], $headers);
}
/**
* Creates an invite for the channel.
*
* @link https://discord.com/developers/docs/resources/channel#create-channel-invite
*
* @param array $options An array of options. All fields are optional.
* @param int $options['max_age'] The time that the invite will be valid in seconds.
* @param int $options['max_uses'] The amount of times the invite can be used.
* @param bool $options['temporary'] Whether the invite is for temporary membership.
* @param bool $options['unique'] Whether the invite code should be unique (useful for creating many unique one time use invites).
* @param int $options['target_type'] The type of target for this voice channel invite.
* @param string $options['target_user_id'] The id of the user whose stream to display for this invite, required if target_type is `Invite::TARGET_TYPE_STREAM`, the user must be streaming in the channel.
* @param string $options['target_application_id'] The id of the embedded application to open for this invite, required if target_type is `Invite::TARGET_TYPE_EMBEDDED_APPLICATION`, the application must have the EMBEDDED flag.
* @param string|null $reason Reason for Audit Log.
*
* @throws NoPermissionsException Missing create_instant_invite permission.
*
* @return ExtendedPromiseInterface<Invite>
*/
public function createInvite($options = [], ?string $reason = null): ExtendedPromiseInterface
{
if (! $this->canInvite()) {
return reject(new \RuntimeException('You cannot create invite in this type of channel.'));
}
if ($botperms = $this->getBotPermissions()) {
if (! $botperms->create_instant_invite) {
return reject(new NoPermissionsException("You do not have permission to create instant invite in the channel {$this->id}."));
}
}
$resolver = new OptionsResolver();
$resolver
->setDefined([
'max_age',
'max_uses',
'temporary',
'unique',
'target_type',
'target_user_id',
'target_application_id',
])
->setAllowedTypes('max_age', 'int')
->setAllowedTypes('max_uses', 'int')
->setAllowedTypes('temporary', 'bool')
->setAllowedTypes('unique', 'bool')
->setAllowedTypes('target_type', 'int')
->setAllowedTypes('target_user_id', ['string', 'int'])
->setAllowedTypes('target_application_id', ['string', 'int'])
->setAllowedValues('max_age', fn ($value) => ($value >= 0 && $value <= 604800))
->setAllowedValues('max_uses', fn ($value) => ($value >= 0 && $value <= 100));
$options = $resolver->resolve($options);
$headers = [];
if (isset($reason)) {
$headers['X-Audit-Log-Reason'] = $reason;
}
return $this->http->post(Endpoint::bind(Endpoint::CHANNEL_INVITES, $this->id), $options, $headers)
->then(function ($response) {
/** @var ?Invite */
if (! $invitePart = $this->invites->get('code', $response->code)) {
/** @var Invite */
$invitePart = $this->invites->create($response, true);
$this->invites->pushItem($invitePart);
}
return $invitePart;
});
}
/**
* Bulk deletes an array of messages.
*
* @link https://discord.com/developers/docs/resources/channel#bulk-delete-messages
*
* @param array|Traversable $messages An array of messages to delete.
* @param string|null $reason Reason for Audit Log (only for bulk messages).
*
* @throws \InvalidArgumentException
* @throws NoPermissionsException Missing manage_messages permission.
*
* @return ExtendedPromiseInterface
*/
public function deleteMessages($messages, ?string $reason = null): ExtendedPromiseInterface
{
if (! is_array($messages) && ! ($messages instanceof Traversable)) {
return reject(new \InvalidArgumentException('$messages must be an array or implement Traversable.'));
}
if ($botperms = $this->getBotPermissions()) {
if (! $botperms->manage_messages) {
return reject(new NoPermissionsException("You do not have permission to delete messages in the channel {$this->id}."));
}
}
$headers = $promises = $messagesBulk = $messagesSingle = [];
if (isset($reason)) {
$headers['X-Audit-Log-Reason'] = $reason;
}
foreach ($messages as $message) {
if ($message instanceof Message) {
$message = $message->id;
}
if ($this->is_private || getSnowflakeTimestamp($message) < time() - 1209600) {
$messagesSingle[] = $message;
} else {
$messagesBulk[] = $message;
}
}
while (count($messagesBulk) > 1) {
$promises[] = $this->http->post(Endpoint::bind(Endpoint::CHANNEL_MESSAGES_BULK_DELETE, $this->id), ['messages' => array_slice($messagesBulk, 0, 100)], $headers);
$messagesBulk = array_slice($messagesBulk, 100);
}
$messagesSingle = array_merge($messagesSingle, $messagesBulk);
foreach ($messagesSingle as $message) {
$promises[] = $this->http->delete(Endpoint::bind(Endpoint::CHANNEL_MESSAGE, $this->id, $message));
}
return all($promises);
}
/**
* Deletes a given number of messages, in order of time sent.
*
* @link https://discord.com/developers/docs/resources/channel#bulk-delete-messages
*
* @param int $value
* @param string|null $reason Reason for Audit Log (only for bulk messages).
*
* @throws NoPermissionsException Missing manage_messages permission.
*
* @return ExtendedPromiseInterface
*/
public function limitDelete(int $value, ?string $reason = null): ExtendedPromiseInterface
{
if ($botperms = $this->getBotPermissions()) {
if (! $botperms->manage_messages) {
return reject(new NoPermissionsException("You do not have permission to delete messages in the channel {$this->id}."));
}
}
return $this->getMessageHistory(['limit' => $value, 'cache' => false])->then(fn ($messages) => $this->deleteMessages($messages, $reason));
}
/**
* Fetches message history.
*
* @link https://discord.com/developers/docs/resources/channel#get-channel-messages
*
* @param array $options Array of options.
* @param string|Message|null $options['around'] Get messages around this message ID.
* @param string|Message|null $options['before'] Get messages before this message ID.
* @param string|Message|null $options['after'] Get messages after this message ID.
* @param int|null $options['limit'] Max number of messages to return (1-100). Defaults to 50.
*
* @throws NoPermissionsException Missing `read_message_history` permission.
* Or also missing `connect` permission for text in voice.
* @throws \RangeException
*
* @return ExtendedPromiseInterface<Collection|Message[]>
*
* @todo Make it in a trait along with Thread
*/
public function getMessageHistory(array $options = []): ExtendedPromiseInterface
{
if (! $this->is_private && $botperms = $this->getBotPermissions()) {
if (! $botperms->read_message_history) {
return reject(new NoPermissionsException("You do not have permission to read message history in the channel {$this->id}."));
}
if ($this->type == self::TYPE_GUILD_VOICE && ! $botperms->connect) {
return reject(new NoPermissionsException("You do not have permission to connect in the channel {$this->id}."));
}
}
$resolver = new OptionsResolver();
$resolver->setDefaults(['limit' => 50, 'cache' => true]);
$resolver->setDefined(['before', 'after', 'around']);
$resolver->setAllowedTypes('before', [Message::class, 'string']);
$resolver->setAllowedTypes('after', [Message::class, 'string']);
$resolver->setAllowedTypes('around', [Message::class, 'string']);
$resolver->setAllowedTypes('limit', 'integer');
$resolver->setAllowedValues('limit', fn ($value) => ($value >= 1 && $value <= 100));
$options = $resolver->resolve($options);
if (isset($options['before'], $options['after']) ||
isset($options['before'], $options['around']) ||
isset($options['around'], $options['after'])) {
return reject(new \RangeException('Can only specify one of before, after and around.'));
}
$endpoint = Endpoint::bind(Endpoint::CHANNEL_MESSAGES, $this->id);
$endpoint->addQuery('limit', $options['limit']);
if (isset($options['before'])) {
$endpoint->addQuery('before', $options['before'] instanceof Message ? $options['before']->id : $options['before']);
}
if (isset($options['after'])) {
$endpoint->addQuery('after', $options['after'] instanceof Message ? $options['after']->id : $options['after']);
}
if (isset($options['around'])) {
$endpoint->addQuery('around', $options['around'] instanceof Message ? $options['around']->id : $options['around']);
}
return $this->http->get($endpoint)->then(function ($responses) {
$messages = Collection::for(Message::class);
foreach ($responses as $response) {
$messages->pushItem($this->messages->get('id', $response->id) ?: $this->messages->create($response, true));
}
return $messages;
});
}
/**
* Adds a message to the channels pinboard.
*
* @link https://discord.com/developers/docs/resources/channel#pin-message
*
* @param Message $message The message to pin.
* @param string|null $reason Reason for Audit Log.
*
* @throws NoPermissionsException Missing manage_messages permission.
* @throws \RuntimeException
*
* @return ExtendedPromiseInterface<Message>
*/
public function pinMessage(Message $message, ?string $reason = null): ExtendedPromiseInterface
{
if (! $this->is_private && $botperms = $this->getBotPermissions()) {
if (! $botperms->manage_messages) {
return reject(new NoPermissionsException("You do not have permission to pin messages in the channel {$this->id}."));
}
}
if ($message->pinned) {
return reject(new \RuntimeException('This message is already pinned.'));
}
if ($message->channel_id != $this->id) {
return reject(new \RuntimeException('You cannot pin a message to a different channel.'));
}
$headers = [];
if (isset($reason)) {
$headers['X-Audit-Log-Reason'] = $reason;
}
return $this->http->put(Endpoint::bind(Endpoint::CHANNEL_PIN, $this->id, $message->id), null, $headers)->then(function () use (&$message) {
$message->pinned = true;
return $message;
});
}
/**
* Removes a message from the channels pinboard.
*
* @link https://discord.com/developers/docs/resources/channel#unpin-message
*
* @param Message $message The message to un-pin.
* @param string|null $reason Reason for Audit Log.
*
* @throws NoPermissionsException Missing manage_messages permission.
* @throws \RuntimeException
*
* @return ExtendedPromiseInterface
*/
public function unpinMessage(Message $message, ?string $reason = null): ExtendedPromiseInterface
{
if (! $this->is_private && $botperms = $this->getBotPermissions()) {
if (! $botperms->manage_messages) {
return reject(new NoPermissionsException("You do not have permission to unpin messages in the channel {$this->id}."));
}
}
if (! $message->pinned) {
return reject(new \RuntimeException('This message is not pinned.'));
}
if ($message->channel_id != $this->id) {
return reject(new \RuntimeException('You cannot un-pin a message from a different channel.'));
}
$headers = [];
if (isset($reason)) {
$headers['X-Audit-Log-Reason'] = $reason;
}
return $this->http->delete(Endpoint::bind(Endpoint::CHANNEL_PIN, $this->id, $message->id), null, $headers)->then(function () use (&$message) {
$message->pinned = false;
return $message;
});
}
/**
* Sets the permission overwrites attribute.
*
* @param ?array $overwrites
*/
protected function setPermissionOverwritesAttribute(?array $overwrites): void
{
if ($overwrites) {
$overwritesDiscrim = $this->overwrites->discrim;
foreach ($overwrites as $overwrite) {
$overwrite = (array) $overwrite;
/** @var ?Overwrite */
if ($overwritePart = $this->overwrites->offsetGet($overwrite[$overwritesDiscrim])) {
$overwritePart->fill($overwrite);
} else {
/** @var Overwrite */
$overwritePart = $this->overwrites->create($overwrite, $this->created);
$overwritePart->created = &$this->created;
}
$this->overwrites->pushItem($overwritePart);
}
} else {
if (null === nowait($this->overwrites->cache->clear())) {
foreach ($this->overwrites->keys() as $key) {
$this->overwrites->offsetUnset($key);
}
}
}
$this->attributes['permission_overwrites'] = $overwrites;
}
/**
* Gets the permission overwrites attribute.
*
* @return ?array $overwrites
*/
protected function getPermissionOverwritesAttribute(): ?array
{
$overwrites = null;
/** @var Overwrite */
foreach ($this->overwrites as $overwrite) {
$overwrites[] = $overwrite->getRawAttributes();
}
return $overwrites ?? $this->attributes['permission_overwrites'] ?? null;
}
/**
* Gets the available tags attribute.
*
* @return Collection|Tag[] Available forum tags.
*
* @since 7.4.0
*/
protected function getAvailableTagsAttribute(): Collection
{
$available_tags = Collection::for(Tag::class);
foreach ($this->attributes['available_tags'] ?? [] as $available_tag) {
$available_tags->pushItem($this->createOf(Tag::class, $available_tag));
}
return $available_tags;
}
/**
* Gets the default reaction emoji attribute.
*
* @return Reaction|null Default forum reaction emoji.
*
* @since 7.4.0
*/
protected function getDefaultReactionEmojiAttribute(): ?Reaction
{
if (! isset($this->attributes['default_reaction_emoji'])) {
return null;
}
return $this->createOf(Reaction::class, $this->attributes['default_reaction_emoji']);
}
/**
* Starts a thread in the channel.
*
* @link https://discord.com/developers/docs/resources/channel#start-thread-without-message
* @link https://discord.com/developers/docs/resources/channel#start-thread-in-forum-channel
*
* @param array $options Thread params.
* @param bool $options['private'] Whether the thread should be private. Cannot start a private thread in a news channel. Ignored in forum channel.
* @param string $options['name'] The name of the thread.
* @param int|null $options['auto_archive_duration'] Number of minutes of inactivity until the thread is auto-archived. one of 60, 1440, 4320, 10080.
* @param bool|null $options['invitable'] Whether non-moderators can add other non-moderators to a thread; only available when creating a private thread.
* @param ?int|null $options['rate_limit_per_user'] Amount of seconds a user has to wait before sending another message (0-21600).
* @param MessageBuilder $options['message'] Contents of the first message in the forum thread.
* @param string[]|null $options['applied_tags'] The IDs of the set of tags that have been applied to a thread in a forum channel, limited to 5.
* @param string|null $reason Reason for Audit Log.
*
* @throws \RuntimeException
* @throws NoPermissionsException Missing various permissions:
* create_private_threads when creating a private thread.
* create_public_threads when creating a public thread.
* send_messages when creating a forum post.
*
* @return ExtendedPromiseInterface<Thread>
*
* @since 10.0.0 Arguments for `$name`, `$private` and `$auto_archive_duration` are now inside `$options`
*/
public function startThread(array|string $options, string|null|bool $reason = null, int $_auto_archive_duration = 1440, ?string $_reason = null): ExtendedPromiseInterface
{
// Old v7 signature
if (is_string($options)) {
$options = [
'name' => $options,
'auto_archive_duration' => $_auto_archive_duration,
];
if (is_bool($reason)) {
$options['private'] = $reason;
}
$reason = $_reason;
}
$resolver = new OptionsResolver();
$resolver