/
channel.py
4619 lines (3797 loc) · 157 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
# SPDX-License-Identifier: MIT
from __future__ import annotations
import asyncio
import datetime
import time
from typing import (
TYPE_CHECKING,
Any,
Callable,
Dict,
Iterable,
List,
Literal,
Mapping,
NamedTuple,
Optional,
Sequence,
Tuple,
Type,
Union,
cast,
overload,
)
import disnake.abc
from . import utils
from .asset import Asset
from .context_managers import Typing
from .enums import (
ChannelType,
StagePrivacyLevel,
ThreadLayout,
ThreadSortOrder,
VideoQualityMode,
try_enum,
try_enum_to_int,
)
from .errors import ClientException
from .file import File
from .flags import ChannelFlags, MessageFlags
from .iterators import ArchivedThreadIterator
from .mixins import Hashable
from .partial_emoji import PartialEmoji
from .permissions import PermissionOverwrite, Permissions
from .stage_instance import StageInstance
from .threads import ForumTag, Thread
from .utils import MISSING
__all__ = (
"TextChannel",
"VoiceChannel",
"StageChannel",
"DMChannel",
"CategoryChannel",
"NewsChannel",
"ThreadWithMessage",
"ForumChannel",
"GroupChannel",
"PartialMessageable",
)
if TYPE_CHECKING:
from typing_extensions import Never, Self
from .abc import Snowflake, SnowflakeTime
from .asset import AssetBytes
from .embeds import Embed
from .emoji import Emoji
from .guild import Guild, GuildChannel as GuildChannelType
from .member import Member, VoiceState
from .message import AllowedMentions, Message, PartialMessage
from .role import Role
from .state import ConnectionState
from .sticker import GuildSticker, StandardSticker, StickerItem
from .threads import AnyThreadArchiveDuration, ThreadType
from .types.channel import (
CategoryChannel as CategoryChannelPayload,
DefaultReaction as DefaultReactionPayload,
DMChannel as DMChannelPayload,
ForumChannel as ForumChannelPayload,
GroupDMChannel as GroupChannelPayload,
StageChannel as StageChannelPayload,
TextChannel as TextChannelPayload,
VoiceChannel as VoiceChannelPayload,
)
from .types.snowflake import SnowflakeList
from .types.threads import ThreadArchiveDurationLiteral
from .ui.action_row import Components, MessageUIComponent
from .ui.view import View
from .user import BaseUser, ClientUser, User
from .voice_region import VoiceRegion
from .webhook import Webhook
async def _single_delete_strategy(messages: Iterable[Message]) -> None:
for m in messages:
await m.delete()
class TextChannel(disnake.abc.Messageable, disnake.abc.GuildChannel, Hashable):
"""Represents a Discord guild text channel.
.. collapse:: operations
.. describe:: x == y
Checks if two channels are equal.
.. describe:: x != y
Checks if two channels are not equal.
.. describe:: hash(x)
Returns the channel's hash.
.. describe:: str(x)
Returns the channel's name.
Attributes
----------
name: :class:`str`
The channel's name.
guild: :class:`Guild`
The guild the channel belongs to.
id: :class:`int`
The channel's ID.
category_id: Optional[:class:`int`]
The category channel ID this channel belongs to, if applicable.
topic: Optional[:class:`str`]
The channel's topic. ``None`` if it doesn't exist.
position: :class:`int`
The position in the channel list. This is a number that starts at 0. e.g. the
top channel is position 0.
last_message_id: Optional[:class:`int`]
The last message ID of the message sent to this channel. It may
*not* point to an existing or valid message.
slowmode_delay: :class:`int`
The number of seconds a member must wait between sending messages
in this channel.
A value of `0` denotes that it is disabled.
Bots, and users with :attr:`~Permissions.manage_channels` or
:attr:`~Permissions.manage_messages` permissions, bypass slowmode.
See also :attr:`default_thread_slowmode_delay`.
default_thread_slowmode_delay: :class:`int`
The default number of seconds a member must wait between sending messages
in newly created threads in this channel.
A value of ``0`` denotes that it is disabled.
Bots, and users with :attr:`~Permissions.manage_channels` or
:attr:`~Permissions.manage_messages`, bypass slowmode.
.. versionadded:: 2.8
nsfw: :class:`bool`
Whether the channel is marked as "not safe for work".
.. note::
To check if the channel or the guild of that channel are marked as NSFW, consider :meth:`is_nsfw` instead.
default_auto_archive_duration: :class:`int`
The default auto archive duration in minutes for threads created in this channel.
.. versionadded:: 2.0
last_pin_timestamp: Optional[:class:`datetime.datetime`]
The time the most recent message was pinned, or ``None`` if no message is currently pinned.
.. versionadded:: 2.5
"""
__slots__ = (
"name",
"id",
"guild",
"topic",
"_state",
"nsfw",
"category_id",
"position",
"slowmode_delay",
"default_thread_slowmode_delay",
"last_message_id",
"default_auto_archive_duration",
"last_pin_timestamp",
"_overwrites",
"_flags",
"_type",
)
def __init__(self, *, state: ConnectionState, guild: Guild, data: TextChannelPayload) -> None:
self._state: ConnectionState = state
self.id: int = int(data["id"])
self._type: Literal[0, 5] = data["type"]
self._update(guild, data)
def __repr__(self) -> str:
attrs = (
("id", self.id),
("name", self.name),
("position", self.position),
("nsfw", self.nsfw),
("news", self.is_news()),
("category_id", self.category_id),
("default_auto_archive_duration", self.default_auto_archive_duration),
("flags", self.flags),
)
joined = " ".join(f"{k!s}={v!r}" for k, v in attrs)
return f"<{self.__class__.__name__} {joined}>"
def _update(self, guild: Guild, data: TextChannelPayload) -> None:
self.guild: Guild = guild
# apparently this can be nullable in the case of a bad api deploy
self.name: str = data.get("name") or ""
self.category_id: Optional[int] = utils._get_as_snowflake(data, "parent_id")
self.topic: Optional[str] = data.get("topic")
self.position: int = data["position"]
self._flags = data.get("flags", 0)
self.nsfw: bool = data.get("nsfw", False)
# Does this need coercion into `int`? No idea yet.
self.slowmode_delay: int = data.get("rate_limit_per_user", 0)
self.default_thread_slowmode_delay: int = data.get("default_thread_rate_limit_per_user", 0)
self.default_auto_archive_duration: ThreadArchiveDurationLiteral = data.get(
"default_auto_archive_duration", 1440
)
self._type: Literal[0, 5] = data.get("type", self._type)
self.last_message_id: Optional[int] = utils._get_as_snowflake(data, "last_message_id")
self.last_pin_timestamp: Optional[datetime.datetime] = utils.parse_time(
data.get("last_pin_timestamp")
)
self._fill_overwrites(data)
async def _get_channel(self):
return self
@property
def type(self) -> Literal[ChannelType.text, ChannelType.news]:
""":class:`ChannelType`: The channel's Discord type.
This always returns :attr:`ChannelType.text` or :attr:`ChannelType.news`.
"""
if self._type == ChannelType.text.value:
return ChannelType.text
return ChannelType.news
@property
def _sorting_bucket(self) -> int:
return ChannelType.text.value
@utils.copy_doc(disnake.abc.GuildChannel.permissions_for)
def permissions_for(
self,
obj: Union[Member, Role],
/,
*,
ignore_timeout: bool = MISSING,
) -> Permissions:
base = super().permissions_for(obj, ignore_timeout=ignore_timeout)
self._apply_implict_permissions(base)
# text channels do not have voice related permissions
denied = Permissions.voice()
base.value &= ~denied.value
return base
@property
def members(self) -> List[Member]:
"""List[:class:`Member`]: Returns all members that can see this channel."""
return [m for m in self.guild.members if self.permissions_for(m).view_channel]
@property
def threads(self) -> List[Thread]:
"""List[:class:`Thread`]: Returns all the threads that you can see.
.. versionadded:: 2.0
"""
return [thread for thread in self.guild._threads.values() if thread.parent_id == self.id]
def is_nsfw(self) -> bool:
"""Whether the channel is marked as NSFW.
:return type: :class:`bool`
"""
return self.nsfw
def is_news(self) -> bool:
"""Whether the channel is a news channel.
:return type: :class:`bool`
"""
return self._type == ChannelType.news.value
@property
def last_message(self) -> Optional[Message]:
"""Gets the last message in this channel from the cache.
The message might not be valid or point to an existing message.
.. admonition:: Reliable Fetching
:class: helpful
For a slightly more reliable method of fetching the
last message, consider using either :meth:`history`
or :meth:`fetch_message` with the :attr:`last_message_id`
attribute.
Returns
-------
Optional[:class:`Message`]
The last message in this channel or ``None`` if not found.
"""
return self._state._get_message(self.last_message_id) if self.last_message_id else None
# if only these parameters are passed, `_move` is called and no channel will be returned
@overload
async def edit(
self,
*,
position: int,
category: Optional[Snowflake] = ...,
sync_permissions: bool = ...,
reason: Optional[str] = ...,
) -> None:
...
# only passing `sync_permissions` may or may not return a channel,
# depending on whether the channel is in a category
@overload
async def edit(
self,
*,
sync_permissions: bool,
reason: Optional[str] = ...,
) -> Optional[TextChannel]:
...
@overload
async def edit(
self,
*,
name: str = ...,
topic: Optional[str] = ...,
position: int = ...,
nsfw: bool = ...,
sync_permissions: bool = ...,
category: Optional[Snowflake] = ...,
slowmode_delay: Optional[int] = ...,
default_thread_slowmode_delay: Optional[int] = ...,
default_auto_archive_duration: Optional[AnyThreadArchiveDuration] = ...,
type: ChannelType = ...,
overwrites: Mapping[Union[Role, Member], PermissionOverwrite] = ...,
flags: ChannelFlags = ...,
reason: Optional[str] = ...,
) -> TextChannel:
...
async def edit(
self,
*,
name: str = MISSING,
topic: Optional[str] = MISSING,
position: int = MISSING,
nsfw: bool = MISSING,
sync_permissions: bool = MISSING,
category: Optional[Snowflake] = MISSING,
slowmode_delay: Optional[int] = MISSING,
default_thread_slowmode_delay: Optional[int] = MISSING,
default_auto_archive_duration: Optional[AnyThreadArchiveDuration] = MISSING,
type: ChannelType = MISSING,
overwrites: Mapping[Union[Role, Member], PermissionOverwrite] = MISSING,
flags: ChannelFlags = MISSING,
reason: Optional[str] = None,
**kwargs: Never,
) -> Optional[TextChannel]:
"""|coro|
Edits the channel.
You must have :attr:`~Permissions.manage_channels` permission to
do this.
.. versionchanged:: 1.3
The ``overwrites`` keyword-only parameter was added.
.. versionchanged:: 1.4
The ``type`` keyword-only parameter was added.
.. versionchanged:: 2.0
Edits are no longer in-place, the newly edited channel is returned instead.
.. versionchanged:: 2.6
Raises :exc:`TypeError` or :exc:`ValueError` instead of ``InvalidArgument``.
Parameters
----------
name: :class:`str`
The new channel's name.
topic: Optional[:class:`str`]
The new channel's topic.
position: :class:`int`
The new channel's position.
nsfw: :class:`bool`
Whether to mark the channel as NSFW.
sync_permissions: :class:`bool`
Whether to sync permissions with the channel's new or pre-existing
category. Defaults to ``False``.
category: Optional[:class:`abc.Snowflake`]
The new category for this channel. Can be ``None`` to remove the
category.
slowmode_delay: Optional[:class:`int`]
Specifies the slowmode rate limit for users in this channel, in seconds.
A value of ``0`` disables slowmode. The maximum value possible is ``21600``.
default_thread_slowmode_delay: Optional[:class:`int`]
Specifies the slowmode rate limit at which users can send messages
in newly created threads in this channel, in seconds.
This does not apply retroactively to existing threads.
A value of ``0`` or ``None`` disables slowmode. The maximum value possible is ``21600``.
.. versionadded:: 2.8
type: :class:`ChannelType`
The new type of this text channel. Currently, only conversion between
:attr:`ChannelType.text` and :attr:`ChannelType.news` is supported. This
is only available to guilds that contain ``NEWS`` in :attr:`Guild.features`.
overwrites: :class:`Mapping`
A :class:`Mapping` of target (either a role or a member) to
:class:`PermissionOverwrite` to apply to the channel.
default_auto_archive_duration: Optional[Union[:class:`int`, :class:`ThreadArchiveDuration`]]
The new default auto archive duration in minutes for threads created in this channel.
Must be one of ``60``, ``1440``, ``4320``, or ``10080``.
flags: :class:`ChannelFlags`
The new flags to set for this channel. This will overwrite any existing flags set on this channel.
.. versionadded:: 2.6
reason: Optional[:class:`str`]
The reason for editing this channel. Shows up on the audit log.
Raises
------
Forbidden
You do not have permissions to edit the channel.
HTTPException
Editing the channel failed.
TypeError
The permission overwrite information is not in proper form.
ValueError
The position is less than 0.
Returns
-------
Optional[:class:`.TextChannel`]
The newly edited text channel. If the edit was only positional
then ``None`` is returned instead.
"""
payload = await self._edit(
name=name,
topic=topic,
position=position,
nsfw=nsfw,
sync_permissions=sync_permissions,
category=category,
slowmode_delay=slowmode_delay,
default_thread_slowmode_delay=default_thread_slowmode_delay,
default_auto_archive_duration=default_auto_archive_duration,
type=type,
overwrites=overwrites,
flags=flags,
reason=reason,
**kwargs, # type: ignore
)
if payload is not None:
# the payload will always be the proper channel payload
return self.__class__(state=self._state, guild=self.guild, data=payload) # type: ignore
async def clone(
self,
*,
name: Optional[str] = None,
topic: Optional[str] = MISSING,
position: int = MISSING,
nsfw: bool = MISSING,
category: Optional[Snowflake] = MISSING,
slowmode_delay: int = MISSING,
default_thread_slowmode_delay: Optional[int] = MISSING,
default_auto_archive_duration: AnyThreadArchiveDuration = MISSING,
overwrites: Mapping[Union[Role, Member], PermissionOverwrite] = MISSING,
news: bool = MISSING,
reason: Optional[str] = None,
) -> TextChannel:
"""|coro|
Clones this channel. This creates a channel with the same properties
as this channel.
You must have :attr:`.Permissions.manage_channels` permission to
do this.
.. versionchanged:: 2.9
Added ``topic``, ``position``, ``nsfw``, ``category``, ``slowmode_delay``,
``default_thread_slowmode_delay``, ``default_auto_archive_duration``, ``news``
and ``overwrites`` keyword-only parameters.
.. note::
The current :attr:`TextChannel.flags` value won't be cloned.
This is a Discord limitation.
Parameters
----------
name: Optional[:class:`str`]
The name of the new channel. If not provided, defaults to this channel's name.
topic: Optional[:class:`str`]
The topic of the new channel. If not provided, defaults to this channel's topic.
position: :class:`int`
The position of the new channel. If not provided, defaults to this channel's position.
nsfw: :class:`bool`
Whether the new channel should be marked as NSFW. If not provided, defaults to this channel's NSFW value.
category: Optional[:class:`abc.Snowflake`]
The category where the new channel should be grouped. If not provided, defaults to this channel's category.
slowmode_delay: :class:`int`
The slowmode of the new channel. If not provided, defaults to this channel's slowmode.
default_thread_slowmode_delay: Optional[:class:`int`]
Specifies the slowmode rate limit at which users can send messages
in newly created threads in this channel, in seconds.
This does not apply retroactively to existing threads.
A value of ``0`` or ``None`` disables slowmode. The maximum value possible is ``21600``. If not provided, defaults
to this channel's default thread slowmode delay.
default_auto_archive_duration: Union[:class:`int`, :class:`ThreadArchiveDuration`]
The default auto archive duration of the new channel. If not provided, defaults to this channel's default auto archive duration.
overwrites: :class:`Mapping`
A :class:`Mapping` of target (either a role or a member) to :class:`PermissionOverwrite`
to apply to the channel. If not provided, defaults to this channel's overwrites.
news: :class:`bool`
Whether the new channel should be a news channel. News channels are text channels that can be followed.
This is only available to guilds that contain ``NEWS`` in :attr:`Guild.features`. If not provided, defaults to the current type of this channel.
reason: Optional[:class:`str`]
The reason for cloning this channel. Shows up on the audit log.
Raises
------
Forbidden
You do not have the proper permissions to create this channel.
HTTPException
Creating the channel failed.
Returns
-------
:class:`TextChannel`
The newly created text channel.
"""
if news is not MISSING:
# if news is True set the channel_type to News, otherwise if it's False set it to Text
channel_type = ChannelType.news if news else ChannelType.text
else:
# if news is not given falls back to the original TextChannel type
channel_type = self.type
return await self._clone_impl(
{
"topic": topic if topic is not MISSING else self.topic,
"position": position if position is not MISSING else self.position,
"nsfw": nsfw if nsfw is not MISSING else self.nsfw,
"type": channel_type.value,
"rate_limit_per_user": (
slowmode_delay if slowmode_delay is not MISSING else self.slowmode_delay
),
"default_thread_rate_limit_per_user": (
default_thread_slowmode_delay
if default_thread_slowmode_delay is not MISSING
else self.default_thread_slowmode_delay
),
"default_auto_archive_duration": (
try_enum_to_int(default_auto_archive_duration)
if default_auto_archive_duration is not MISSING
else self.default_auto_archive_duration
),
},
name=name,
category=category,
reason=reason,
overwrites=overwrites,
)
async def delete_messages(self, messages: Iterable[Snowflake]) -> None:
"""|coro|
Deletes a list of messages. This is similar to :meth:`Message.delete`
except it bulk deletes multiple messages.
As a special case, if the number of messages is 0, then nothing
is done. If the number of messages is 1 then single message
delete is done. If it's more than two, then bulk delete is used.
You cannot bulk delete more than 100 messages or messages that
are older than 14 days.
You must have :attr:`~Permissions.manage_messages` permission to
do this.
Parameters
----------
messages: Iterable[:class:`abc.Snowflake`]
An iterable of messages denoting which ones to bulk delete.
Raises
------
ClientException
The number of messages to delete was more than 100.
Forbidden
You do not have proper permissions to delete the messages.
NotFound
If single delete, then the message was already deleted.
HTTPException
Deleting the messages failed.
"""
if not isinstance(messages, (list, tuple)):
messages = list(messages)
if len(messages) == 0:
return # do nothing
if len(messages) == 1:
message_id: int = messages[0].id
await self._state.http.delete_message(self.id, message_id)
return
if len(messages) > 100:
raise ClientException("Can only bulk delete messages up to 100 messages")
message_ids: SnowflakeList = [m.id for m in messages]
await self._state.http.delete_messages(self.id, message_ids)
async def purge(
self,
*,
limit: Optional[int] = 100,
check: Callable[[Message], bool] = MISSING,
before: Optional[SnowflakeTime] = None,
after: Optional[SnowflakeTime] = None,
around: Optional[SnowflakeTime] = None,
oldest_first: Optional[bool] = False,
bulk: bool = True,
) -> List[Message]:
"""|coro|
Purges a list of messages that meet the criteria given by the predicate
``check``. If a ``check`` is not provided then all messages are deleted
without discrimination.
You must have :attr:`~Permissions.manage_messages` permission to
delete messages even if they are your own.
:attr:`~Permissions.read_message_history` permission is
also needed to retrieve message history.
Examples
--------
Deleting bot's messages ::
def is_me(m):
return m.author == client.user
deleted = await channel.purge(limit=100, check=is_me)
await channel.send(f'Deleted {len(deleted)} message(s)')
Parameters
----------
limit: Optional[:class:`int`]
The number of messages to search through. This is not the number
of messages that will be deleted, though it can be.
check: Callable[[:class:`Message`], :class:`bool`]
The function used to check if a message should be deleted.
It must take a :class:`Message` as its sole parameter.
before: Optional[Union[:class:`abc.Snowflake`, :class:`datetime.datetime`]]
Same as ``before`` in :meth:`history`.
after: Optional[Union[:class:`abc.Snowflake`, :class:`datetime.datetime`]]
Same as ``after`` in :meth:`history`.
around: Optional[Union[:class:`abc.Snowflake`, :class:`datetime.datetime`]]
Same as ``around`` in :meth:`history`.
oldest_first: Optional[:class:`bool`]
Same as ``oldest_first`` in :meth:`history`.
bulk: :class:`bool`
If ``True``, use bulk delete. Setting this to ``False`` is useful for mass-deleting
a bot's own messages without :attr:`Permissions.manage_messages`. When ``True``, will
fall back to single delete if messages are older than two weeks.
Raises
------
Forbidden
You do not have proper permissions to do the actions required.
HTTPException
Purging the messages failed.
Returns
-------
List[:class:`.Message`]
A list of messages that were deleted.
"""
if check is MISSING:
check = lambda m: True
iterator = self.history(
limit=limit, before=before, after=after, oldest_first=oldest_first, around=around
)
ret: List[Message] = []
count = 0
minimum_time = int((time.time() - 14 * 24 * 60 * 60) * 1000.0 - 1420070400000) << 22
strategy = self.delete_messages if bulk else _single_delete_strategy
async for message in iterator:
if count == 100:
to_delete = ret[-100:]
await strategy(to_delete)
count = 0
await asyncio.sleep(1)
if not check(message):
continue
if message.id < minimum_time:
# older than 14 days old
if count == 1:
await ret[-1].delete()
elif count >= 2:
to_delete = ret[-count:]
await strategy(to_delete)
count = 0
strategy = _single_delete_strategy
count += 1
ret.append(message)
# SOme messages remaining to poll
if count >= 2:
# more than 2 messages -> bulk delete
to_delete = ret[-count:]
await strategy(to_delete)
elif count == 1:
# delete a single message
await ret[-1].delete()
return ret
async def webhooks(self) -> List[Webhook]:
"""|coro|
Retrieves the list of webhooks this channel has.
You must have :attr:`~.Permissions.manage_webhooks` permission to
use this.
Raises
------
Forbidden
You don't have permissions to get the webhooks.
Returns
-------
List[:class:`Webhook`]
The list of webhooks this channel has.
"""
from .webhook import Webhook
data = await self._state.http.channel_webhooks(self.id)
return [Webhook.from_state(d, state=self._state) for d in data]
async def create_webhook(
self, *, name: str, avatar: Optional[AssetBytes] = None, reason: Optional[str] = None
) -> Webhook:
"""|coro|
Creates a webhook for this channel.
You must have :attr:`~.Permissions.manage_webhooks` permission to
do this.
.. versionchanged:: 1.1
The ``reason`` keyword-only parameter was added.
Parameters
----------
name: :class:`str`
The webhook's name.
avatar: Optional[|resource_type|]
The webhook's default avatar.
This operates similarly to :meth:`~ClientUser.edit`.
.. versionchanged:: 2.5
Now accepts various resource types in addition to :class:`bytes`.
reason: Optional[:class:`str`]
The reason for creating this webhook. Shows up in the audit logs.
Raises
------
NotFound
The ``avatar`` asset couldn't be found.
Forbidden
You do not have permissions to create a webhook.
HTTPException
Creating the webhook failed.
TypeError
The ``avatar`` asset is a lottie sticker (see :func:`Sticker.read`).
Returns
-------
:class:`Webhook`
The newly created webhook.
"""
from .webhook import Webhook
avatar_data = await utils._assetbytes_to_base64_data(avatar)
data = await self._state.http.create_webhook(
self.id, name=str(name), avatar=avatar_data, reason=reason
)
return Webhook.from_state(data, state=self._state)
async def follow(self, *, destination: TextChannel, reason: Optional[str] = None) -> Webhook:
"""|coro|
Follows a channel using a webhook.
Only news channels can be followed.
.. note::
The webhook returned will not provide a token to do webhook
actions, as Discord does not provide it.
.. versionadded:: 1.3
.. versionchanged:: 2.6
Raises :exc:`TypeError` instead of ``InvalidArgument``.
Parameters
----------
destination: :class:`TextChannel`
The channel you would like to follow from.
reason: Optional[:class:`str`]
The reason for following the channel. Shows up on the destination guild's audit log.
.. versionadded:: 1.4
Raises
------
HTTPException
Following the channel failed.
Forbidden
You do not have the permissions to create a webhook.
TypeError
The current or provided channel is not of the correct type.
Returns
-------
:class:`Webhook`
The newly created webhook.
"""
if not self.is_news():
raise TypeError("This channel must be a news channel.")
if not isinstance(destination, TextChannel):
raise TypeError(f"Expected TextChannel received {destination.__class__.__name__}")
from .webhook import Webhook
data = await self._state.http.follow_webhook(
self.id, webhook_channel_id=destination.id, reason=reason
)
return Webhook._as_follower(data, channel=destination, user=self._state.user)
def get_partial_message(self, message_id: int, /) -> PartialMessage:
"""Creates a :class:`PartialMessage` from the given message ID.
This is useful if you want to work with a message and only have its ID without
doing an unnecessary API call.
.. versionadded:: 1.6
Parameters
----------
message_id: :class:`int`
The message ID to create a partial message for.
Returns
-------
:class:`PartialMessage`
The partial message object.
"""
from .message import PartialMessage
return PartialMessage(channel=self, id=message_id)
def get_thread(self, thread_id: int, /) -> Optional[Thread]:
"""Returns a thread with the given ID.
.. versionadded:: 2.0
Parameters
----------
thread_id: :class:`int`
The ID to search for.
Returns
-------
Optional[:class:`Thread`]
The returned thread or ``None`` if not found.
"""
return self.guild.get_thread(thread_id)
@overload
async def create_thread(
self,
*,
name: str,
message: Snowflake,
auto_archive_duration: Optional[AnyThreadArchiveDuration] = None,
slowmode_delay: Optional[int] = None,
reason: Optional[str] = None,
) -> Thread:
...
@overload
async def create_thread(
self,
*,
name: str,
type: ThreadType,
auto_archive_duration: Optional[AnyThreadArchiveDuration] = None,
invitable: Optional[bool] = None,
slowmode_delay: Optional[int] = None,
reason: Optional[str] = None,
) -> Thread:
...
async def create_thread(
self,
*,
name: str,
message: Optional[Snowflake] = None,
auto_archive_duration: Optional[AnyThreadArchiveDuration] = None,
type: Optional[ThreadType] = None,
invitable: Optional[bool] = None,
slowmode_delay: Optional[int] = None,
reason: Optional[str] = None,
) -> Thread:
"""|coro|
Creates a thread in this text channel.
To create a public thread, you must have :attr:`~disnake.Permissions.create_public_threads` permission.
For a private thread, :attr:`~disnake.Permissions.create_private_threads` permission is needed instead.
.. versionadded:: 2.0
.. versionchanged:: 2.5
- Only one of ``message`` and ``type`` may be provided.
- ``type`` is now required if ``message`` is not provided.
Parameters
----------
name: :class:`str`
The name of the thread.
message: :class:`abc.Snowflake`
A snowflake representing the message to create the thread with.
.. versionchanged:: 2.5
Cannot be provided with ``type``.
type: :class:`ChannelType`
The type of thread to create.
.. versionchanged:: 2.5
Cannot be provided with ``message``.
Now required if message is not provided.
auto_archive_duration: Union[:class:`int`, :class:`ThreadArchiveDuration`]
The duration in minutes before a thread is automatically archived for inactivity.
If not provided, the channel's default auto archive duration is used.
Must be one of ``60``, ``1440``, ``4320``, or ``10080``.
invitable: :class:`bool`
Whether non-moderators can add other non-moderators to this thread.
Only available for private threads.
If a ``message`` is passed then this parameter is ignored, as a thread
created with a message is always a public thread.
Defaults to ``True``.
.. versionadded:: 2.3