forked from Pycord-Development/pycord
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttp.py
2862 lines (2524 loc) · 87 KB
/
http.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 logging
import sys
import weakref
from typing import TYPE_CHECKING, Any, Coroutine, Iterable, Sequence, TypeVar
from urllib.parse import quote as _uriquote
import aiohttp
from . import __version__, utils
from .errors import (
DiscordServerError,
Forbidden,
GatewayNotFound,
HTTPException,
InvalidArgument,
LoginFailure,
NotFound,
)
from .gateway import DiscordClientWebSocketResponse
from .utils import MISSING, warn_deprecated
_log = logging.getLogger(__name__)
if TYPE_CHECKING:
from types import TracebackType
from .enums import AuditLogAction, InteractionResponseType
from .file import File
from .types import (
appinfo,
audit_log,
automod,
channel,
components,
embed,
emoji,
guild,
integration,
interactions,
invite,
member,
message,
role,
scheduled_events,
sticker,
template,
threads,
user,
webhook,
welcome_screen,
widget,
)
from .types.snowflake import Snowflake, SnowflakeList
T = TypeVar("T")
BE = TypeVar("BE", bound=BaseException)
MU = TypeVar("MU", bound="MaybeUnlock")
Response = Coroutine[Any, Any, T]
API_VERSION: int = 10
async def json_or_text(response: aiohttp.ClientResponse) -> dict[str, Any] | str:
text = await response.text(encoding="utf-8")
try:
if response.headers["content-type"] == "application/json":
return utils._from_json(text)
except KeyError:
# Thanks Cloudflare
pass
return text
class Route:
def __init__(self, method: str, path: str, **parameters: Any) -> None:
self.path: str = path
self.method: str = method
url = self.base + self.path
if parameters:
url = url.format_map(
{
k: _uriquote(v) if isinstance(v, str) else v
for k, v in parameters.items()
}
)
self.url: str = url
# major parameters:
self.channel_id: Snowflake | None = parameters.get("channel_id")
self.guild_id: Snowflake | None = parameters.get("guild_id")
self.webhook_id: Snowflake | None = parameters.get("webhook_id")
self.webhook_token: str | None = parameters.get("webhook_token")
@property
def base(self) -> str:
return f"https://discord.com/api/v{API_VERSION}"
@property
def bucket(self) -> str:
# the bucket is just method + path w/ major parameters
return f"{self.channel_id}:{self.guild_id}:{self.path}"
class MaybeUnlock:
def __init__(self, lock: asyncio.Lock) -> None:
self.lock: asyncio.Lock = lock
self._unlock: bool = True
def __enter__(self: MU) -> MU:
return self
def defer(self) -> None:
self._unlock = False
def __exit__(
self,
exc_type: type[BE] | None,
exc: BE | None,
traceback: TracebackType | None,
) -> None:
if self._unlock:
self.lock.release()
# For some reason, the Discord voice websocket expects this header to be
# completely lowercase while aiohttp respects spec and does it as case-insensitive
aiohttp.hdrs.WEBSOCKET = "websocket" # type: ignore
class HTTPClient:
"""Represents an HTTP client sending HTTP requests to the Discord API."""
def __init__(
self,
connector: aiohttp.BaseConnector | None = None,
*,
proxy: str | None = None,
proxy_auth: aiohttp.BasicAuth | None = None,
loop: asyncio.AbstractEventLoop | None = None,
unsync_clock: bool = True,
) -> None:
self.loop: asyncio.AbstractEventLoop = (
asyncio.get_event_loop() if loop is None else loop
)
self.connector = connector
self.__session: aiohttp.ClientSession = MISSING # filled in static_login
self._locks: weakref.WeakValueDictionary = weakref.WeakValueDictionary()
self._global_over: asyncio.Event = asyncio.Event()
self._global_over.set()
self.token: str | None = None
self.bot_token: bool = False
self.proxy: str | None = proxy
self.proxy_auth: aiohttp.BasicAuth | None = proxy_auth
self.use_clock: bool = not unsync_clock
user_agent = (
"DiscordBot (https://pycord.dev, {0}) Python/{1[0]}.{1[1]} aiohttp/{2}"
)
self.user_agent: str = user_agent.format(
__version__, sys.version_info, aiohttp.__version__
)
def recreate(self) -> None:
if self.__session.closed:
self.__session = aiohttp.ClientSession(
connector=self.connector,
ws_response_class=DiscordClientWebSocketResponse,
)
async def ws_connect(self, url: str, *, compress: int = 0) -> Any:
kwargs = {
"proxy_auth": self.proxy_auth,
"proxy": self.proxy,
"max_msg_size": 0,
"timeout": 30.0,
"autoclose": False,
"headers": {
"User-Agent": self.user_agent,
},
"compress": compress,
}
return await self.__session.ws_connect(url, **kwargs)
async def request(
self,
route: Route,
*,
files: Sequence[File] | None = None,
form: Iterable[dict[str, Any]] | None = None,
**kwargs: Any,
) -> Any:
bucket = route.bucket
method = route.method
url = route.url
lock = self._locks.get(bucket)
if lock is None:
lock = asyncio.Lock()
if bucket is not None:
self._locks[bucket] = lock
# header creation
headers: dict[str, str] = {
"User-Agent": self.user_agent,
}
if self.token is not None:
headers["Authorization"] = f"Bot {self.token}"
# some checking if it's a JSON request
if "json" in kwargs:
headers["Content-Type"] = "application/json"
kwargs["data"] = utils._to_json(kwargs.pop("json"))
try:
reason = kwargs.pop("reason")
except KeyError:
pass
else:
if reason:
headers["X-Audit-Log-Reason"] = _uriquote(reason, safe="/ ")
if locale := kwargs.pop("locale", None):
headers["X-Discord-Locale"] = locale
kwargs["headers"] = headers
# Proxy support
if self.proxy is not None:
kwargs["proxy"] = self.proxy
if self.proxy_auth is not None:
kwargs["proxy_auth"] = self.proxy_auth
if not self._global_over.is_set():
# wait until the global lock is complete
await self._global_over.wait()
response: aiohttp.ClientResponse | None = None
data: dict[str, Any] | str | None = None
await lock.acquire()
with MaybeUnlock(lock) as maybe_lock:
for tries in range(5):
if files:
for f in files:
f.reset(seek=tries)
if form:
form_data = aiohttp.FormData(quote_fields=False)
for params in form:
form_data.add_field(**params)
kwargs["data"] = form_data
try:
async with self.__session.request(
method, url, **kwargs
) as response:
_log.debug(
"%s %s with %s has returned %s",
method,
url,
kwargs.get("data"),
response.status,
)
# even errors have text involved in them so this is safe to call
data = await json_or_text(response)
# check if we have rate limit header information
remaining = response.headers.get("X-Ratelimit-Remaining")
if remaining == "0" and response.status != 429:
# we've depleted our current bucket
delta = utils._parse_ratelimit_header(
response, use_clock=self.use_clock
)
_log.debug(
"A rate limit bucket has been exhausted (bucket: %s,"
" retry: %s).",
bucket,
delta,
)
maybe_lock.defer()
self.loop.call_later(delta, lock.release)
# the request was successful so just return the text/json
if 300 > response.status >= 200:
_log.debug("%s %s has received %s", method, url, data)
return data
# we are being rate limited
if response.status == 429:
if not response.headers.get("Via") or isinstance(data, str):
# Banned by Cloudflare more than likely.
raise HTTPException(response, data)
fmt = (
"We are being rate limited. Retrying in %.2f seconds."
' Handled under the bucket "%s"'
)
# sleep a bit
retry_after: float = data["retry_after"]
_log.warning(fmt, retry_after, bucket)
# check if it's a global rate limit
is_global = data.get("global", False)
if is_global:
_log.warning(
"Global rate limit has been hit. Retrying in %.2f"
" seconds.",
retry_after,
)
self._global_over.clear()
await asyncio.sleep(retry_after)
_log.debug("Done sleeping for the rate limit. Retrying...")
# release the global lock now that the
# global rate limit has passed
if is_global:
self._global_over.set()
_log.debug("Global rate limit is now over.")
continue
# we've received a 500, 502, or 504, unconditional retry
if response.status in {500, 502, 504}:
await asyncio.sleep(1 + tries * 2)
continue
# the usual error cases
if response.status == 403:
raise Forbidden(response, data)
elif response.status == 404:
raise NotFound(response, data)
elif response.status >= 500:
raise DiscordServerError(response, data)
else:
raise HTTPException(response, data)
# This is handling exceptions from the request
except OSError as e:
# Connection reset by peer
if tries < 4 and e.errno in (54, 10054):
await asyncio.sleep(1 + tries * 2)
continue
raise
if response is not None:
# We've run out of retries, raise.
if response.status >= 500:
raise DiscordServerError(response, data)
raise HTTPException(response, data)
raise RuntimeError("Unreachable code in HTTP handling")
async def get_from_cdn(self, url: str) -> bytes:
async with self.__session.get(url) as resp:
if resp.status == 200:
return await resp.read()
elif resp.status == 404:
raise NotFound(resp, "asset not found")
elif resp.status == 403:
raise Forbidden(resp, "cannot retrieve asset")
else:
raise HTTPException(resp, "failed to get asset")
# state management
async def close(self) -> None:
if self.__session:
await self.__session.close()
# login management
async def static_login(self, token: str) -> user.User:
# Necessary to get aiohttp to stop complaining about session creation
self.__session = aiohttp.ClientSession(
connector=self.connector, ws_response_class=DiscordClientWebSocketResponse
)
old_token = self.token
self.token = token
try:
data = await self.request(Route("GET", "/users/@me"))
except HTTPException as exc:
self.token = old_token
if exc.status == 401:
raise LoginFailure("Improper token has been passed.") from exc
raise
return data
def logout(self) -> Response[None]:
return self.request(Route("POST", "/auth/logout"))
# Group functionality
def start_group(
self, user_id: Snowflake, recipients: list[int]
) -> Response[channel.GroupDMChannel]:
payload = {
"recipients": recipients,
}
return self.request(
Route("POST", "/users/{user_id}/channels", user_id=user_id), json=payload
)
def leave_group(self, channel_id) -> Response[None]:
return self.request(
Route("DELETE", "/channels/{channel_id}", channel_id=channel_id)
)
# Message management
def start_private_message(self, user_id: Snowflake) -> Response[channel.DMChannel]:
payload = {
"recipient_id": user_id,
}
return self.request(Route("POST", "/users/@me/channels"), json=payload)
def send_message(
self,
channel_id: Snowflake,
content: str | None,
*,
tts: bool = False,
embed: embed.Embed | None = None,
embeds: list[embed.Embed] | None = None,
nonce: str | None = None,
allowed_mentions: message.AllowedMentions | None = None,
message_reference: message.MessageReference | None = None,
stickers: list[sticker.StickerItem] | None = None,
components: list[components.Component] | None = None,
flags: int | None = None,
) -> Response[message.Message]:
r = Route("POST", "/channels/{channel_id}/messages", channel_id=channel_id)
payload = {}
if content:
payload["content"] = content
if tts:
payload["tts"] = True
if embed:
payload["embeds"] = [embed]
if embeds:
payload["embeds"] = embeds
if nonce:
payload["nonce"] = nonce
if allowed_mentions:
payload["allowed_mentions"] = allowed_mentions
if message_reference:
payload["message_reference"] = message_reference
if components:
payload["components"] = components
if stickers:
payload["sticker_ids"] = stickers
if flags:
payload["flags"] = flags
return self.request(r, json=payload)
def send_typing(self, channel_id: Snowflake) -> Response[None]:
return self.request(
Route("POST", "/channels/{channel_id}/typing", channel_id=channel_id)
)
def send_multipart_helper(
self,
route: Route,
*,
files: Sequence[File],
content: str | None = None,
tts: bool = False,
embed: embed.Embed | None = None,
embeds: Iterable[embed.Embed | None] | None = None,
nonce: str | None = None,
allowed_mentions: message.AllowedMentions | None = None,
message_reference: message.MessageReference | None = None,
stickers: list[sticker.StickerItem] | None = None,
components: list[components.Component] | None = None,
flags: int | None = None,
) -> Response[message.Message]:
form = []
payload: dict[str, Any] = {"tts": tts}
if content:
payload["content"] = content
if embed:
payload["embeds"] = [embed]
if embeds:
payload["embeds"] = embeds
if nonce:
payload["nonce"] = nonce
if allowed_mentions:
payload["allowed_mentions"] = allowed_mentions
if message_reference:
payload["message_reference"] = message_reference
if components:
payload["components"] = components
if stickers:
payload["sticker_ids"] = stickers
if flags:
payload["flags"] = flags
attachments = []
form.append({"name": "payload_json"})
for index, file in enumerate(files):
attachments.append(
{
"id": index,
"filename": file.filename,
"description": file.description,
}
)
form.append(
{
"name": f"files[{index}]",
"value": file.fp,
"filename": file.filename,
"content_type": "application/octet-stream",
}
)
payload["attachments"] = attachments
form[0]["value"] = utils._to_json(payload)
return self.request(route, form=form, files=files)
def send_files(
self,
channel_id: Snowflake,
*,
files: Sequence[File],
content: str | None = None,
tts: bool = False,
embed: embed.Embed | None = None,
embeds: list[embed.Embed] | None = None,
nonce: str | None = None,
allowed_mentions: message.AllowedMentions | None = None,
message_reference: message.MessageReference | None = None,
stickers: list[sticker.StickerItem] | None = None,
components: list[components.Component] | None = None,
flags: int | None = None,
) -> Response[message.Message]:
r = Route("POST", "/channels/{channel_id}/messages", channel_id=channel_id)
return self.send_multipart_helper(
r,
files=files,
content=content,
tts=tts,
embed=embed,
embeds=embeds,
nonce=nonce,
allowed_mentions=allowed_mentions,
message_reference=message_reference,
stickers=stickers,
components=components,
flags=flags,
)
def edit_multipart_helper(
self,
route: Route,
files: Sequence[File],
**payload,
) -> Response[message.Message]:
form = []
attachments = []
form.append({"name": "payload_json"})
for index, file in enumerate(files):
attachments.append(
{
"id": index,
"filename": file.filename,
"description": file.description,
}
)
form.append(
{
"name": f"files[{index}]",
"value": file.fp,
"filename": file.filename,
"content_type": "application/octet-stream",
}
)
if "attachments" not in payload:
payload["attachments"] = attachments
else:
payload["attachments"].extend(attachments)
form[0]["value"] = utils._to_json(payload)
return self.request(route, form=form, files=files)
def edit_files(
self,
channel_id: Snowflake,
message_id: Snowflake,
files: Sequence[File],
**fields,
) -> Response[message.Message]:
r = Route(
"PATCH",
f"/channels/{channel_id}/messages/{message_id}",
channel_id=channel_id,
message_id=message_id,
)
payload: dict[str, Any] = {}
if "attachments" in fields:
payload["attachments"] = fields["attachments"]
if "flags" in fields:
payload["flags"] = fields["flags"]
if "content" in fields:
payload["content"] = fields["content"]
if "embeds" in fields:
payload["embeds"] = fields["embeds"]
if "allowed_mentions" in fields:
payload["allowed_mentions"] = fields["allowed_mentions"]
if "components" in fields:
payload["components"] = fields["components"]
return self.edit_multipart_helper(
r,
files=files,
**payload,
)
def delete_message(
self,
channel_id: Snowflake,
message_id: Snowflake,
*,
reason: str | None = None,
) -> Response[None]:
r = Route(
"DELETE",
"/channels/{channel_id}/messages/{message_id}",
channel_id=channel_id,
message_id=message_id,
)
return self.request(r, reason=reason)
def delete_messages(
self,
channel_id: Snowflake,
message_ids: SnowflakeList,
*,
reason: str | None = None,
) -> Response[None]:
r = Route(
"POST", "/channels/{channel_id}/messages/bulk-delete", channel_id=channel_id
)
payload = {
"messages": message_ids,
}
return self.request(r, json=payload, reason=reason)
def edit_message(
self, channel_id: Snowflake, message_id: Snowflake, **fields: Any
) -> Response[message.Message]:
r = Route(
"PATCH",
"/channels/{channel_id}/messages/{message_id}",
channel_id=channel_id,
message_id=message_id,
)
return self.request(r, json=fields)
def add_reaction(
self, channel_id: Snowflake, message_id: Snowflake, emoji: str
) -> Response[None]:
r = Route(
"PUT",
"/channels/{channel_id}/messages/{message_id}/reactions/{emoji}/@me",
channel_id=channel_id,
message_id=message_id,
emoji=emoji,
)
return self.request(r)
def remove_reaction(
self,
channel_id: Snowflake,
message_id: Snowflake,
emoji: str,
member_id: Snowflake,
) -> Response[None]:
r = Route(
"DELETE",
"/channels/{channel_id}/messages/{message_id}/reactions/{emoji}/{member_id}",
channel_id=channel_id,
message_id=message_id,
member_id=member_id,
emoji=emoji,
)
return self.request(r)
def remove_own_reaction(
self, channel_id: Snowflake, message_id: Snowflake, emoji: str
) -> Response[None]:
r = Route(
"DELETE",
"/channels/{channel_id}/messages/{message_id}/reactions/{emoji}/@me",
channel_id=channel_id,
message_id=message_id,
emoji=emoji,
)
return self.request(r)
def get_reaction_users(
self,
channel_id: Snowflake,
message_id: Snowflake,
emoji: str,
limit: int,
after: Snowflake | None = None,
) -> Response[list[user.User]]:
r = Route(
"GET",
"/channels/{channel_id}/messages/{message_id}/reactions/{emoji}",
channel_id=channel_id,
message_id=message_id,
emoji=emoji,
)
params: dict[str, Any] = {
"limit": limit,
}
if after:
params["after"] = after
return self.request(r, params=params)
def clear_reactions(
self, channel_id: Snowflake, message_id: Snowflake
) -> Response[None]:
r = Route(
"DELETE",
"/channels/{channel_id}/messages/{message_id}/reactions",
channel_id=channel_id,
message_id=message_id,
)
return self.request(r)
def clear_single_reaction(
self, channel_id: Snowflake, message_id: Snowflake, emoji: str
) -> Response[None]:
r = Route(
"DELETE",
"/channels/{channel_id}/messages/{message_id}/reactions/{emoji}",
channel_id=channel_id,
message_id=message_id,
emoji=emoji,
)
return self.request(r)
def get_message(
self, channel_id: Snowflake, message_id: Snowflake
) -> Response[message.Message]:
r = Route(
"GET",
"/channels/{channel_id}/messages/{message_id}",
channel_id=channel_id,
message_id=message_id,
)
return self.request(r)
def get_channel(self, channel_id: Snowflake) -> Response[channel.Channel]:
r = Route("GET", "/channels/{channel_id}", channel_id=channel_id)
return self.request(r)
def logs_from(
self,
channel_id: Snowflake,
limit: int,
before: Snowflake | None = None,
after: Snowflake | None = None,
around: Snowflake | None = None,
) -> Response[list[message.Message]]:
params: dict[str, Any] = {
"limit": limit,
}
if before is not None:
params["before"] = before
if after is not None:
params["after"] = after
if around is not None:
params["around"] = around
return self.request(
Route("GET", "/channels/{channel_id}/messages", channel_id=channel_id),
params=params,
)
def publish_message(
self, channel_id: Snowflake, message_id: Snowflake
) -> Response[message.Message]:
return self.request(
Route(
"POST",
"/channels/{channel_id}/messages/{message_id}/crosspost",
channel_id=channel_id,
message_id=message_id,
)
)
def pin_message(
self, channel_id: Snowflake, message_id: Snowflake, reason: str | None = None
) -> Response[None]:
r = Route(
"PUT",
"/channels/{channel_id}/pins/{message_id}",
channel_id=channel_id,
message_id=message_id,
)
return self.request(r, reason=reason)
def unpin_message(
self, channel_id: Snowflake, message_id: Snowflake, reason: str | None = None
) -> Response[None]:
r = Route(
"DELETE",
"/channels/{channel_id}/pins/{message_id}",
channel_id=channel_id,
message_id=message_id,
)
return self.request(r, reason=reason)
def pins_from(self, channel_id: Snowflake) -> Response[list[message.Message]]:
return self.request(
Route("GET", "/channels/{channel_id}/pins", channel_id=channel_id)
)
# Member management
def kick(
self, user_id: Snowflake, guild_id: Snowflake, reason: str | None = None
) -> Response[None]:
r = Route(
"DELETE",
"/guilds/{guild_id}/members/{user_id}",
guild_id=guild_id,
user_id=user_id,
)
return self.request(r, reason=reason)
def ban(
self,
user_id: Snowflake,
guild_id: Snowflake,
delete_message_seconds: int = None,
delete_message_days: int = None,
reason: str | None = None,
) -> Response[None]:
r = Route(
"PUT",
"/guilds/{guild_id}/bans/{user_id}",
guild_id=guild_id,
user_id=user_id,
)
params = {}
if delete_message_seconds:
params["delete_message_seconds"] = delete_message_seconds
elif delete_message_days:
warn_deprecated(
"delete_message_days",
"delete_message_seconds",
"2.2",
reference="https://github.com/discord/discord-api-docs/pull/5219",
)
params["delete_message_days"] = delete_message_days
return self.request(r, params=params, reason=reason)
def unban(
self, user_id: Snowflake, guild_id: Snowflake, *, reason: str | None = None
) -> Response[None]:
r = Route(
"DELETE",
"/guilds/{guild_id}/bans/{user_id}",
guild_id=guild_id,
user_id=user_id,
)
return self.request(r, reason=reason)
def guild_voice_state(
self,
user_id: Snowflake,
guild_id: Snowflake,
*,
mute: bool | None = None,
deafen: bool | None = None,
reason: str | None = None,
) -> Response[member.Member]:
r = Route(
"PATCH",
"/guilds/{guild_id}/members/{user_id}",
guild_id=guild_id,
user_id=user_id,
)
payload = {}
if mute is not None:
payload["mute"] = mute
if deafen is not None:
payload["deaf"] = deafen
return self.request(r, json=payload, reason=reason)
def edit_profile(self, payload: dict[str, Any]) -> Response[user.User]:
return self.request(Route("PATCH", "/users/@me"), json=payload)
def change_my_nickname(
self,
guild_id: Snowflake,
nickname: str,
*,
reason: str | None = None,
) -> Response[member.Nickname]:
r = Route("PATCH", "/guilds/{guild_id}/members/@me", guild_id=guild_id)
payload = {
"nick": nickname,
}
return self.request(r, json=payload, reason=reason)
def change_nickname(
self,
guild_id: Snowflake,
user_id: Snowflake,
nickname: str,
*,
reason: str | None = None,
) -> Response[member.Member]:
r = Route(
"PATCH",
"/guilds/{guild_id}/members/{user_id}",
guild_id=guild_id,
user_id=user_id,
)
payload = {
"nick": nickname,
}
return self.request(r, json=payload, reason=reason)
def edit_my_voice_state(
self, guild_id: Snowflake, payload: dict[str, Any]
) -> Response[None]:
r = Route("PATCH", "/guilds/{guild_id}/voice-states/@me", guild_id=guild_id)
return self.request(r, json=payload)
def edit_voice_state(
self, guild_id: Snowflake, user_id: Snowflake, payload: dict[str, Any]
) -> Response[None]:
r = Route(
"PATCH",
"/guilds/{guild_id}/voice-states/{user_id}",
guild_id=guild_id,
user_id=user_id,
)
return self.request(r, json=payload)