/
channel.py
1995 lines (1653 loc) · 72.6 KB
/
channel.py
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
from asyncio import Task, create_task, get_running_loop, sleep
from datetime import datetime, timedelta, timezone
from enum import IntEnum
from inspect import isawaitable
from math import inf
from typing import (
TYPE_CHECKING,
Any,
Awaitable,
Callable,
ContextManager,
Iterable,
List,
Literal,
Optional,
Union,
)
from warnings import warn
from ...utils.abc.base_context_managers import BaseAsyncContextManager
from ...utils.abc.base_iterators import DiscordPaginationIterator
from ...utils.attrs_utils import (
ClientSerializerMixin,
DictSerializerMixin,
convert_list,
define,
field,
)
from ...utils.missing import MISSING
from ...utils.utils import search_iterable
from ..error import LibraryException
from .emoji import Emoji
from .flags import Permissions
from .misc import AllowedMentions, File, IDMixin, Overwrite, Snowflake
from .role import Role
from .user import User
from .webhook import Webhook
if TYPE_CHECKING:
from ...client.models.component import ActionRow, Button, SelectMenu
from ..http.client import HTTPClient
from .guild import Guild, Invite, InviteTargetType
from .gw import VoiceState
from .member import Member
from .message import Attachment, Embed, Message, Sticker
__all__ = (
"ChannelType",
"Thread",
"Channel",
"ThreadMember",
"ThreadMetadata",
"AsyncHistoryIterator",
"AsyncTypingContextManager",
"Tags",
)
class ChannelType(IntEnum):
"""An enumerable object representing the type of channels."""
GUILD_TEXT = 0
DM = 1
GUILD_VOICE = 2
GROUP_DM = 3
GUILD_CATEGORY = 4
GUILD_ANNOUNCEMENT = 5
GUILD_STORE = 6
ANNOUNCEMENT_THREAD = 10
PUBLIC_THREAD = 11
PRIVATE_THREAD = 12
GUILD_STAGE_VOICE = 13
GUILD_DIRECTORY = 14
GUILD_FORUM = 15
@define()
class ThreadMetadata(DictSerializerMixin):
"""
A class object representing the metadata of a thread.
.. note::
``invitable`` will only show if the thread can have an invited created with the
current cached permissions.
:ivar bool archived: The current thread accessibility state.
:ivar int auto_archive_duration: The auto-archive time.
:ivar datetime archive_timestamp: The timestamp that the thread will be/has been closed at.
:ivar bool locked: The current message state of the thread.
:ivar Optional[bool] invitable: The ability to invite users to the thread.
"""
archived: bool = field()
auto_archive_duration: int = field()
archive_timestamp: datetime = field(converter=datetime.fromisoformat, repr=False)
locked: bool = field()
invitable: Optional[bool] = field(default=None)
@define()
class ThreadMember(ClientSerializerMixin):
"""
A class object representing a member in a thread.
.. note::
``id`` only shows if there are active intents involved with the member
in the thread.
:ivar Optional[Snowflake] id: The "ID" or intents of the member.
:ivar Snowflake user_id: The user ID of the member.
:ivar datetime join_timestamp: The timestamp of when the member joined the thread.
:ivar int flags: The bitshift flags for the member in the thread.
:ivar bool muted: Whether the member is muted or not.
"""
id: Optional[Snowflake] = field(converter=Snowflake, default=None, repr=False)
user_id: Optional[Snowflake] = field(converter=Snowflake, default=None)
join_timestamp: datetime = field(converter=datetime.fromisoformat, repr=False)
flags: int = field(repr=False)
muted: bool = field()
mute_config: Optional[Any] = field(
default=None, repr=False
) # todo explore this, it isn't in the ddev docs
class AsyncHistoryIterator(DiscordPaginationIterator):
"""
A class object that allows iterating through a channel's history.
:param HTTPClient _client: The HTTPClient of the bot
:param Union[int, str, Snowflake, Channel] obj: The channel to get the history from
:param Optional[Union[int, str, Snowflake, Message]] start_at: The message to begin getting the history from
:param Optional[bool] reverse: Whether to only get newer message. Default False
:param Optional[Callable[[Message], Union[bool, Awaitable[bool]]]] check: A check to ignore certain messages
:param Optional[int] maximum: A set maximum of messages to get before stopping the iteration
"""
def __init__(
self,
_client: "HTTPClient",
obj: Union[int, str, Snowflake, "Channel"],
maximum: Optional[int] = inf,
start_at: Optional[Union[int, str, Snowflake, "Message"]] = MISSING,
check: Optional[Callable[["Message"], Union[bool, Awaitable[bool]]]] = None,
reverse: Optional[bool] = False,
):
super().__init__(obj, _client, maximum=maximum, start_at=start_at, check=check)
self.__stop: bool = False
from .message import Message
if reverse and start_at is MISSING:
raise LibraryException(
code=12,
message="A message to start from is required to go through the channel in reverse.",
)
if reverse:
self.before = MISSING
self.after = self.start_at
else:
self.before = self.start_at
self.after = MISSING
self.objects: Optional[List[Message]]
async def get_first_objects(self) -> None:
from .message import Message
limit = min(self.maximum, 100)
if self.maximum == limit:
self.__stop = True
if self.after is not MISSING:
msgs = await self._client.get_channel_messages(
channel_id=self.object_id, after=self.after, limit=limit
)
msgs.reverse()
self.after = int(msgs[-1]["id"])
else:
msgs = await self._client.get_channel_messages(
channel_id=self.object_id, before=self.before, limit=limit
)
self.before = int(msgs[-1]["id"])
if len(msgs) < 100:
# already all messages resolved with one operation
self.__stop = True
self.object_count += limit
self.objects = [Message(**msg, _client=self._client) for msg in msgs]
async def flatten(self) -> List["Message"]:
"""Returns all remaining items as list"""
return [item async for item in self]
async def get_objects(self) -> None:
from .message import Message
limit = min(50, self.maximum - self.object_count)
if self.after is not MISSING:
msgs = await self._client.get_channel_messages(
channel_id=self.object_id, after=self.after, limit=limit
)
msgs.reverse()
self.after = int(msgs[-1]["id"])
else:
msgs = await self._client.get_channel_messages(
channel_id=self.object_id, before=self.before, limit=limit
)
self.before = int(msgs[-1]["id"])
if len(msgs) < limit or limit == self.maximum - self.object_count:
# end of messages reached again
self.__stop = True
self.object_count += limit
self.objects.extend([Message(**msg, _client=self._client) for msg in msgs])
async def __anext__(self) -> "Message":
try:
if self.objects is None:
await self.get_first_objects()
obj = self.objects.pop(0)
if self.check:
res = self.check(obj)
_res = await res if isawaitable(res) else res
while not _res:
if (
not self.__stop
and len(self.objects) < 5
and self.object_count >= self.maximum
):
await self.get_objects()
self.object_count -= 1
obj = self.objects.pop(0)
_res = self.check(obj)
if not self.__stop and len(self.objects) < 5 and self.object_count <= self.maximum:
await self.get_objects()
except IndexError as e:
raise StopAsyncIteration from e
else:
return obj
class AsyncTypingContextManager(BaseAsyncContextManager):
"""
An async context manager for triggering typing.
:param Union[int, str, Snowflake, Channel] obj: The channel to trigger typing in.
:param HTTPClient _client: The HTTPClient of the bot
"""
def __init__(
self,
obj: Union[int, str, "Snowflake", "Channel"],
_client: "HTTPClient",
):
try:
self.loop = get_running_loop()
except RuntimeError as e:
raise RuntimeError("No running event loop detected!") from e
self.object_id = (int(obj.id) if hasattr(obj, "id") else int(obj)) if obj else None
self._client = _client
self.__task: Optional[Task] = None
def __await__(self):
return self._client.trigger_typing(self.object_id).__await__()
async def do_action(self):
while True:
await self._client.trigger_typing(self.object_id)
await sleep(8)
async def __aenter__(self):
self.__task = create_task(self.do_action())
async def __aexit__(self, exc_type, exc_val, exc_tb):
self.__task.cancel()
@define()
class Tags(ClientSerializerMixin): # helpers, hehe :D
"""
An object denoting a tag object within a forum channel.
.. note::
If the emoji is custom, it won't have name information.
:ivar str name: Name of the tag. The limit is up to 20 characters.
:ivar int id: ID of the tag. Can also be 0 if manually created.
:ivar bool moderated: A boolean denoting whether this tag can be removed/added by moderators with the :attr:`.Permissions.MANAGE_THREADS` permission.
:ivar Optional[Emoji] emoji: The emoji to represent the tag, if any.
"""
# TODO: Rename these to discord-docs
name: str = field()
id: int = field()
moderated: bool = field()
emoji: Optional[Emoji] = field(converter=Emoji, default=None)
# Maybe on post_attrs_init replace emoji object with one from cache for name population?
async def delete(
self, channel_id: Union[int, str, Snowflake, "Channel"] # discord, why :hollow:
) -> None:
"""
Deletes this tag
:param Union[int, str, Snowflake, Channel] channel_id: The ID of the channel where the tag belongs to
"""
if isinstance(channel_id, Channel) and channel_id.type != ChannelType.GUILD_FORUM:
raise LibraryException(code=14, message="Can only manage tags on a forum channel")
if not self._client:
raise LibraryException(code=13)
_channel_id = int(channel_id.id) if isinstance(channel_id, Channel) else int(channel_id)
return await self._client.delete_tag(_channel_id, int(self.id))
async def edit(
self,
channel_id: Union[int, str, Snowflake, "Channel"], # discord, why :hollow:
name: str,
emoji_name: Optional[str] = MISSING,
emoji_id: Optional[int] = MISSING,
) -> "Tags":
"""
Edits this tag
.. note::
Can either have an emoji_id or an emoji_name, but not both.
emoji_id is meant for custom emojis, emoji_name is meant for unicode emojis.
:param Union[int, str, Snowflake, Channel] channel_id: The ID of the channel where the tag belongs to
:param str name: The new name of the tag
:param Optional[int] emoji_id: The ID of the emoji to use for the tag
:param Optional[int] emoji_name: The name of the emoji to use for the tag
:return: The modified tag
:rtype: Tags
"""
if isinstance(channel_id, Channel) and channel_id.type != ChannelType.GUILD_FORUM:
raise LibraryException(code=14, message="Can only manage tags on a forum channel")
if not self._client:
raise LibraryException(code=13)
_channel_id = int(channel_id.id) if isinstance(channel_id, Channel) else int(channel_id)
payload = {"name": name}
if emoji_id is not MISSING and emoji_id and emoji_name and emoji_name is not MISSING:
raise LibraryException(
code=12, message="emoji_id and emoji_name are mutually exclusive"
)
if emoji_id is not MISSING:
payload["emoji_id"] = emoji_id
if emoji_name is not MISSING:
payload["emoji_name"] = emoji_name
data = await self._client.edit_tag(_channel_id, int(self.id), **payload)
return Tags(**data)
@define()
class Channel(ClientSerializerMixin, IDMixin):
"""
A class object representing all types of channels.
:ivar Snowflake id: The (snowflake) ID of the channel.
:ivar ChannelType type: The type of channel.
:ivar Optional[Snowflake] guild_id: The ID of the guild if it is not a DM channel.
:ivar Optional[int] position: The position of the channel.
:ivar List[Overwrite] permission_overwrites: The non-synced permissions of the channel.
:ivar str name: The name of the channel.
:ivar Optional[str] topic: The description of the channel.
:ivar Optional[bool] nsfw: Whether the channel is NSFW.
:ivar Snowflake last_message_id: The ID of the last message sent.
:ivar Optional[int] bitrate: The audio bitrate of the channel.
:ivar Optional[int] user_limit: The maximum amount of users allowed in the channel.
:ivar Optional[int] rate_limit_per_user: The concurrent ratelimit for users in the channel.
:ivar Optional[List[User]] recipients: The recipients of the channel.
:ivar Optional[str] icon: The icon of the channel.
:ivar Optional[Snowflake] owner_id: The owner of the channel.
:ivar Optional[Snowflake] application_id: The application of the channel.
:ivar Optional[Snowflake] parent_id: The ID of the "parent"/main channel.
:ivar Optional[datetime] last_pin_timestamp: The timestamp of the last pinned message in the channel.
:ivar Optional[str] rtc_region: The region of the WebRTC connection for the channel.
:ivar Optional[int] video_quality_mode: The set quality mode for video streaming in the channel.
:ivar int message_count: The amount of messages in the channel.
:ivar Optional[int] member_count: The amount of members in the channel.
:ivar Optional[bool] newly_created: Boolean representing if a thread is created.
:ivar Optional[ThreadMetadata] thread_metadata: The thread metadata of the channel.
:ivar Optional[ThreadMember] member: The member of the thread in the channel.
:ivar Optional[int] default_auto_archive_duration: The set auto-archive time for all threads to naturally follow in the channel.
:ivar Optional[str] permissions: The permissions of the channel.
:ivar Optional[int] flags: The flags of the channel.
:ivar Optional[int] total_message_sent: Number of messages ever sent in a thread.
:ivar Optional[int] default_thread_slowmode_delay: The default slowmode delay in seconds for threads, if this channel is a forum.
:ivar Optional[List[Tags]] available_tags: Tags in a forum channel, if any.
:ivar Optional[Emoji] default_reaction_emoji: Default reaction emoji for threads created in a forum, if any.
"""
# Template attribute isn't live/documented, this line exists as a placeholder 'TODO' of sorts
__slots__ = (
# TODO: Document banner when Discord officially documents them.
"banner",
"guild_hashes",
)
type: ChannelType = field(converter=ChannelType)
id: Snowflake = field(converter=Snowflake)
_guild_id: Optional[Snowflake] = field(
converter=Snowflake, default=None, discord_name="guild_id"
)
position: Optional[int] = field(default=None)
permission_overwrites: Optional[List[Overwrite]] = field(
converter=convert_list(Overwrite), factory=list
)
name: str = field(factory=str)
topic: Optional[str] = field(default=None)
nsfw: Optional[bool] = field(default=None)
last_message_id: Optional[Snowflake] = field(converter=Snowflake, default=None, repr=False)
bitrate: Optional[int] = field(default=None, repr=False)
user_limit: Optional[int] = field(default=None)
rate_limit_per_user: Optional[int] = field(default=None)
recipients: Optional[List[User]] = field(converter=convert_list(User), default=None, repr=False)
icon: Optional[str] = field(default=None, repr=False)
owner_id: Optional[Snowflake] = field(converter=Snowflake, default=None)
application_id: Optional[Snowflake] = field(converter=Snowflake, default=None, repr=False)
parent_id: Optional[Snowflake] = field(converter=Snowflake, default=None)
last_pin_timestamp: Optional[datetime] = field(
converter=datetime.fromisoformat, default=None, repr=False
)
rtc_region: Optional[str] = field(default=None, repr=False)
video_quality_mode: Optional[int] = field(default=None, repr=False)
message_count: Optional[int] = field(default=None, repr=False)
member_count: Optional[int] = field(default=None, repr=False)
newly_created: Optional[int] = field(default=None, repr=False)
thread_metadata: Optional[ThreadMetadata] = field(converter=ThreadMetadata, default=None)
member: Optional[ThreadMember] = field(
converter=ThreadMember, default=None, add_client=True, repr=False
)
default_auto_archive_duration: Optional[int] = field(default=None)
permissions: Optional[str] = field(default=None, repr=False)
flags: Optional[int] = field(default=None, repr=False)
total_message_sent: Optional[int] = field(default=None, repr=False)
default_thread_slowmode_delay: Optional[int] = field(default=None, repr=False)
available_tags: Optional[List[Tags]] = field(
converter=convert_list(Tags), default=None, add_client=True
) # eh?
default_reaction_emoji: Optional[Emoji] = field(converter=Emoji, default=None)
def __attrs_post_init__(self): # sourcery skip: last-if-guard
if self._client:
if channel := self._client.cache[Channel].get(self.id):
if not self.recipients:
self.recipients = channel.recipients
@property
def guild_id(self) -> Optional[Snowflake]:
"""
.. versionadded:: 4.4.0
Attempts to get the guild ID the channel is in.
:return: The ID of the guild this channel belongs to.
:rtype: Optional[Snowflake]
"""
if self._guild_id:
return self._guild_id
elif _id := self._extras.get("guild_id"):
return Snowflake(_id)
if not self._client:
raise LibraryException(code=13)
from .guild import Guild
def check(channel: Channel):
return self.id == channel.id
for guild in self._client.cache[Guild].values.values():
if len(search_iterable(guild.channels, check=check)) == 1:
self._extras["guild_id"] = guild.id
return guild.id
@property
def guild(self) -> Optional["Guild"]:
"""
.. versionadded:: 4.4.0
Attempts to get the guild the channel is in.
:return: The guild this channel belongs to.
:rtype: Guild
"""
_id = self.guild_id
from .guild import Guild
return self._client.cache[Guild].get(_id, None) if _id else None
@property
def typing(self) -> Union[Awaitable, ContextManager]:
"""
Manages the typing of the channel. Use with `await` or `async with`
:return: A manager for typing
:rtype: AsyncTypingContextManager
"""
return AsyncTypingContextManager(self, self._client)
@property
def mention(self) -> str:
"""
Returns a string that allows you to mention the given channel.
:return: The string of the mentioned channel.
:rtype: str
"""
return f"<#{self.id}>"
@property
def voice_states(self) -> List["VoiceState"]:
"""
Returns all voice states this channel has. Only applicable for voice channels.
:rtype: List[VoiceState]
"""
if self.type != ChannelType.GUILD_VOICE:
raise LibraryException(
code=14, message="Cannot only get voice states from a voice channel!"
)
if not self._client:
raise LibraryException(code=13)
from .gw import VoiceState
states: List[VoiceState] = []
data = self._client.cache[VoiceState].values.values()
states.extend(state for state in data if state.channel_id == self.id)
return states
def history(
self,
start_at: Optional[Union[int, str, Snowflake, "Message"]] = MISSING,
reverse: Optional[bool] = False,
maximum: Optional[int] = inf,
check: Optional[Callable[["Message"], Union[bool, Awaitable[bool]]]] = None,
) -> AsyncHistoryIterator:
"""
:param Optional[Union[int, str, Snowflake, Message]] start_at: The message to begin getting the history from
:param Optional[bool] reverse: Whether to only get newer message. Default False
:param Optional[int] maximum: A set maximum of messages to get before stopping the iteration
:param Optional[Callable[[Message], Union[bool, Awaitable[bool]]]] check: A custom check to ignore certain messages
:return: An asynchronous iterator over the history of the channel
:rtype: AsyncHistoryIterator
"""
if not self._client:
raise LibraryException(code=13)
return AsyncHistoryIterator(
self._client, self, start_at=start_at, reverse=reverse, maximum=maximum, check=check
)
async def send(
self,
content: Optional[str] = MISSING,
*,
tts: Optional[bool] = MISSING,
attachments: Optional[List["Attachment"]] = MISSING,
files: Optional[Union[File, List[File]]] = MISSING,
embeds: Optional[Union["Embed", List["Embed"]]] = MISSING,
allowed_mentions: Optional[Union[AllowedMentions, dict]] = MISSING,
stickers: Optional[List["Sticker"]] = MISSING,
components: Optional[
Union[
"ActionRow",
"Button",
"SelectMenu",
List["ActionRow"],
List["Button"],
List["SelectMenu"],
]
] = MISSING,
) -> "Message": # noqa # sourcery skip: dict-assign-update-to-union
"""
Sends a message in the channel.
:param Optional[str] content: The contents of the message as a string or string-converted value.
:param Optional[bool] tts: Whether the message utilizes the text-to-speech Discord programme or not.
:param Optional[Union[File, List[File]]] files: A file or list of files to be attached to the message.
:param Optional[List[Attachment]] attachments: The attachments to attach to the message. Needs to be uploaded to the CDN first
:param Optional[Union[Embed, List[Embed]]] embeds: An embed, or list of embeds for the message.
:param Optional[Union[AllowedMentions, dict]] allowed_mentions: The allowed mentions for the message.
:param Optional[List[Sticker]] stickers: A list of stickers to send with your message. You can send up to 3 stickers per message.
:param Optional[Union[ActionRow, Button, SelectMenu, List[Actionrow], List[Button], List[SelectMenu]]] components: A component, or list of components for the message.
:return: The sent message as an object.
:rtype: Message
"""
if self.type == ChannelType.GUILD_FORUM:
raise LibraryException(code=14, message="Cannot message a forum channel!")
if not self._client:
raise LibraryException(code=13)
from ...client.models.component import _build_components
from .message import Message
_content: str = "" if content is MISSING else content
_tts: bool = False if tts is MISSING else tts
_attachments = [] if attachments is MISSING else [a._json for a in attachments]
_allowed_mentions: dict = (
{}
if allowed_mentions is MISSING
else allowed_mentions._json
if isinstance(allowed_mentions, AllowedMentions)
else allowed_mentions
)
_sticker_ids: list = (
[] if stickers is MISSING else [str(sticker.id) for sticker in stickers]
)
if not embeds or embeds is MISSING:
_embeds: list = []
elif isinstance(embeds, list):
_embeds = [embed._json for embed in embeds]
else:
_embeds = [embeds._json]
if not components or components is MISSING:
_components = []
else:
_components = _build_components(components=components)
if not files or files is MISSING:
_files = []
elif isinstance(files, list):
_files = [file._json_payload(id) for id, file in enumerate(files)]
else:
_files = [files._json_payload(0)]
files = [files]
_files.extend(_attachments)
payload = dict(
content=_content,
tts=_tts,
attachments=_files,
embeds=_embeds,
allowed_mentions=_allowed_mentions,
components=_components,
sticker_ids=_sticker_ids,
)
res = await self._client.create_message(
channel_id=int(self.id), payload=payload, files=files
)
# dumb hack, discord doesn't send the full author data
author = {"id": None, "username": None, "discriminator": None}
author.update(res["author"])
res["author"] = author
return Message(**res, _client=self._client)
async def delete(self) -> None:
"""
Deletes the channel.
"""
if not self._client:
raise LibraryException(code=13)
await self._client.delete_channel(channel_id=int(self.id))
async def modify(
self,
name: Optional[str] = MISSING,
topic: Optional[str] = MISSING,
bitrate: Optional[int] = MISSING,
user_limit: Optional[int] = MISSING,
rate_limit_per_user: Optional[int] = MISSING,
position: Optional[int] = MISSING,
permission_overwrites: Optional[List[Overwrite]] = MISSING,
parent_id: Optional[int] = MISSING,
nsfw: Optional[bool] = MISSING,
archived: Optional[bool] = MISSING,
auto_archive_duration: Optional[int] = MISSING,
locked: Optional[bool] = MISSING,
reason: Optional[str] = None,
) -> "Channel": # sourcery skip: low-code-quality
"""
Edits the channel.
.. note::
The fields ``archived``, ``auto_archive_duration`` and ``locked`` require the provided channel to be a thread.
:param Optional[str] name: The name of the channel, defaults to the current value of the channel
:param Optional[str] topic: The topic of that channel, defaults to the current value of the channel
:param Optional[int] bitrate: (voice channel only) The bitrate (in bits) of the voice channel, defaults to the current value of the channel
:param Optional[int] user_limit: (voice channel only) Maximum amount of users in the channel, defaults to the current value of the channel
:param Optional[int] rate_limit_per_user: Amount of seconds a user has to wait before sending another message (0-21600), defaults to the current value of the channel
:param Optional[int] position: Sorting position of the channel, defaults to the current value of the channel
:param Optional[int] parent_id: The id of the parent category for a channel, defaults to the current value of the channel
:param Optional[bool] nsfw: Whether the channel is nsfw or not, defaults to the current value of the channel
:param Optional[List[Overwrite]] permission_overwrites: The permission overwrites, if any
:param Optional[bool] archived: Whether the thread is archived
:param Optional[int] auto_archive_duration: The time after the thread is automatically archived. One of 60, 1440, 4320, 10080
:param Optional[bool] locked: Whether the thread is locked
:param Optional[str] reason: The reason for the edit
:return: The modified channel as new object
:rtype: Channel
"""
if not self._client:
raise LibraryException(code=13)
_name = self.name if name is MISSING else name
_topic = self.topic if topic is MISSING else topic
_bitrate = self.bitrate if bitrate is MISSING else bitrate
_user_limit = self.user_limit if user_limit is MISSING else user_limit
_rate_limit_per_user = (
self.rate_limit_per_user if rate_limit_per_user is MISSING else rate_limit_per_user
)
_position = self.position if position is MISSING else position
_parent_id = (
(int(self.parent_id) if self.parent_id else None)
if parent_id is MISSING
else int(parent_id)
)
_nsfw = self.nsfw if nsfw is MISSING else nsfw
_permission_overwrites = (
[overwrite._json for overwrite in permission_overwrites]
if permission_overwrites is not MISSING
else [overwrite._json for overwrite in self.permission_overwrites]
if self.permission_overwrites
else None
)
_type = self.type
payload = dict(
name=_name,
type=_type,
topic=_topic,
bitrate=_bitrate,
user_limit=_user_limit,
rate_limit_per_user=_rate_limit_per_user,
position=_position,
parent_id=_parent_id,
nsfw=_nsfw,
permission_overwrites=_permission_overwrites,
)
if (
archived is not MISSING or auto_archive_duration is not MISSING or locked is not MISSING
) and not self.thread_metadata:
raise LibraryException(message="The specified channel is not a Thread!", code=12)
if archived is not MISSING:
payload["archived"] = archived
if auto_archive_duration is not MISSING:
payload["auto_archive_duration"] = auto_archive_duration
if locked is not MISSING:
payload["locked"] = locked
res = await self._client.modify_channel(
channel_id=int(self.id),
reason=reason,
payload=payload,
)
self.update(res)
return self
async def set_name(
self,
name: str,
*,
reason: Optional[str] = None,
) -> "Channel":
"""
Sets the name of the channel.
:param str name: The new name of the channel
:param Optional[str] reason: The reason of the edit
:return: The edited channel
:rtype: Channel
"""
return await self.modify(name=name, reason=reason)
async def set_topic(
self,
topic: str,
*,
reason: Optional[str] = None,
) -> "Channel":
"""
Sets the topic of the channel.
:param str topic: The new topic of the channel
:param Optional[str] reason: The reason of the edit
:return: The edited channel
:rtype: Channel
"""
return await self.modify(topic=topic, reason=reason)
async def set_bitrate(
self,
bitrate: int,
*,
reason: Optional[str] = None,
) -> "Channel":
"""
Sets the bitrate of the channel.
:param int bitrate: The new bitrate of the channel
:param Optional[str] reason: The reason of the edit
:return: The edited channel
:rtype: Channel
"""
if self.type != ChannelType.GUILD_VOICE:
raise LibraryException(message="Bitrate is only available for VoiceChannels", code=12)
return await self.modify(bitrate=bitrate, reason=reason)
async def set_user_limit(
self,
user_limit: int,
*,
reason: Optional[str] = None,
) -> "Channel":
"""
Sets the user_limit of the channel.
:param int user_limit: The new user limit of the channel
:param Optional[str] reason: The reason of the edit
:return: The edited channel
:rtype: Channel
"""
if self.type != ChannelType.GUILD_VOICE:
raise LibraryException(
message="user_limit is only available for VoiceChannels", code=12
)
return await self.modify(user_limit=user_limit, reason=reason)
async def set_rate_limit_per_user(
self,
rate_limit_per_user: int,
*,
reason: Optional[str] = None,
) -> "Channel":
"""
Sets the amount of seconds a user has to wait before sending another message.
:param int rate_limit_per_user: The new rate_limit_per_user of the channel (0-21600)
:param Optional[str] reason: The reason of the edit
:return: The edited channel
:rtype: Channel
"""
return await self.modify(rate_limit_per_user=rate_limit_per_user, reason=reason)
async def set_position(
self,
position: int,
*,
reason: Optional[str] = None,
) -> "Channel":
"""
Sets the position of the channel.
:param int position: The new position of the channel
:param Optional[str] reason: The reason of the edit
:return: The edited channel
:rtype: Channel
"""
return await self.modify(position=position, reason=reason)
async def set_parent_id(
self,
parent_id: int,
*,
reason: Optional[str] = None,
) -> "Channel":
"""
Sets the parent_id of the channel.
:param int parent_id: The new parent_id of the channel
:param Optional[str] reason: The reason of the edit
:return: The edited channel
:rtype: Channel
"""
return await self.modify(parent_id=parent_id, reason=reason)
async def set_nsfw(
self,
nsfw: bool,
*,
reason: Optional[str] = None,
) -> "Channel":
"""
Sets the nsfw-flag of the channel.
:param bool nsfw: The new nsfw-flag of the channel
:param Optional[str] reason: The reason of the edit
:return: The edited channel
:rtype: Channel
"""
return await self.modify(nsfw=nsfw, reason=reason)
async def archive(
self,
archived: bool = True,
*,
reason: Optional[str] = None,
) -> "Channel":
"""
Sets the archived state of the thread.
:param bool archived: Whether the Thread is archived, defaults to True
:param Optional[str] reason: The reason of the archiving
:return: The edited channel
:rtype: Channel
"""
return await self.modify(archived=archived, reason=reason)
async def set_auto_archive_duration(
self,
auto_archive_duration: int,
*,
reason: Optional[str] = None,
) -> "Channel":
"""
Sets the time after the thread is automatically archived.
:param int auto_archive_duration: The time after the thread is automatically archived. One of 60, 1440, 4320, 10080
:param Optional[str] reason: The reason of the edit
:return: The edited channel
:rtype: Channel
"""
return await self.modify(auto_archive_duration=auto_archive_duration, reason=reason)
async def lock(
self,
locked: bool = True,
*,
reason: Optional[str] = None,
) -> "Channel":
"""
Sets the locked state of the thread.
:param bool locked: Whether the Thread is locked, defaults to True
:param Optional[str] reason: The reason of the edit
:return: The edited channel
:rtype: Channel
"""
return await self.modify(locked=locked, reason=reason)
async def add_member(
self,
member_id: Union[int, Snowflake, "Member"],
) -> None:
"""
This adds a member to the channel, if the channel is a thread.
:param int member_id: The id of the member to add to the channel
"""