-
-
Notifications
You must be signed in to change notification settings - Fork 455
/
context.py
402 lines (327 loc) · 14.1 KB
/
context.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
"""
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
from typing import TYPE_CHECKING, Any, TypeVar
import discord.abc
from discord.interactions import Interaction, InteractionMessage, InteractionResponse
from discord.webhook.async_ import Webhook
if TYPE_CHECKING:
from typing_extensions import ParamSpec
import discord
from .. import Bot
from ..state import ConnectionState
from ..voice_client import VoiceProtocol
from .core import ApplicationCommand, Option
from ..interactions import InteractionChannel
from ..guild import Guild
from ..member import Member
from ..message import Message
from ..user import User
from ..permissions import Permissions
from ..client import ClientUser
from ..cog import Cog
from ..webhook import WebhookMessage
from typing import Callable, Awaitable
from ..utils import cached_property
T = TypeVar("T")
CogT = TypeVar("CogT", bound="Cog")
if TYPE_CHECKING:
P = ParamSpec("P")
else:
P = TypeVar("P")
__all__ = ("ApplicationContext", "AutocompleteContext")
class ApplicationContext(discord.abc.Messageable):
"""Represents a Discord application command interaction context.
This class is not created manually and is instead passed to application
commands as the first parameter.
.. versionadded:: 2.0
Attributes
----------
bot: :class:`.Bot`
The bot that the command belongs to.
interaction: :class:`.Interaction`
The interaction object that invoked the command.
command: :class:`.ApplicationCommand`
The command that this context belongs to.
"""
def __init__(self, bot: Bot, interaction: Interaction):
self.bot = bot
self.interaction = interaction
# below attributes will be set after initialization
self.command: ApplicationCommand = None # type: ignore
self.focused: Option = None # type: ignore
self.value: str = None # type: ignore
self.options: dict = None # type: ignore
self._state: ConnectionState = self.interaction._state
async def _get_channel(self) -> InteractionChannel | None:
return self.interaction.channel
async def invoke(
self,
command: ApplicationCommand[CogT, P, T],
/,
*args: P.args,
**kwargs: P.kwargs,
) -> T:
r"""|coro|
Calls a command with the arguments given.
This is useful if you want to just call the callback that a
:class:`.ApplicationCommand` holds internally.
.. note::
This does not handle converters, checks, cooldowns, pre-invoke,
or after-invoke hooks in any matter. It calls the internal callback
directly as-if it was a regular function.
You must take care in passing the proper arguments when
using this function.
Parameters
-----------
command: :class:`.ApplicationCommand`
The command that is going to be called.
\*args
The arguments to use.
\*\*kwargs
The keyword arguments to use.
Raises
-------
TypeError
The command argument to invoke is missing.
"""
return await command(self, *args, **kwargs)
@cached_property
def channel(self) -> InteractionChannel | None:
"""Union[:class:`abc.GuildChannel`, :class:`PartialMessageable`, :class:`Thread`]:
Returns the channel associated with this context's command. Shorthand for :attr:`.Interaction.channel`.
"""
return self.interaction.channel
@cached_property
def channel_id(self) -> int | None:
""":class:`int`: Returns the ID of the channel associated with this context's command.
Shorthand for :attr:`.Interaction.channel_id`.
"""
return self.interaction.channel_id
@cached_property
def guild(self) -> Guild | None:
"""Optional[:class:`.Guild`]: Returns the guild associated with this context's command.
Shorthand for :attr:`.Interaction.guild`.
"""
return self.interaction.guild
@cached_property
def guild_id(self) -> int | None:
""":class:`int`: Returns the ID of the guild associated with this context's command.
Shorthand for :attr:`.Interaction.guild_id`.
"""
return self.interaction.guild_id
@cached_property
def locale(self) -> str | None:
""":class:`str`: Returns the locale of the guild associated with this context's command.
Shorthand for :attr:`.Interaction.locale`.
"""
return self.interaction.locale
@cached_property
def guild_locale(self) -> str | None:
""":class:`str`: Returns the locale of the guild associated with this context's command.
Shorthand for :attr:`.Interaction.guild_locale`.
"""
return self.interaction.guild_locale
@cached_property
def app_permissions(self) -> Permissions:
return self.interaction.app_permissions
@cached_property
def me(self) -> Member | ClientUser | None:
"""Union[:class:`.Member`, :class:`.ClientUser`]:
Similar to :attr:`.Guild.me` except it may return the :class:`.ClientUser` in private message
message contexts, or when :meth:`Intents.guilds` is absent.
"""
return (
self.interaction.guild.me
if self.interaction.guild is not None
else self.bot.user
)
@cached_property
def message(self) -> Message | None:
"""Optional[:class:`.Message`]: Returns the message sent with this context's command.
Shorthand for :attr:`.Interaction.message`, if applicable.
"""
return self.interaction.message
@cached_property
def user(self) -> Member | User | None:
"""Union[:class:`.Member`, :class:`.User`]: Returns the user that sent this context's command.
Shorthand for :attr:`.Interaction.user`.
"""
return self.interaction.user
author: Member | User | None = user
@property
def voice_client(self) -> VoiceProtocol | None:
"""Optional[:class:`.VoiceProtocol`]: Returns the voice client associated with this context's command.
Shorthand for :attr:`Interaction.guild.voice_client<~discord.Guild.voice_client>`, if applicable.
"""
if self.interaction.guild is None:
return None
return self.interaction.guild.voice_client
@cached_property
def response(self) -> InteractionResponse:
""":class:`.InteractionResponse`: Returns the response object associated with this context's command.
Shorthand for :attr:`.Interaction.response`.
"""
return self.interaction.response
@property
def selected_options(self) -> list[dict[str, Any]] | None:
"""The options and values that were selected by the user when sending the command.
Returns
-------
Optional[List[Dict[:class:`str`, Any]]]
A dictionary containing the options and values that were selected by the user when the command
was processed, if applicable. Returns ``None`` if the command has not yet been invoked,
or if there are no options defined for that command.
"""
return self.interaction.data.get("options", None)
@property
def unselected_options(self) -> list[Option] | None:
"""The options that were not provided by the user when sending the command.
Returns
-------
Optional[List[:class:`.Option`]]
A list of Option objects (if any) that were not selected by the user when the command was processed.
Returns ``None`` if there are no options defined for that command.
"""
if self.command.options is not None: # type: ignore
if self.selected_options:
return [
option
for option in self.command.options # type: ignore
if option.to_dict()["name"]
not in [opt["name"] for opt in self.selected_options]
]
else:
return self.command.options # type: ignore
return None
@property
@discord.utils.copy_doc(InteractionResponse.send_modal)
def send_modal(self) -> Callable[..., Awaitable[Interaction]]:
return self.interaction.response.send_modal
async def respond(self, *args, **kwargs) -> Interaction | WebhookMessage:
"""|coro|
Sends either a response or a message using the followup webhook determined by whether the interaction
has been responded to or not.
Returns
-------
Union[:class:`discord.Interaction`, :class:`discord.WebhookMessage`]:
The response, its type depending on whether it's an interaction response or a followup.
"""
try:
if not self.interaction.response.is_done():
return await self.interaction.response.send_message(
*args, **kwargs
) # self.response
else:
return await self.followup.send(*args, **kwargs) # self.send_followup
except discord.errors.InteractionResponded:
return await self.followup.send(*args, **kwargs)
@property
@discord.utils.copy_doc(InteractionResponse.send_message)
def send_response(self) -> Callable[..., Awaitable[Interaction]]:
if not self.interaction.response.is_done():
return self.interaction.response.send_message
else:
raise RuntimeError(
f"Interaction was already issued a response. Try using {type(self).__name__}.send_followup() instead."
)
@property
@discord.utils.copy_doc(Webhook.send)
def send_followup(self) -> Callable[..., Awaitable[WebhookMessage]]:
if self.interaction.response.is_done():
return self.followup.send
else:
raise RuntimeError(
f"Interaction was not yet issued a response. Try using {type(self).__name__}.respond() first."
)
@property
@discord.utils.copy_doc(InteractionResponse.defer)
def defer(self) -> Callable[..., Awaitable[None]]:
return self.interaction.response.defer
@property
def followup(self) -> Webhook:
""":class:`Webhook`: Returns the followup webhook for followup interactions."""
return self.interaction.followup
async def delete(self, *, delay: float | None = None) -> None:
"""|coro|
Deletes the original interaction response message.
This is a higher level interface to :meth:`Interaction.delete_original_response`.
Parameters
----------
delay: Optional[:class:`float`]
If provided, the number of seconds to wait before deleting the message.
Raises
------
HTTPException
Deleting the message failed.
Forbidden
You do not have proper permissions to delete the message.
"""
if not self.interaction.response.is_done():
await self.defer()
return await self.interaction.delete_original_response(delay=delay)
@property
@discord.utils.copy_doc(Interaction.edit_original_response)
def edit(self) -> Callable[..., Awaitable[InteractionMessage]]:
return self.interaction.edit_original_response
@property
def cog(self) -> Cog | None:
"""Optional[:class:`.Cog`]: Returns the cog associated with this context's command.
``None`` if it does not exist.
"""
if self.command is None:
return None
return self.command.cog
class AutocompleteContext:
"""Represents context for a slash command's option autocomplete.
This class is not created manually and is instead passed to an :class:`.Option`'s autocomplete callback.
.. versionadded:: 2.0
Attributes
----------
bot: :class:`.Bot`
The bot that the command belongs to.
interaction: :class:`.Interaction`
The interaction object that invoked the autocomplete.
command: :class:`.ApplicationCommand`
The command that this context belongs to.
focused: :class:`.Option`
The option the user is currently typing.
value: :class:`.str`
The content of the focused option.
options: Dict[:class:`str`, Any]
A name to value mapping of the options that the user has selected before this option.
"""
__slots__ = ("bot", "interaction", "command", "focused", "value", "options")
def __init__(self, bot: Bot, interaction: Interaction):
self.bot = bot
self.interaction = interaction
self.command: ApplicationCommand = None # type: ignore
self.focused: Option = None # type: ignore
self.value: str = None # type: ignore
self.options: dict = None # type: ignore
@property
def cog(self) -> Cog | None:
"""Optional[:class:`.Cog`]: Returns the cog associated with this context's command.
``None`` if it does not exist.
"""
if self.command is None:
return None
return self.command.cog