forked from Pycord-Development/pycord
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathabc.py
1991 lines (1643 loc) · 64.5 KB
/
abc.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
"""
The MIT License (MIT)
Copyright (c) 2015-2021 Rapptz
Copyright (c) 2021-present Pycord Development
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
"""
from __future__ import annotations
import asyncio
import copy
import time
from typing import (
TYPE_CHECKING,
Any,
Callable,
Iterable,
Protocol,
Sequence,
TypeVar,
Union,
overload,
runtime_checkable,
)
from . import utils
from .context_managers import Typing
from .enums import ChannelType
from .errors import ClientException, InvalidArgument
from .file import File
from .flags import MessageFlags
from .invite import Invite
from .iterators import HistoryIterator
from .mentions import AllowedMentions
from .partial_emoji import PartialEmoji, _EmojiTag
from .permissions import PermissionOverwrite, Permissions
from .role import Role
from .scheduled_events import ScheduledEvent
from .sticker import GuildSticker, StickerItem
from .voice_client import VoiceClient, VoiceProtocol
__all__ = (
"Snowflake",
"User",
"PrivateChannel",
"GuildChannel",
"Messageable",
"Connectable",
"Mentionable",
)
T = TypeVar("T", bound=VoiceProtocol)
if TYPE_CHECKING:
from datetime import datetime
from .asset import Asset
from .channel import (
CategoryChannel,
DMChannel,
GroupChannel,
PartialMessageable,
StageChannel,
TextChannel,
VoiceChannel,
)
from .client import Client
from .embeds import Embed
from .enums import InviteTarget
from .flags import ChannelFlags
from .guild import Guild
from .member import Member
from .message import Message, MessageReference, PartialMessage
from .state import ConnectionState
from .threads import Thread
from .types.channel import Channel as ChannelPayload
from .types.channel import GuildChannel as GuildChannelPayload
from .types.channel import OverwriteType
from .types.channel import PermissionOverwrite as PermissionOverwritePayload
from .ui.view import View
from .user import ClientUser
PartialMessageableChannel = Union[
TextChannel, VoiceChannel, StageChannel, Thread, DMChannel, PartialMessageable
]
MessageableChannel = Union[PartialMessageableChannel, GroupChannel]
SnowflakeTime = Union["Snowflake", datetime]
MISSING = utils.MISSING
async def _single_delete_strategy(
messages: Iterable[Message], *, reason: str | None = None
):
for m in messages:
await m.delete(reason=reason)
async def _purge_messages_helper(
channel: TextChannel | Thread | VoiceChannel,
*,
limit: int | None = 100,
check: Callable[[Message], bool] = MISSING,
before: SnowflakeTime | None = None,
after: SnowflakeTime | None = None,
around: SnowflakeTime | None = None,
oldest_first: bool | None = False,
bulk: bool = True,
reason: str | None = None,
) -> list[Message]:
if check is MISSING:
check = lambda m: True
iterator = channel.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 = channel.delete_messages if bulk else _single_delete_strategy
async for message in iterator:
if count == 100:
to_delete = ret[-100:]
await strategy(to_delete, reason=reason)
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(reason=reason)
elif count >= 2:
to_delete = ret[-count:]
await strategy(to_delete, reason=reason)
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, reason=reason)
elif count == 1:
# delete a single message
await ret[-1].delete(reason=reason)
return ret
@runtime_checkable
class Snowflake(Protocol):
"""An ABC that details the common operations on a Discord model.
Almost all :ref:`Discord models <discord_api_models>` meet this
abstract base class.
If you want to create a snowflake on your own, consider using
:class:`.Object`.
Attributes
----------
id: :class:`int`
The model's unique ID.
"""
__slots__ = ()
id: int
@runtime_checkable
class User(Snowflake, Protocol):
"""An ABC that details the common operations on a Discord user.
The following implement this ABC:
- :class:`~discord.User`
- :class:`~discord.ClientUser`
- :class:`~discord.Member`
This ABC must also implement :class:`~discord.abc.Snowflake`.
Attributes
----------
name: :class:`str`
The user's username.
discriminator: :class:`str`
The user's discriminator.
.. note::
If the user has migrated to the new username system, this will always be "0".
global_name: :class:`str`
The user's global name.
.. versionadded:: 2.5
avatar: :class:`~discord.Asset`
The avatar asset the user has.
bot: :class:`bool`
If the user is a bot account.
"""
__slots__ = ()
name: str
discriminator: str
global_name: str | None
avatar: Asset
bot: bool
@property
def display_name(self) -> str:
"""Returns the user's display name."""
raise NotImplementedError
@property
def mention(self) -> str:
"""Returns a string that allows you to mention the given user."""
raise NotImplementedError
@runtime_checkable
class PrivateChannel(Snowflake, Protocol):
"""An ABC that details the common operations on a private Discord channel.
The following implement this ABC:
- :class:`~discord.DMChannel`
- :class:`~discord.GroupChannel`
This ABC must also implement :class:`~discord.abc.Snowflake`.
Attributes
----------
me: :class:`~discord.ClientUser`
The user presenting yourself.
"""
__slots__ = ()
me: ClientUser
class _Overwrites:
__slots__ = ("id", "allow", "deny", "type")
ROLE = 0
MEMBER = 1
def __init__(self, data: PermissionOverwritePayload):
self.id: int = int(data["id"])
self.allow: int = int(data.get("allow", 0))
self.deny: int = int(data.get("deny", 0))
self.type: OverwriteType = data["type"]
def _asdict(self) -> PermissionOverwritePayload:
return {
"id": self.id,
"allow": str(self.allow),
"deny": str(self.deny),
"type": self.type,
}
def is_role(self) -> bool:
return self.type == self.ROLE
def is_member(self) -> bool:
return self.type == self.MEMBER
GCH = TypeVar("GCH", bound="GuildChannel")
class GuildChannel:
"""An ABC that details the common operations on a Discord guild channel.
The following implement this ABC:
- :class:`~discord.TextChannel`
- :class:`~discord.VoiceChannel`
- :class:`~discord.CategoryChannel`
- :class:`~discord.StageChannel`
- :class:`~discord.ForumChannel`
This ABC must also implement :class:`~discord.abc.Snowflake`.
Attributes
----------
name: :class:`str`
The channel name.
guild: :class:`~discord.Guild`
The guild the channel belongs to.
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.
"""
__slots__ = ()
id: int
name: str
guild: Guild
type: ChannelType
position: int
category_id: int | None
flags: ChannelFlags
_state: ConnectionState
_overwrites: list[_Overwrites]
if TYPE_CHECKING:
def __init__(
self, *, state: ConnectionState, guild: Guild, data: dict[str, Any]
):
...
def __str__(self) -> str:
return self.name
@property
def _sorting_bucket(self) -> int:
raise NotImplementedError
def _update(self, guild: Guild, data: dict[str, Any]) -> None:
raise NotImplementedError
async def _move(
self,
position: int,
parent_id: Any | None = None,
lock_permissions: bool = False,
*,
reason: str | None,
) -> None:
if position < 0:
raise InvalidArgument("Channel position cannot be less than 0.")
http = self._state.http
bucket = self._sorting_bucket
channels: list[GuildChannel] = [
c for c in self.guild.channels if c._sorting_bucket == bucket
]
channels.sort(key=lambda c: c.position)
try:
# remove ourselves from the channel list
channels.remove(self)
except ValueError:
# not there somehow lol
return
else:
index = next(
(i for i, c in enumerate(channels) if c.position >= position),
len(channels),
)
# add ourselves at our designated position
channels.insert(index, self)
payload = []
for index, c in enumerate(channels):
d: dict[str, Any] = {"id": c.id, "position": index}
if parent_id is not MISSING and c.id == self.id:
d.update(parent_id=parent_id, lock_permissions=lock_permissions)
payload.append(d)
await http.bulk_channel_update(self.guild.id, payload, reason=reason)
async def _edit(
self, options: dict[str, Any], reason: str | None
) -> ChannelPayload | None:
try:
parent = options.pop("category")
except KeyError:
parent_id = MISSING
else:
parent_id = parent and parent.id
try:
options["rate_limit_per_user"] = options.pop("slowmode_delay")
except KeyError:
pass
try:
options["default_thread_rate_limit_per_user"] = options.pop(
"default_thread_slowmode_delay"
)
except KeyError:
pass
try:
if options.pop("require_tag"):
options["flags"] = ChannelFlags.require_tag.flag
except KeyError:
pass
try:
options["available_tags"] = [
tag.to_dict() for tag in options.pop("available_tags")
]
except KeyError:
pass
try:
rtc_region = options.pop("rtc_region")
except KeyError:
pass
else:
options["rtc_region"] = None if rtc_region is None else str(rtc_region)
try:
video_quality_mode = options.pop("video_quality_mode")
except KeyError:
pass
else:
options["video_quality_mode"] = int(video_quality_mode)
lock_permissions = options.pop("sync_permissions", False)
try:
position = options.pop("position")
except KeyError:
if parent_id is not MISSING:
if lock_permissions:
category = self.guild.get_channel(parent_id)
if category:
options["permission_overwrites"] = [
c._asdict() for c in category._overwrites
]
options["parent_id"] = parent_id
elif lock_permissions and self.category_id is not None:
# if we're syncing permissions on a pre-existing channel category without changing it
# we need to update the permissions to point to the pre-existing category
category = self.guild.get_channel(self.category_id)
if category:
options["permission_overwrites"] = [
c._asdict() for c in category._overwrites
]
else:
await self._move(
position,
parent_id=parent_id,
lock_permissions=lock_permissions,
reason=reason,
)
overwrites = options.get("overwrites")
if overwrites is not None:
perms = []
for target, perm in overwrites.items():
if not isinstance(perm, PermissionOverwrite):
raise InvalidArgument(
"Expected PermissionOverwrite received"
f" {perm.__class__.__name__}"
)
allow, deny = perm.pair()
payload = {
"allow": allow.value,
"deny": deny.value,
"id": target.id,
"type": (
_Overwrites.ROLE
if isinstance(target, Role)
else _Overwrites.MEMBER
),
}
perms.append(payload)
options["permission_overwrites"] = perms
try:
ch_type = options["type"]
except KeyError:
pass
else:
if not isinstance(ch_type, ChannelType):
raise InvalidArgument("type field must be of type ChannelType")
options["type"] = ch_type.value
try:
default_reaction_emoji = options["default_reaction_emoji"]
except KeyError:
pass
else:
if isinstance(default_reaction_emoji, _EmojiTag): # Emoji, PartialEmoji
default_reaction_emoji = default_reaction_emoji._to_partial()
elif isinstance(default_reaction_emoji, int):
default_reaction_emoji = PartialEmoji(
name=None, id=default_reaction_emoji
)
elif isinstance(default_reaction_emoji, str):
default_reaction_emoji = PartialEmoji.from_str(default_reaction_emoji)
else:
raise InvalidArgument(
"default_reaction_emoji must be of type: Emoji | int | str"
)
options[
"default_reaction_emoji"
] = default_reaction_emoji._to_forum_reaction_payload()
if options:
return await self._state.http.edit_channel(
self.id, reason=reason, **options
)
def _fill_overwrites(self, data: GuildChannelPayload) -> None:
self._overwrites = []
everyone_index = 0
everyone_id = self.guild.id
for index, overridden in enumerate(data.get("permission_overwrites", [])):
overwrite = _Overwrites(overridden)
self._overwrites.append(overwrite)
if overwrite.type == _Overwrites.MEMBER:
continue
if overwrite.id == everyone_id:
# the @everyone role is not guaranteed to be the first one
# in the list of permission overwrites, however the permission
# resolution code kind of requires that it is the first one in
# the list since it is special. So we need the index so we can
# swap it to be the first one.
everyone_index = index
# do the swap
tmp = self._overwrites
if tmp:
tmp[everyone_index], tmp[0] = tmp[0], tmp[everyone_index]
@property
def changed_roles(self) -> list[Role]:
"""Returns a list of roles that have been overridden from
their default values in the :attr:`~discord.Guild.roles` attribute.
"""
ret = []
g = self.guild
for overwrite in filter(lambda o: o.is_role(), self._overwrites):
role = g.get_role(overwrite.id)
if role is None:
continue
role = copy.copy(role)
role.permissions.handle_overwrite(overwrite.allow, overwrite.deny)
ret.append(role)
return ret
@property
def mention(self) -> str:
"""The string that allows you to mention the channel."""
return f"<#{self.id}>"
@property
def jump_url(self) -> str:
"""Returns a URL that allows the client to jump to the channel.
.. versionadded:: 2.0
"""
return f"https://discord.com/channels/{self.guild.id}/{self.id}"
@property
def created_at(self) -> datetime:
"""Returns the channel's creation time in UTC."""
return utils.snowflake_time(self.id)
def overwrites_for(self, obj: Role | User) -> PermissionOverwrite:
"""Returns the channel-specific overwrites for a member or a role.
Parameters
----------
obj: Union[:class:`~discord.Role`, :class:`~discord.abc.User`]
The role or user denoting
whose overwrite to get.
Returns
-------
:class:`~discord.PermissionOverwrite`
The permission overwrites for this object.
"""
if isinstance(obj, User):
predicate = lambda p: p.is_member()
elif isinstance(obj, Role):
predicate = lambda p: p.is_role()
else:
predicate = lambda p: True
for overwrite in filter(predicate, self._overwrites):
if overwrite.id == obj.id:
allow = Permissions(overwrite.allow)
deny = Permissions(overwrite.deny)
return PermissionOverwrite.from_pair(allow, deny)
return PermissionOverwrite()
@property
def overwrites(self) -> dict[Role | Member, PermissionOverwrite]:
"""Returns all of the channel's overwrites.
This is returned as a dictionary where the key contains the target which
can be either a :class:`~discord.Role` or a :class:`~discord.Member` and the value is the
overwrite as a :class:`~discord.PermissionOverwrite`.
Returns
-------
Dict[Union[:class:`~discord.Role`, :class:`~discord.Member`], :class:`~discord.PermissionOverwrite`]
The channel's permission overwrites.
"""
ret = {}
for ow in self._overwrites:
allow = Permissions(ow.allow)
deny = Permissions(ow.deny)
overwrite = PermissionOverwrite.from_pair(allow, deny)
target = None
if ow.is_role():
target = self.guild.get_role(ow.id)
elif ow.is_member():
target = self.guild.get_member(ow.id)
# TODO: There is potential data loss here in the non-chunked
# case, i.e. target is None because get_member returned nothing.
# This can be fixed with a slight breaking change to the return type,
# i.e. adding discord.Object to the list of it
# However, for now this is an acceptable compromise.
if target is not None:
ret[target] = overwrite
return ret
@property
def category(self) -> CategoryChannel | None:
"""The category this channel belongs to.
If there is no category then this is ``None``.
"""
return self.guild.get_channel(self.category_id) # type: ignore
@property
def permissions_synced(self) -> bool:
"""Whether the permissions for this channel are synced with the
category it belongs to.
If there is no category then this is ``False``.
.. versionadded:: 1.3
"""
if self.category_id is None:
return False
category = self.guild.get_channel(self.category_id)
return bool(category and category.overwrites == self.overwrites)
def permissions_for(self, obj: Member | Role, /) -> Permissions:
"""Handles permission resolution for the :class:`~discord.Member`
or :class:`~discord.Role`.
This function takes into consideration the following cases:
- Guild owner
- Guild roles
- Channel overrides
- Member overrides
If a :class:`~discord.Role` is passed, then it checks the permissions
someone with that role would have, which is essentially:
- The default role permissions
- The permissions of the role used as a parameter
- The default role permission overwrites
- The permission overwrites of the role used as a parameter
.. versionchanged:: 2.0
The object passed in can now be a role object.
Parameters
----------
obj: Union[:class:`~discord.Member`, :class:`~discord.Role`]
The object to resolve permissions for. This could be either
a member or a role. If it's a role then member overwrites
are not computed.
Returns
-------
:class:`~discord.Permissions`
The resolved permissions for the member or role.
"""
# The current cases can be explained as:
# Guild owner get all permissions -- no questions asked. Otherwise...
# The @everyone role gets the first application.
# After that, the applied roles that the user has in the channel
# (or otherwise) are then OR'd together.
# After the role permissions are resolved, the member permissions
# have to take into effect.
# After all that is done, you have to do the following:
# If manage permissions is True, then all permissions are set to True.
# The operation first takes into consideration the denied
# and then the allowed.
if self.guild.owner_id == obj.id:
return Permissions.all()
default = self.guild.default_role
base = Permissions(default.permissions.value if default else 0)
# Handle the role case first
if isinstance(obj, Role):
base.value |= obj._permissions
if base.administrator:
return Permissions.all()
# Apply @everyone allow/deny first since it's special
try:
maybe_everyone = self._overwrites[0]
if maybe_everyone.id == self.guild.id:
base.handle_overwrite(
allow=maybe_everyone.allow, deny=maybe_everyone.deny
)
except IndexError:
pass
if obj.is_default():
return base
overwrite = utils.get(self._overwrites, type=_Overwrites.ROLE, id=obj.id)
if overwrite is not None:
base.handle_overwrite(overwrite.allow, overwrite.deny)
return base
roles = obj._roles
get_role = self.guild.get_role
# Apply guild roles that the member has.
for role_id in roles:
role = get_role(role_id)
if role is not None:
base.value |= role._permissions
# Guild-wide Administrator -> True for everything
# Bypass all channel-specific overrides
if base.administrator:
return Permissions.all()
# Apply @everyone allow/deny first since it's special
try:
maybe_everyone = self._overwrites[0]
if maybe_everyone.id == self.guild.id:
base.handle_overwrite(
allow=maybe_everyone.allow, deny=maybe_everyone.deny
)
remaining_overwrites = self._overwrites[1:]
else:
remaining_overwrites = self._overwrites
except IndexError:
remaining_overwrites = self._overwrites
denies = 0
allows = 0
# Apply channel specific role permission overwrites
for overwrite in remaining_overwrites:
if overwrite.is_role() and roles.has(overwrite.id):
denies |= overwrite.deny
allows |= overwrite.allow
base.handle_overwrite(allow=allows, deny=denies)
# Apply member specific permission overwrites
for overwrite in remaining_overwrites:
if overwrite.is_member() and overwrite.id == obj.id:
base.handle_overwrite(allow=overwrite.allow, deny=overwrite.deny)
break
# if you can't send a message in a channel then you can't have certain
# permissions as well
if not base.send_messages:
base.send_tts_messages = False
base.mention_everyone = False
base.embed_links = False
base.attach_files = False
# if you can't read a channel then you have no permissions there
if not base.read_messages:
denied = Permissions.all_channel()
base.value &= ~denied.value
return base
async def delete(self, *, reason: str | None = None) -> None:
"""|coro|
Deletes the channel.
You must have :attr:`~discord.Permissions.manage_channels` permission to use this.
Parameters
----------
reason: Optional[:class:`str`]
The reason for deleting this channel.
Shows up on the audit log.
Raises
------
~discord.Forbidden
You do not have proper permissions to delete the channel.
~discord.NotFound
The channel was not found or was already deleted.
~discord.HTTPException
Deleting the channel failed.
"""
await self._state.http.delete_channel(self.id, reason=reason)
@overload
async def set_permissions(
self,
target: Member | Role,
*,
overwrite: PermissionOverwrite | None = ...,
reason: str | None = ...,
) -> None:
...
@overload
async def set_permissions(
self,
target: Member | Role,
*,
reason: str | None = ...,
**permissions: bool,
) -> None:
...
async def set_permissions(
self, target, *, overwrite=MISSING, reason=None, **permissions
):
r"""|coro|
Sets the channel specific permission overwrites for a target in the
channel.
The ``target`` parameter should either be a :class:`~discord.Member` or a
:class:`~discord.Role` that belongs to guild.
The ``overwrite`` parameter, if given, must either be ``None`` or
:class:`~discord.PermissionOverwrite`. For convenience, you can pass in
keyword arguments denoting :class:`~discord.Permissions` attributes. If this is
done, then you cannot mix the keyword arguments with the ``overwrite``
parameter.
If the ``overwrite`` parameter is ``None``, then the permission
overwrites are deleted.
You must have the :attr:`~discord.Permissions.manage_roles` permission to use this.
.. note::
This method *replaces* the old overwrites with the ones given.
Examples
----------
Setting allow and deny: ::
await message.channel.set_permissions(message.author, read_messages=True,
send_messages=False)
Deleting overwrites ::
await channel.set_permissions(member, overwrite=None)
Using :class:`~discord.PermissionOverwrite` ::
overwrite = discord.PermissionOverwrite()
overwrite.send_messages = False
overwrite.read_messages = True
await channel.set_permissions(member, overwrite=overwrite)
Parameters
-----------
target: Union[:class:`~discord.Member`, :class:`~discord.Role`]
The member or role to overwrite permissions for.
overwrite: Optional[:class:`~discord.PermissionOverwrite`]
The permissions to allow and deny to the target, or ``None`` to
delete the overwrite.
\*\*permissions
A keyword argument list of permissions to set for ease of use.
Cannot be mixed with ``overwrite``.
reason: Optional[:class:`str`]
The reason for doing this action. Shows up on the audit log.
Raises
-------
~discord.Forbidden
You do not have permissions to edit channel specific permissions.
~discord.HTTPException
Editing channel specific permissions failed.
~discord.NotFound
The role or member being edited is not part of the guild.
~discord.InvalidArgument
The overwrite parameter invalid or the target type was not
:class:`~discord.Role` or :class:`~discord.Member`.
"""
http = self._state.http
if isinstance(target, User):
perm_type = _Overwrites.MEMBER
elif isinstance(target, Role):
perm_type = _Overwrites.ROLE
else:
raise InvalidArgument("target parameter must be either Member or Role")
if overwrite is MISSING:
if len(permissions) == 0:
raise InvalidArgument("No overwrite provided.")
try:
overwrite = PermissionOverwrite(**permissions)
except (ValueError, TypeError):
raise InvalidArgument("Invalid permissions given to keyword arguments.")
elif len(permissions) > 0:
raise InvalidArgument("Cannot mix overwrite and keyword arguments.")
# TODO: wait for event
if overwrite is None:
await http.delete_channel_permissions(self.id, target.id, reason=reason)
elif isinstance(overwrite, PermissionOverwrite):
(allow, deny) = overwrite.pair()
await http.edit_channel_permissions(
self.id, target.id, allow.value, deny.value, perm_type, reason=reason
)
else:
raise InvalidArgument("Invalid overwrite type provided.")
async def _clone_impl(
self: GCH,
base_attrs: dict[str, Any],
*,
name: str | None = None,
reason: str | None = None,
) -> GCH:
base_attrs["permission_overwrites"] = [x._asdict() for x in self._overwrites]
base_attrs["parent_id"] = self.category_id
base_attrs["name"] = name or self.name
guild_id = self.guild.id
cls = self.__class__
data = await self._state.http.create_channel(
guild_id, self.type.value, reason=reason, **base_attrs
)
obj = cls(state=self._state, guild=self.guild, data=data)
# temporarily add it to the cache
self.guild._channels[obj.id] = obj # type: ignore
return obj
async def clone(
self: GCH, *, name: str | None = None, reason: str | None = None
) -> GCH:
"""|coro|
Clones this channel. This creates a channel with the same properties
as this channel.
You must have the :attr:`~discord.Permissions.manage_channels` permission to