/
channel.py
962 lines (852 loc) · 34.5 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
from datetime import datetime, timedelta, timezone
from enum import IntEnum
from typing import Callable, List, Optional, Union
from .misc import MISSING, DictSerializerMixin, Snowflake
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_NEWS = 5
GUILD_STORE = 6
GUILD_NEWS_THREAD = 10
GUILD_PUBLIC_THREAD = 11
GUILD_PRIVATE_THREAD = 12
GUILD_STAGE_VOICE = 13
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.
"""
__slots__ = (
"_json",
"archived",
"auto_archive_duration",
"archive_timestamp",
"locked",
"invitable",
)
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.archive_timestamp = (
datetime.fromisoformat(self._json.get("archive_timestamp"))
if self._json.get("archive_timestamp")
else datetime.utcnow()
)
class ThreadMember(DictSerializerMixin):
"""
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.
"""
__slots__ = (
"_json",
"id",
"user_id",
"join_timestamp",
"flags",
# TODO: Document below attributes.
"user",
"team_id",
"membership_state",
"permissions",
)
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.id = Snowflake(self.id) if self._json.get("id") else None
self.user_id = Snowflake(self.user_id) if self._json.get("user_id") else None
self.join_timestamp = (
datetime.fromisoformat(self._json.get("join_timestamp"))
if self._json.get("join_timestamp")
else None
)
class Channel(DictSerializerMixin):
"""
A class object representing all types of channels.
.. note::
The purpose of this model is to be used as a base class, and
is never needed to be used directly.
: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[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.
"""
__slots__ = (
"_json",
"id",
"type",
"guild_id",
"position",
"permission_overwrites",
"name",
"topic",
"nsfw",
"last_message_id",
"bitrate",
"user_limit",
"rate_limit_per_user",
"recipients",
"icon",
"owner_id",
"application_id",
"parent_id",
"last_pin_timestamp",
"rtc_region",
"video_quality_mode",
"message_count",
"member_count",
"thread_metadata",
"member",
"default_auto_archive_duration",
"permissions",
"_client",
# TODO: Document banner when Discord officially documents them.
"banner",
"guild_hashes",
)
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.type = ChannelType(self.type)
self.id = Snowflake(self.id) if self._json.get("id") else None
self.guild_id = Snowflake(self.guild_id) if self._json.get("guild_id") else None
self.last_message_id = (
Snowflake(self.last_message_id) if self._json.get("last_message_id") else None
)
self.owner_id = Snowflake(self.owner_id) if self._json.get("owner_id") else None
self.application_id = (
Snowflake(self.application_id) if self._json.get("application_id") else None
)
self.parent_id = Snowflake(self.parent_id) if self._json.get("parent_id") else None
self.last_pin_timestamp = (
datetime.fromisoformat(self._json.get("last_pin_timestamp"))
if self._json.get("last_pin_timestamp")
else None
)
@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}>"
async def send(
self,
content: Optional[str] = MISSING,
*,
tts: Optional[bool] = MISSING,
# attachments: Optional[List[Any]] = None, # TODO: post-v4: Replace with own file type.
embeds: Optional[Union["Embed", List["Embed"]]] = MISSING, # noqa
allowed_mentions: Optional["MessageInteraction"] = MISSING, # noqa
components: Optional[
Union[
"ActionRow", # noqa
"Button", # noqa
"SelectMenu", # noqa
List["ActionRow"], # noqa
List["Button"], # noqa
List["SelectMenu"], # noqa
]
] = MISSING,
) -> "Message": # noqa
"""
Sends a message in the channel.
:param content?: The contents of the message as a string or string-converted value.
:type content: Optional[str]
:param tts?: Whether the message utilizes the text-to-speech Discord programme or not.
:type tts: Optional[bool]
:param embeds?: An embed, or list of embeds for the message.
:type embeds: Optional[Union[Embed, List[Embed]]]
:param allowed_mentions?: The message interactions/mention limits that the message can refer to.
:type allowed_mentions: Optional[MessageInteraction]
:param components?: A component, or list of components for the message.
:type components: Optional[Union[ActionRow, Button, SelectMenu, List[Actionrow], List[Button], List[SelectMenu]]]
:return: The sent message as an object.
:rtype: Message
"""
if not self._client:
raise AttributeError("HTTPClient not found!")
from ...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
# _file = None if file is None else file
# _attachments = [] if attachments else None
_allowed_mentions: dict = {} if allowed_mentions is MISSING else allowed_mentions
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)
# TODO: post-v4: Add attachments into Message obj.
payload = Message(
content=_content,
tts=_tts,
# file=file,
# attachments=_attachments,
embeds=_embeds,
allowed_mentions=_allowed_mentions,
components=_components,
)
res = await self._client.create_message(channel_id=int(self.id), payload=payload._json)
return Message(**res, _client=self._client)
async def delete(self) -> None:
"""
Deletes the channel.
"""
if not self._client:
raise AttributeError("HTTPClient not found!")
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,
parent_id: Optional[int] = MISSING,
nsfw: Optional[bool] = MISSING,
reason: Optional[str] = None,
) -> "Channel":
"""
Edits the channel.
:param name?: The name of the channel, defaults to the current value of the channel
:type name: str
:param topic?: The topic of that channel, defaults to the current value of the channel
:type topic: Optional[str]
:param bitrate?: (voice channel only) The bitrate (in bits) of the voice channel, defaults to the current value of the channel
:type bitrate Optional[int]
:param user_limit?: (voice channel only) Maximum amount of users in the channel, defaults to the current value of the channel
:type user_limit: Optional[int]
:param rate_limit_per_use?: Amount of seconds a user has to wait before sending another message (0-21600), defaults to the current value of the channel
:type rate_limit_per_user: Optional[int]
:param position?: Sorting position of the channel, defaults to the current value of the channel
:type position: Optional[int]
:param parent_id?: The id of the parent category for a channel, defaults to the current value of the channel
:type parent_id: Optional[int]
:param nsfw?: Whether the channel is nsfw or not, defaults to the current value of the channel
:type nsfw: Optional[bool]
:param reason?: The reason for the edit
:type reason: Optional[str]
:return: The modified channel as new object
:rtype: Channel
"""
if not self._client:
raise AttributeError("HTTPClient not found!")
_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 = self.parent_id if parent_id is MISSING else parent_id
_nsfw = self.nsfw if nsfw is MISSING else nsfw
_type = self.type
payload = Channel(
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,
)
res = await self._client.modify_channel(
channel_id=int(self.id),
reason=reason,
data=payload._json,
)
return Channel(**res, _client=self._client)
async def set_name(
self,
name: str,
*,
reason: Optional[str] = None,
) -> "Channel":
"""
Sets the name of the channel.
:param name: The new name of the channel
:type name: str
:param reason?: The reason of the edit
:type reason: Optional[str]
: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 topic: The new topic of the channel
:type topic: str
:param reason?: The reason of the edit
:type reason: Optional[str]
: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 bitrate: The new bitrate of the channel
:type bitrate: int
:param reason?: The reason of the edit
:type reason: Optional[str]
:return: The edited channel
:rtype: Channel
"""
if self.type != ChannelType.GUILD_VOICE:
raise TypeError("Bitrate is only available for VoiceChannels")
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 user_limit: The new user limit of the channel
:type user_limit: int
:param reason?: The reason of the edit
:type reason: Optional[str]
:return: The edited channel
:rtype: Channel
"""
if self.type != ChannelType.GUILD_VOICE:
raise TypeError("user_limit is only available for VoiceChannels")
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 position of the channel.
:param rate_limit_per_user: The new rate_limit_per_user of the channel (0-21600)
:type rate_limit_per_user: int
:param reason?: The reason of the edit
:type reason: Optional[str]
: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 position: The new position of the channel
:type position: int
:param reason?: The reason of the edit
:type reason: Optional[str]
: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 parent_id: The new parent_id of the channel
:type parent_id: int
:param reason?: The reason of the edit
:type reason: Optional[str]
: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 nsfw: The new nsfw-flag of the channel
:type nsfw: bool
:param reason?: The reason of the edit
:type reason: Optional[str]
:return: The edited channel
:rtype: Channel
"""
return await self.modify(nsfw=nsfw, reason=reason)
async def add_member(
self,
member_id: int,
) -> None:
"""
This adds a member to the channel, if the channel is a thread.
:param member_id: The id of the member to add to the channel
:type member_id: int
"""
if not self._client:
raise AttributeError("HTTPClient not found!")
if not self.thread_metadata:
raise TypeError(
"The Channel you specified is not a thread!"
) # TODO: Move to new error formatter.
await self._client.add_member_to_thread(thread_id=int(self.id), user_id=member_id)
async def pin_message(
self,
message_id: int,
) -> None:
"""
Pins a message to the channel.
:param message_id: The id of the message to pin
:type message_id: int
"""
if not self._client:
raise AttributeError("HTTPClient not found!")
await self._client.pin_message(channel_id=int(self.id), message_id=message_id)
async def unpin_message(
self,
message_id: int,
) -> None:
"""
Unpins a message from the channel.
:param message_id: The id of the message to unpin
:type message_id: int
"""
if not self._client:
raise AttributeError("HTTPClient not found!")
await self._client.unpin_message(channel_id=int(self.id), message_id=message_id)
async def publish_message(
self,
message_id: int,
) -> "Message": # noqa
"""Publishes (API calls it crossposts) a message in the channel to any that is followed by.
:param message_id: The id of the message to publish
:type message_id: int
:return: The message published
:rtype: Message
"""
if not self._client:
raise AttributeError("HTTPClient not found!")
from .message import Message
res = await self._client.publish_message(
channel_id=int(self.id), message_id=int(message_id)
)
return Message(**res, _client=self._client)
async def get_pinned_messages(self) -> List["Message"]: # noqa
"""
Get all pinned messages from the channel.
:return: A list of pinned message objects.
:rtype: List[Message]
"""
if not self._client:
raise AttributeError("HTTPClient not found!")
from .message import Message
res = await self._client.get_pinned_messages(int(self.id))
return [Message(**message, _client=self._client) for message in res]
async def get_message(
self,
message_id: int,
) -> "Message": # noqa
"""
Gets a message sent in that channel.
:return: The message as object
:rtype: Message
"""
res = await self._client.get_message(
channel_id=int(self.id),
message_id=message_id,
)
from .message import Message
return Message(**res, _client=self._client)
async def purge(
self,
amount: int,
check: Callable = MISSING,
before: Optional[int] = MISSING,
reason: Optional[str] = None,
bulk: Optional[bool] = True,
) -> List["Message"]: # noqa
"""
Purges a given amount of messages from a channel. You can specify a check function to exclude specific messages.
.. code-block:: python
def check_pinned(message):
return not message.pinned # This returns `True` only if the message is the message is not pinned
await channel.purge(100, check=check_pinned) # This will delete the newest 100 messages that are not pinned in that channel
:param amount: The amount of messages to delete
:type amount: int
:param check?: The function used to check if a message should be deleted. The message is only deleted if the check returns `True`
:type check: Callable[[Message], bool]
:param before?: An id of a message to purge only messages before that message
:type before: Optional[int]
:param bulk?: Whether to bulk delete the messages (you cannot delete messages older than 14 days, default) or to delete every message seperately
:param bulk: Optional[bool]
:param reason?: The reason of the deletes
:type reason: Optional[str]
:return: A list of the deleted messages
:rtype: List[Message]
"""
if not self._client:
raise AttributeError("HTTPClient not found!")
from .message import Message
_before = None if before is MISSING else before
_all = []
if bulk:
_allowed_time = datetime.now(tz=timezone.utc) - timedelta(days=14)
_stop = False
while amount > 100:
messages = [
Message(**res)
for res in await self._client.get_channel_messages(
channel_id=int(self.id),
limit=100,
before=_before,
)
]
messages2 = messages.copy()
for message in messages2:
if datetime.fromisoformat(str(message.timestamp)) < _allowed_time:
messages.remove(message)
_stop = True
messages2 = messages.copy()
for message in messages2:
if message.flags == (1 << 7):
messages.remove(message)
amount += 1
_before = int(message.id)
elif check is not MISSING:
_check = check(message)
if not _check:
messages.remove(message)
amount += 1
_before = int(message.id)
_all += messages
if len(messages) > 1:
await self._client.delete_messages(
channel_id=int(self.id),
message_ids=[int(message.id) for message in messages],
reason=reason,
)
elif len(messages) == 1:
await self._client.delete_message(
channel_id=int(self.id),
message_id=int(messages[0].id),
reason=reason,
)
elif _stop:
return _all
else:
continue
if _stop:
return _all
amount -= 100
while amount > 1:
messages = [
Message(**res)
for res in await self._client.get_channel_messages(
channel_id=int(self.id),
limit=amount,
before=_before,
)
]
messages2 = messages.copy()
for message in messages2:
if datetime.fromisoformat(str(message.timestamp)) < _allowed_time:
messages.remove(message)
_stop = True
amount -= amount
messages2 = messages.copy()
for message in messages2:
if message.flags == (1 << 7):
messages.remove(message)
amount += 1
_before = int(message.id)
elif check is not MISSING:
_check = check(message)
if not _check:
messages.remove(message)
amount += 1
_before = int(message.id)
_all += messages
if len(messages) > 1:
await self._client.delete_messages(
channel_id=int(self.id),
message_ids=[int(message.id) for message in messages],
reason=reason,
)
elif len(messages) == 1:
await self._client.delete_message(
channel_id=int(self.id),
message_id=int(messages[0].id),
reason=reason,
)
elif _stop:
return _all
else:
continue
if _stop:
return _all
while amount == 1:
messages = [
Message(**res)
for res in await self._client.get_channel_messages(
channel_id=int(self.id),
limit=amount,
before=_before,
)
]
amount -= 1
messages2 = messages.copy()
for message in messages2:
if message.flags == (1 << 7):
messages.remove(message)
amount += 1
_before = int(message.id)
elif check is not MISSING:
_check = check(message)
if not _check:
messages.remove(message)
amount += 1
_before = int(message.id)
_all += messages
if not messages:
continue
await self._client.delete_message(
channel_id=int(self.id),
message_id=int(messages[0].id),
reason=reason,
)
else:
while amount > 0:
messages = [
Message(**res)
for res in await self._client.get_channel_messages(
channel_id=int(self.id),
limit=min(amount, 100),
before=_before,
)
]
amount -= min(amount, 100)
messages2 = messages.copy()
for message in messages2:
if message.flags == (1 << 7):
messages.remove(message)
amount += 1
_before = int(message.id)
elif check is not MISSING:
_check = check(message)
if not _check:
messages.remove(message)
amount += 1
_before = int(message.id)
_all += messages
for message in _all:
await self._client.delete_message(
channel_id=int(self.id),
message_id=int(message.id),
reason=reason,
)
return _all
async def create_thread(
self,
name: str,
type: Optional[ChannelType] = ChannelType.GUILD_PUBLIC_THREAD,
auto_archive_duration: Optional[int] = MISSING,
invitable: Optional[bool] = MISSING,
message_id: Optional[int] = MISSING,
reason: Optional[str] = None,
) -> "Channel":
"""
Creates a thread in the Channel.
:param name: The name of the thread
:type name: str
:param auto_archive_duration?: duration in minutes to automatically archive the thread after recent activity,
can be set to: 60, 1440, 4320, 10080
:type auto_archive_duration: Optional[int]
:param type?: The type of thread, defaults to public. ignored if creating thread from a message
:type type: Optional[ChannelType]
:param invitable?: Boolean to display if the Thread is open to join or private.
:type invitable: Optional[bool]
:param message_id?: An optional message to create a thread from.
:type message_id: Optional[int]
:param reason?: An optional reason for the audit log
:type reason: Optional[str]
:return: The created thread
:rtype: Channel
"""
if not self._client:
raise AttributeError("HTTPClient not found!")
if type not in [
ChannelType.GUILD_NEWS_THREAD,
ChannelType.GUILD_PUBLIC_THREAD,
ChannelType.GUILD_PRIVATE_THREAD,
]:
raise AttributeError("type must be a thread type!")
_auto_archive_duration = None if auto_archive_duration is MISSING else auto_archive_duration
_invitable = None if invitable is MISSING else invitable
_message_id = None if message_id is MISSING else message_id
res = await self._client.create_thread(
channel_id=int(self.id),
thread_type=type.value,
name=name,
auto_archive_duration=_auto_archive_duration,
invitable=_invitable,
message_id=_message_id,
reason=reason,
)
return Channel(**res, _client=self._client)
@classmethod
async def get(
cls,
channel: Union[int, str],
client: "HTTPClient", # noqa
) -> "Channel":
"""
Gets a channel based of its URL or its id.
:param channel: The URL to the channel or the id of the channel
:type channel: Union[int, str]
:param client: The HTTPClient of your bot. Set as ``bot._http``
:type client: HTTPClient
"""
channel_id = channel if isinstance(channel, int) else int(channel.split(sep="/")[-1])
res = await client.get_channel(channel_id)
return cls(**res, _client=client)
@property
def url(self) -> str:
guild_id = "@me" if not isinstance(self.guild_id, int) else self.guild_id
return f"https://discord.com/channels/{guild_id}/{self.id}"
async def create_invite(
self,
max_age: Optional[int] = 86400,
max_uses: Optional[int] = 0,
temporary: Optional[bool] = False,
unique: Optional[bool] = False,
target_type: Optional["InviteTargetType"] = MISSING, # noqa
target_user_id: Optional[int] = MISSING,
target_application_id: Optional[int] = MISSING,
reason: Optional[str] = None,
) -> "Invite": # noqa
"""
Creates an invite for the channel
:param max_age?: Duration of invite in seconds before expiry, or 0 for never. between 0 and 604800 (7 days). Default 86400 (24h)
:type max_age: Optional[int]
:param max_uses?: Max number of uses or 0 for unlimited. between 0 and 100. Default 0
:type max_uses: Optional[int]
:param temporary?: Whether this invite only grants temporary membership. Default False
:type temporary: Optional[bool]
:param unique?: If true, don't try to reuse a similar invite (useful for creating many unique one time use invites). Default False
:type unique: Optional[bool]
:param target_type?: The type of target for this voice channel invite
:type target_type: Optional["InviteTargetType"]
:param target_user_id?: The id of the user whose stream to display for this invite, required if target_type is STREAM, the user must be streaming in the channel
:type target_user_id: Optional[int]
:param target_application_id?: The id of the embedded application to open for this invite, required if target_type is EMBEDDED_APPLICATION, the application must have the EMBEDDED flag
:type target_application_id: Optional[int]
:param reason?: The reason for the creation of the invite
:type reason: Optional[str]
"""
if not self._client:
raise AttributeError("HTTPClient not found!")
payload = {
"max_age": max_age,
"max_uses": max_uses,
"temporary": temporary,
"unique": unique,
}
if (target_user_id is not MISSING and target_user_id) and (
target_application_id is not MISSING and target_application_id
):
raise ValueError(
"target user id and target application are mutually exclusive!"
) # TODO: move to custom error formatter
elif (
(target_user_id is not MISSING and target_user_id)
or (target_application_id is not MISSING and target_application_id)
) and not target_type:
raise ValueError(
"you have to specify a target_type if you specify target_user-/target_application_id"
)
if target_user_id is not MISSING:
payload["target_type"] = (
target_type if isinstance(target_type, int) else target_type.value
)
payload["target_user_id"] = target_user_id
if target_application_id is not MISSING:
payload["target_type"] = (
target_type if isinstance(target_type, int) else target_type.value
)
payload["target_application_id"] = target_application_id
res = await self._client.create_channel_invite(
channel_id=int(self.id),
data=payload,
reason=reason,
)
from .guild import Invite
return Invite(**res, _client=self._client)
class Thread(Channel):
"""An object representing a thread.
.. note::
This is a derivation of the base Channel, since a
thread can be its own event.
"""
...