-
-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathinteractions.py
1774 lines (1523 loc) · 70.4 KB
/
interactions.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
# -*- coding: utf-8 -*-
"""
The MIT License (MIT)
Copyright (c) 2021-present mccoderpy
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 re
import asyncio
import logging
from typing import (
Any,
Dict,
List,
Match,
Optional,
overload,
Sequence,
Set,
Tuple,
TYPE_CHECKING,
Union
)
from typing_extensions import Literal
from . import abc, utils
from .monetization import Entitlement
from .object import Object
from .channel import _channel_factory, DMChannel, TextChannel, ThreadChannel, VoiceChannel, ForumPost, PartialMessageable
from .components import *
from .embeds import Embed
from .enums import (
ApplicationCommandType,
ComponentType,
Locale,
ChannelType,
InteractionCallbackType,
InteractionType, Locale,
MessageType,
OptionType,
try_enum
)
from .errors import AlreadyResponded, HTTPException, NotFound, UnknownInteraction
from .file import File
from .flags import MessageFlags
from .guild import Guild
from .http import handle_interaction_message_parameters, handle_message_parameters, HTTPClient
from .member import Member
from .mentions import AllowedMentions
from .message import Attachment, Message
from .permissions import Permissions
from .reaction import Reaction
from .role import Role
from .user import User
from .utils import cached_slot_property, MISSING
if TYPE_CHECKING:
import datetime
from .types.interaction import (
Interaction as InteractionPayload,
InteractionData as InteractionDataPayload,
ApplicationCommandInteractionDataOption as ApplicationCommandInteractionDataOptionPayload,
ResolvedData as ResolvedDataPayload
)
from .state import ConnectionState
from .components import BaseSelect
from .application_commands import SlashCommandOptionChoice, SlashCommand, MessageCommand, UserCommand
log = logging.getLogger(__name__)
__all__ = (
'EphemeralMessage',
'BaseInteraction',
'ApplicationCommandInteraction',
'ComponentInteraction',
'AutocompleteInteraction',
'ModalSubmitInteraction',
'option_str',
'option_float',
'option_int',
)
class EphemeralMessage:
"""
Like a normal :class:`~discord.Message` but with a modified :meth:`edit` method and without
:meth:`~discord.Message.delete` method.
"""
# This class will be removed in the future when we switched to use the WebhookMessage model instead
def __init__(self, *, state, channel, data, interaction):
self._state: ConnectionState = state
self.__interaction__: BaseInteraction = interaction
self.id = int(data.get('id', 0))
self.webhook_id = utils._get_as_snowflake(data, 'webhook_id')
self.channel_id = utils._get_as_snowflake(data, 'channel_id')
self.channel = channel
self._update(data)
def _update(self, data):
self.application = data.get('application')
self.activity = data.get('activity')
self._edited_timestamp = utils.parse_time(data['edited_timestamp'])
self.type = try_enum(MessageType, data['type'])
self._thread = data.get('thread', None)
self.pinned = data['pinned']
self.mention_everyone = data['mention_everyone']
for handler in (
'tts',
'content',
'embeds',
'author',
'member',
'mentions',
'mention_roles',
'flags',
'components',
'interaction',
'attachments',
'reactions'
):
try:
getattr(self, '_handle_%s' % handler)(data[handler])
except KeyError:
if not hasattr(self, handler):
setattr(
self,
handler,
None if handler not in {
'embeds',
'mentions',
'mentioned_roles',
'attachments',
'reactions',
'components'
} else []
) # bad solution for now but works, will be removed anyway when rewrite the existing webhook system
return self
def _handle_flags(self, value):
self.flags = MessageFlags._from_value(value)
def _handle_application(self, value):
self.application = value
def _handle_activity(self, value):
self.activity = value
def _handle_mention_everyone(self, value):
self.mention_everyone = value
def _handle_tts(self, value):
self.tts = value
def _handle_type(self, value):
self.type = try_enum(MessageType, value)
def _handle_content(self, value):
self.content = value
def _handle_attachments(self, value):
self.attachments = [Attachment(data=a, state=self._state) for a in value]
def _handle_embeds(self, value):
self.embeds = [Embed.from_dict(data) for data in value]
def _handle_interaction(self, value):
self.interaction = value
def _handle_components(self, value):
self.components = [ActionRow.from_dict(data) for data in value]
def _handle_reactions(self, value):
self.reactions = [Reaction(message=self, data=d) for d in value]
def _handle_nonce(self, value):
self.nonce = value
def _handle_author(self, author):
self.author = self._state.store_user(author)
if isinstance(self.guild, Guild):
found = self.guild.get_member(self.author.id)
if found is not None:
self.author = found
def _handle_member(self, member):
# The gateway now gives us full Member objects sometimes with the following keys
# deaf, mute, joined_at, roles
# For the sake of performance I'm going to assume that the only
# field that needs *updating* would be the joined_at field.
# If there is no Member object (for some strange reason), then we can upgrade
# ourselves to a more "partial" member object.
author = self.author
try:
# Update member reference
author._update_from_message(member)
except AttributeError:
# It's a user here
# TODO: consider adding to cache here
self.author = Member._from_message(message=self, data=member)
def _handle_mentions(self, mentions):
self.mentions = r = []
guild = self.guild
state = self._state
if not isinstance(guild, Guild):
self.mentions = [state.store_user(m) for m in mentions]
return
for mention in filter(None, mentions):
id_search = int(mention['id'])
member = guild.get_member(id_search)
if member is not None:
r.append(member)
else:
r.append(Member._try_upgrade(data=mention, guild=guild, state=state))
def _handle_mention_roles(self, role_mentions):
self.role_mentions = []
if isinstance(self.guild, Guild):
for role_id in map(int, role_mentions):
role = self.guild.get_role(role_id)
if role is not None:
self.role_mentions.append(role)
@utils.cached_slot_property('_cs_guild')
def guild(self):
"""Optional[:class:`Guild`]: The guild that the message belongs to, if applicable."""
return getattr(self.channel, 'guild', None)
def __repr__(self):
return '<EphemeralMessage id={0.id} channel={0.channel!r} type={0.type!r} author={0.author!r} flags={0.flags!r}>'.format(
self)
def __eq__(self, other):
return isinstance(other, self.__class__) and self.id == other.id
@property
def all_components(self):
"""Union[:class:`Button`, :ref:`Select <select-like-objects>`]:
Yields all buttons and selects that are contained in the message"""
for action_row in self.components:
yield from action_row
@property
def all_buttons(self):
"""Returns all :class:`Button`'s that are contained in the message"""
for action_row in self.components:
for component in action_row:
yield component
@property
def all_select_menus(self):
"""Returns all :ref:`Select <select-like-objects>`'s that are contained in the message"""
for action_row in self.components:
for component in action_row:
if int(component.type) in {3, 5, 6, 7, 8}:
yield component
async def edit(
self,
*,
content: Any = MISSING,
embed: Optional[Embed] = MISSING,
embeds: Sequence[Embed] = MISSING,
components: List[Union[ActionRow, List[Union[Button, BaseSelect]]]] = MISSING,
attachments: Sequence[Union[Attachment, File]] = MISSING,
keep_existing_attachments: bool = False,
allowed_mentions: Optional[AllowedMentions] = MISSING,
suppress_embeds: bool = False,
delete_after: Optional[float] = None
) -> Union[Message, EphemeralMessage]:
"""|coro|
Edits the message.
Parameters
-----------
content: Optional[:class:`str`]
The new content to replace the message with.
Could be ``None`` to remove the content.
embed: Optional[:class:`Embed`]
The new embed to replace the original with.
Could be ``None`` to remove all embeds.
embeds: Optional[List[:class:`Embed`]]
A list containing up to 10 embeds to send.
If ``None`` or empty, all embeds will be removed.
If passed, ``embed`` does also count towards the limit of 10 embeds.
components: List[Union[:class:`~discord.ActionRow`, List[Union[:class:`~discord.Button`, :ref:`Select <select-like-objects>`]]]]
A list of up to five :class:`~discord.ActionRow`s or :class:`list`,
each containing up to five :class:`~discord.Button` or one :ref:`Select <select-like-objects>` like object.
attachments: List[Union[:class:`Attachment`, :class:`File`]]
A list containing previous attachments to keep as well as new files to upload.
You can use ``keep_existing_attachments`` to auto-add the existing attachments to the list.
If an empty list (``[]``) is passed, all attachment will be removed.
.. note::
New files will always appear under existing ones.
keep_existing_attachments: :class:`bool`
Whether to auto-add existing attachments to ``attachments``, default :obj:`False`.
.. note::
Only needed when ``attachments`` are passed, otherwise will be ignored.
suppress_embeds: :class:`bool`
Whether to suppress embeds for the message. If ``True`` this will remove all embeds from the message.
If `´False`` it adds them back.
delete_after: :class:`float`
If provided, the number of seconds to wait in the background
before deleting the response we just edited. If the deletion fails,
then it is silently ignored.
allowed_mentions: Optional[:class:`~discord.AllowedMentions`]
Controls the mentions being processed in this message. If this is
passed, then the object is merged with :attr:`~discord.Client.allowed_mentions`.
The merging behaviour only overrides attributes that have been explicitly passed
to the object, otherwise it uses the attributes set in :attr:`~discord.Client.allowed_mentions`.
If no object is passed at all then the defaults given by :attr:`~discord.Client.allowed_mentions`
are used instead.
"""
if suppress_embeds:
flags = MessageFlags._from_value(self.flags.value)
flags.suppress_embeds = True
else:
flags = MISSING
if keep_existing_attachments:
if attachments is not MISSING:
attachments = [*self.attachments, *attachments]
state = self._state
interaction = self.__interaction__
if not self.channel:
self.channel = self._state.add_dm_channel(data=await state.http.get_channel(self.channel_id))
is_original_response = interaction.callback_message and self.id == interaction.callback_message.id
params = handle_message_parameters(
content=content,
flags=flags,
embed=embed,
embeds=embeds,
attachments=attachments,
components=components,
allowed_mentions=allowed_mentions,
previous_allowed_mentions=state.allowed_mentions
)
if is_original_response:
method = state.http.edit_original_interaction_response(
token=interaction._token,
application_id=interaction._application_id,
params=params
)
else:
method = state.http.edit_followup(
token=interaction._token,
application_id=interaction._application_id,
message_id=self.id,
params=params
)
with params:
data = await method
if not isinstance(data, dict):
if is_original_response:
return await interaction.get_original_callback()
else:
data = await state.http.get_followup_message(
token=interaction._token,
application_id=interaction._application_id,
message_id=self.id,
)
self._update(data)
if delete_after:
import warnings
warnings.warn("You can\'t delete a ephemeral message manual.")
return self
async def delete(self, *, delay: Optional[float] = None) -> None:
"""|coro|
Deletes the message.
.. note::
This can only be used while the interaction token is valid. So within 15 minutes after the interaction.
Parameters
-----------
delay: Optional[:class:`float`]
If provided, the number of seconds to wait in the background
before deleting the message. If the deletion fails then it is silently ignored.
Raises
------
NotFound
The message was deleted already or the interaction token expired
HTTPException
Deleting the message failed.
"""
interaction = self.__interaction__
is_original_response = interaction.callback_message and self.id == interaction.callback_message.id
if delay is not None:
async def delete():
await asyncio.sleep(delay)
try:
await self._state.http.delete_interaction_response(
interaction._token,
interaction._application_id,
message_id=self.id if not is_original_response else '@original'
)
except HTTPException:
pass
asyncio.ensure_future(delete(), loop=self._state.loop)
else:
await self._state.http.delete_interaction_response(
interaction._token,
interaction._application_id,
message_id=self.id if not is_original_response else '@original'
)
class BaseInteraction:
"""
The Base-Class for a discord-interaction like klick a :class:`~discord.Button`,
select (an) option(s) of :class:`~discord.SelectMenu` or using an application-command in discord
For more general information's about Interactions visit the Documentation of the
`Discord-API <https://discord.com/developers/docs/interactions/receiving-and-responding#interaction-object>`_
The following attributes are always available:
Attributes
------------
id: :class:`int`
The id of the interaction.
type: :class:`~discord.InteractionType`
The type of the interaction.
user_id: :class:`int`
The id of the user who triggered the interaction.
channel_id: :class:`int`
The id of the channel where the interaction was triggered.
entitlements: Optional[List[:class:`~discord.Entitlement`]]
For :ddocs:`monetized apps <monetization/overview>` entitlements of the user who triggered the interaction
and optionally, if any.
This is available for all interaction types.
data: :class:`~discord.InteractionData`
Some internal needed metadata for the interaction, depending on the type.
author_locale: Optional[:class:`~discord.Locale`]
The locale of the user who triggered the interaction.
guild_locale: Optional[:class:`~discord.Locale`]
The locale of the guild where the interaction was triggered.
guild_id: Optional[:class:`int`]
The id of the guild where the interaction was triggered, if any.
app_permissions: Optional[:class:`~discord.Permissions`]
The permissions of the bot in the channel where the interaction was triggered, if it was in a guild.
This is similar to `interaction.channel.permissions_for(interaction.guild.me)` but calculated on discord side.
author_permissions: Optional[:class:`~discord.Permissions`]
The author's permissions in the channel where the interaction was triggered, if it was in a guild.
This is similar to `interaction.channel.permissions_for(interaction.author)`, but calculated on discord side.
"""
if TYPE_CHECKING:
type: InteractionType
id: int
guild_id: Optional[int]
channel_id: int
user_id: int
user: User
author_locale: Locale
entitlements: Set[Entitlement]
app_permissions: Optional[Permissions]
author_permissions: Optional[Permissions]
member: Optional[Member]
guild_locale: Optional[Locale]
data: Optional[InteractionData]
message: Optional[Union[Message, EphemeralMessage]]
cached_message: Optional[Union[Message, EphemeralMessage]]
message_id: Optional[int]
def __init__(self, state: ConnectionState, data: InteractionPayload) -> None:
self._state: ConnectionState = state
self._http: HTTPClient = state.http
self._application_id = int(data.get('application_id'))
self._token = data['token']
self.type = InteractionType.try_value(data['type'])
self.id = int(data['id'])
self.guild_id = guild_id = utils._get_as_snowflake(data, 'guild_id')
self.entitlements = {Entitlement(data=e, state=state) for e in data.get('entitlements', [])}
channel_data = data.get('channel', {})
self.channel_id = channel_id = int(data.get('channel_id', channel_data.get('id', 0)))
guild = self.guild or Object(id=guild_id) if guild_id else None # I'm not sure if we need the Object thing here
if guild:
channel = guild.get_channel(self.channel_id)
member = data.get('member')
self.author_permissions = Permissions(int(member.get('permissions', 0)))
user = member.get('user')
self.app_permissions = Permissions(int(data.get('app_permissions', 0)))
self.user_id = user_id = int(user['id'])
self.member = guild.get_member(user_id) or Member(state=state, data=member, guild=guild)
self.guild_locale = try_enum(Locale, data.get('guild_locale'))
else:
channel = state._get_private_channel(channel_id)
user = data.get('user')
self.app_permissions = None
self.author_permissions = None
self.user_id = int(user['id'])
self.member = None
self.guild_locale = None
self.user = state.store_user(user)
if not channel:
factory, ch_type = _channel_factory(channel_data['type'])
if ch_type in (ChannelType.group, ChannelType.private):
# In my tests the required fields for those channels where always present
channel = factory(me=state.user, data=channel_data, state=state)
else:
channel = PartialMessageable(
state=state,
id=self.channel_id,
guild_id=self.guild_id,
type=ch_type,
partial_data=channel_data
)
self._channel = channel
message_data = data.get('message')
if message_data is not None:
if MessageFlags._from_value(message_data['flags']).ephemeral:
self.message = EphemeralMessage(state=state, channel=channel, data=message_data, interaction=self)
else:
self.message = Message(state=state, channel=channel, data=message_data)
# Remove this on release, it's unnecessary as we always get the full message (except reactions for components)
self.cached_message = self.message and state._get_message(self.message.id)
self.message_id = int(message_data['id'])
else:
self.message = None
self.cached_message = None
self.message_id = None
interaction_data = data.get('data')
if interaction_data is not None:
self.data = InteractionData(data=interaction_data,state=state, guild=self.guild, channel_id=self.channel_id)
else:
self.data = None
self.author_locale = try_enum(Locale, data['locale'])
self.deferred: bool = False
self.deferred_hidden: bool = False
self.deferred_modal: bool = False
self._command = None
self._callback_message: Optional[Union[Message, EphemeralMessage]] = None
self.messages: Dict[Union[str, int], Union[Message, EphemeralMessage]] = {}
def __repr__(self) -> str:
"""Represents a :class:`~discord.BaseInteraction` object."""
return f'<{self.__class__.__name__} {", ".join([f"{k}={v}" for k, v in self.__dict__.items() if k[0] != "_"])}>'
@property
def callback_message(self) -> Optional[Union[Message, EphemeralMessage]]:
"""Optional[Union[:class:`Message`, :class:`EphemeralMessage`]: The initial interaction response message, if any. (``@original``)"""
return self._callback_message
@callback_message.setter
def callback_message(self, value: Optional[Union[Message, EphemeralMessage]]) -> None:
self._callback_message = value
if value:
self.messages['@original'] = value
async def _defer(
self,
response_type: Optional[InteractionCallbackType] = InteractionCallbackType.deferred_update_msg,
hidden: Optional[bool] = False
) -> Optional[Union[Message, EphemeralMessage]]:
"""
|coro|
'Defers' the response.
If :attr:`response_type` is `InteractionCallbackType.deferred_msg_with_source` it shows a loading state to the user.
response_type: Optional[:class:`InteractionCallbackType`]
The type to response with, aiter :class:`InteractionCallbackType.deferred_msg_with_source` or :class:`InteractionCallbackType.deferred_update_msg` (e.g. 5 or 6)
hidden: Optional[:class:`bool`]
Whether to defer ephemerally(only the :attr:`author` of the interaction can see the message)
.. note::
Only for :class:`InteractionCallbackType.deferred_msg_with_source`.
.. important::
If you don't respond with a message using :meth:`respond`
or edit the original message using :meth:`edit` within less than 3 seconds,
discord will indicate that the interaction failed and the interaction-token will be invalidated.
To provide this us this method
.. note::
A Token will be Valid for 15 Minutes, so you could edit the original :attr:`message` with :meth:`edit`,
:meth:`respond` or doing anything other with this interaction for 15 minutes.
After that time you have to edit the original message with the Methode :meth:`edit` of the :attr:`message`
and send new messages with the :meth:`send` Methode of :attr:`channel`
(you could not do this hidden as it isn't a response anymore).
"""
if isinstance(response_type, int):
response_type = InteractionCallbackType.from_value(response_type)
if self.deferred:
raise AlreadyResponded(self.id)
base = {"type": int(response_type), "data": {'flags': 64 if hidden else None}}
try:
data = await self._http.post_initial_response(
data=base,
token=self._token,
interaction_id=self.id
)
except NotFound:
raise UnknownInteraction(self.id)
else:
self.deferred = True
if hidden is True:
self.deferred_hidden = True
if not data and response_type.msg_with_source or response_type.deferred_msg_with_source:
msg = self.callback_message = await self.get_original_callback()
return msg
async def _premium_required(self) -> None:
"""|coro|
Respond with an upgrade button, only available for apps
with :ddocs:`monetized apps <monetization/overview>` enabled.
"""
await self._state.http.post_initial_response(
self.id,
self._token,
data={'type': InteractionCallbackType.premium_required.value}
)
async def edit(
self,
*,
content: Any = MISSING,
embed: Optional[Embed] = MISSING,
embeds: Sequence[Embed] = MISSING,
components: List[Union[ActionRow, List[Union[Button, BaseSelect]]]] = MISSING,
attachments: Sequence[Union[Attachment, File]] = MISSING,
keep_existing_attachments: bool = False,
delete_after: Optional[float] = None,
allowed_mentions: Optional[AllowedMentions] = MISSING,
suppress_embeds: Optional[bool] = False
) -> Union[Message, EphemeralMessage]:
"""|coro|
Responds to the interaction by editing the original (:attr:`~ComponentInteraction.message`)
or :attr:`callback_message`, depending on the :attr:`~BaseInteraction.type`.
Parameters
-----------
content: Optional[:class:`str`]
The new content to replace the message with.
Could be ``None`` to remove the content.
embed: Optional[:class:`Embed`]
The new embed to replace the original with.
Could be ``None`` to remove all embeds.
embeds: Optional[List[:class:`Embed`]]
A list containing up to 10 embeds to send.
If ``None`` or empty, all embeds will be removed.
If passed, ``embed`` does also count towards the limit of 10 embeds.
components: List[Union[:class:`~discord.ActionRow`, List[Union[:class:`~discord.Button`, :ref:`Select <select-like-objects>`]]]]
A list of up to five :class:`~discord.ActionRow` or :class:`list`,
each containing up to five :class:`~discord.Button` or one :ref:`Select <select-like-objects>` like object.
attachments: List[Union[:class:`Attachment`, :class:`File`]]
A list containing previous attachments to keep as well as new files to upload.
You can use ``keep_existing_attachments`` to auto-add the existing attachments to the list.
If ``None`` or empty, all attachments will be removed.
.. note::
New files will always appear under existing ones.
keep_existing_attachments: :class:`bool`
Whether to auto-add existing attachments to ``attachments``, default :obj:`False`.
.. note::
Only needed when ``attachments`` are passed, otherwise will be ignored.
suppress_embeds: :class:`bool`
Whether to suppress embeds for the message. This removes
all the embeds if set to ``True``. If set to ``False``
this brings the embeds back if they were suppressed.
delete_after: Optional[:class:`float`]
If provided, the number of seconds to wait in the background
before deleting the response we just edited. If the deletion fails,
then it is silently ignored.
allowed_mentions: Optional[:class:`~discord.AllowedMentions`]
Controls the mentions being processed in this message. If this is
passed, then the object is merged with :attr:`~discord.Client.allowed_mentions`.
The merging behaviour only overrides attributes that have been explicitly passed
to the object, otherwise it uses the attributes set in :attr:`~discord.Client.allowed_mentions`.
If no object is passed at all then the defaults given by :attr:`~discord.Client.allowed_mentions`
are used instead.
Raises
-------
TypeError
The interaction was already responded to with a modal,
or it is an application-command that was not responded to.
NotFound:
The interaction is expired.
HTTPException
Editing the message failed.
Returns
--------
Union[:class:`~discord.Message`, :class:`~discord.EphemeralMessage`]
The edited message.
"""
if self.deferred_modal:
if self.type.Component:
return await self.message.edit(
content=content,
embed=embed,
embeds=embeds,
components=components,
attachments=attachments,
keep_existing_attachments=keep_existing_attachments,
allowed_mentions=allowed_mentions,
delete_after=delete_after,
suppress_embeds=suppress_embeds
)
else:
raise TypeError('You can\'t edit the message as it does not exist when using `respond_with_modal`.')
response_type = MISSING
if not self.deferred:
if self.type.ApplicationCommand:
raise TypeError('You need to send a response first before you can edit it')
else:
response_type = InteractionCallbackType.update_msg
m = self.callback_message if self.type.ApplicationCommand else self.message
if suppress_embeds is not MISSING:
flags = MessageFlags._from_value(m.flags.value) if m else MessageFlags._from_value(0)
flags.suppress_embeds = suppress_embeds
else:
flags = MISSING
state = self._state
if not self.channel:
ch = await self._http.get_channel(self.channel_id)
self.channel = _channel_factory(ch['type'])[0](state=state, data=ch)
if response_type is MISSING:
params = handle_message_parameters(
content=content,
flags=flags,
embed=embed,
embeds=embeds,
attachments=attachments,
components=components,
allowed_mentions=allowed_mentions,
previous_allowed_mentions=state.allowed_mentions
)
method = state.http.edit_original_interaction_response(
token=self._token,
application_id=self._application_id,
params=params
)
else:
params = handle_interaction_message_parameters(
type=response_type,
content=content,
flags=flags,
embed=embed,
embeds=embeds,
attachments=attachments,
components=components,
allowed_mentions=allowed_mentions,
previous_allowed_mentions=state.allowed_mentions
)
method = state.http.send_interaction_response(
interaction_id=self.id,
token=self._token,
params=params
)
with params:
data = await method
if not isinstance(data, dict):
msg = await self.get_original_callback()
else:
if m is not None:
msg = m._update(data)
else:
if MessageFlags._from_value(data['flags']).ephemeral:
msg = EphemeralMessage(state=self._state, data=data, channel=self.channel, interaction=self)
else:
msg = Message(state=self._state, channel=self.channel, data=data)
if not self.deferred:
self.callback_message = msg
is_hidden = msg.flags.ephemeral
if is_hidden:
self.deferred_hidden = True
self.deferred = True
if delete_after is not None:
await msg.delete(delay=delete_after)
return msg
async def respond(
self,
content: str = None, *,
tts: bool = False,
embed: Optional[Embed] = None,
embeds: Optional[List[Embed]] = None,
components: Optional[List[Union[ActionRow, List[Union[Button, BaseSelect]]]]] = None,
file: Optional[File] = None,
files: Optional[List[File]] = None,
delete_after: Optional[float] = None,
allowed_mentions: Optional[AllowedMentions] = None,
suppress_embeds: bool = False,
suppress_notifications: bool = False,
hidden: bool = False
) -> Union[Message, EphemeralMessage]:
"""|coro|
Responds to an interaction by sending a message.
Parameters
------------
content: :class:`str`
The content of the message to send.
tts: :class:`bool`
Indicates if the message should be sent using text-to-speech.
embed: :class:`~discord.Embed`
The rich embed for the content.
embeds: List[:class:`~discord.Embed`]
A list containing up to 10 embeds.
If passed, ``embed`` also counts towards the limit of 10.
components: List[Union[:class:`~discord.ActionRow`, List[Union[:class:`~discord.Button`, :ref:`Select <select-like-objects>`]]]]
A list of up to five :class:`~discord.ActionRow`s/:class:`list`s.
Each containing up to five :class:`~discord.Button` or one :ref:`Select <select-like-objects>` like object.
file: :class:`~discord.File`
The file to upload.
files: List[:class:`~discord.File`]
A :class:`list` of files to upload. Must be a maximum of 10.
suppress_embeds: :class:`bool`
Whether to suppress embeds for the message.
suppress_notifications: :class:`bool`
Whether to suppress desktop- & push-notifications for the post starter-message.
delete_after: :class:`float`
If provided, the number of seconds to wait in the background
before deleting the response we just sent. If the deletion fails,
then it is silently ignored.
allowed_mentions: :class:`~discord.AllowedMentions`
Controls the mentions being processed in this message. If this is
passed, then the object is merged with :attr:`~discord.Client.allowed_mentions`.
The merging behaviour only overrides attributes that have been explicitly passed
to the object, otherwise it uses the attributes set in :attr:`~discord.Client.allowed_mentions`.
If no object is passed at all then the defaults given by :attr:`~discord.Client.allowed_mentions`
are used instead.
hidden: Optional[:class:`bool`]
If :obj:`True` the message will be only visible for the performer of the interaction (e.g. :attr:`.author`).
Raises
-------
TypeError
This interaction was already responded to with a modal.
NotFound
The interaction has expired.
HTTPException
Responding to the interaction failed.
"""
if self.deferred_modal:
raise TypeError('After responding to the interaction with a modal, you can\'t respond.')
state = self._state
flags = MessageFlags._from_value(0)
flags.ephemeral = hidden
flags.suppress_embeds = suppress_embeds
flags.suppress_notifications = suppress_notifications
is_initial = False
response_type = MISSING
if not self.deferred:
response_type = InteractionCallbackType.msg_with_source
else:
if self.callback_message and (self.callback_message.flags.loading if self.type.ApplicationCommand else False):
is_initial = True
if response_type is MISSING:
params = handle_message_parameters(
content=content,
tts=tts,
flags=flags,
embed=embed or MISSING,
embeds=embeds or MISSING,
file=file or MISSING,
files=files or MISSING,
components=components or MISSING,
allowed_mentions=allowed_mentions,
previous_allowed_mentions=state.allowed_mentions
)
if is_initial:
method = state.http.edit_original_interaction_response(
token=self._token,
application_id=self._application_id,
params=params
)
else:
method = state.http.send_followup(
token=self._token,
application_id=self._application_id,
params=params
)
else:
params = handle_interaction_message_parameters(
type=response_type,
content=content,
tts=tts,
flags=flags,
embed=embed or MISSING,
embeds=embeds or MISSING,
file=file or MISSING,
files=files or MISSING,
components=components or MISSING,
allowed_mentions=allowed_mentions,
previous_allowed_mentions=state.allowed_mentions
)
method = state.http.send_interaction_response(
token=self._token,
interaction_id=self.id,
params=params
)
with params:
data = await method
if not isinstance(data, dict):
data = await self.get_original_callback(raw=True)
# We can't use the value from the params here because the message might be an edit/followup of the initial (hidden or not) response.
# Anyway, this will be removed in the future when we switched to use the webhook message modell for interactions.
is_hidden = MessageFlags._from_value(data['flags']).ephemeral
if is_hidden:
msg = EphemeralMessage(state=self._state, channel=self.channel, data=data, interaction=self)
else:
msg = Message(state=self._state, channel=self.channel, data=data)
if not self.callback_message or is_initial:
self.callback_message = msg
else:
self.messages[msg.id] = msg
if response_type is not MISSING or is_initial:
self.deferred = True