4 Commits

6 changed files with 64 additions and 62 deletions

View File

@ -28,7 +28,6 @@ from __future__ import annotations
import asyncio import asyncio
import collections import collections
import collections.abc import collections.abc
from functools import cached_property
import inspect import inspect
import importlib.util import importlib.util
@ -73,9 +72,7 @@ from .cog import Cog
if TYPE_CHECKING: if TYPE_CHECKING:
import importlib.machinery import importlib.machinery
from discord.role import Role
from discord.message import Message from discord.message import Message
from discord.abc import PartialMessageableChannel
from ._types import ( from ._types import (
Check, Check,
CoroFunc, CoroFunc,
@ -97,16 +94,9 @@ CXT = TypeVar("CXT", bound="Context")
class _FakeSlashMessage(discord.PartialMessage): class _FakeSlashMessage(discord.PartialMessage):
activity = application = edited_at = reference = webhook_id = None activity = application = edited_at = reference = webhook_id = None
attachments = components = reactions = stickers = [] attachments = components = reactions = stickers = mentions = []
tts = False
raw_mentions = discord.Message.raw_mentions
clean_content = discord.Message.clean_content
channel_mentions = discord.Message.channel_mentions
raw_role_mentions = discord.Message.raw_role_mentions
raw_channel_mentions = discord.Message.raw_channel_mentions
author: Union[discord.User, discord.Member] author: Union[discord.User, discord.Member]
tts = False
@classmethod @classmethod
def from_interaction( def from_interaction(
@ -118,22 +108,6 @@ class _FakeSlashMessage(discord.PartialMessage):
return self return self
@cached_property
def mentions(self) -> List[Union[discord.Member, discord.User]]:
client = self._state._get_client()
if self.guild:
ensure_user = lambda id: self.guild.get_member(id) or client.get_user(id) # type: ignore
else:
ensure_user = client.get_user
return discord.utils._unique(filter(None, map(ensure_user, self.raw_mentions)))
@cached_property
def role_mentions(self) -> List[Role]:
if self.guild is None:
return []
return discord.utils._unique(filter(None, map(self.guild.get_role, self.raw_role_mentions)))
def when_mentioned(bot: Union[Bot, AutoShardedBot], msg: Message) -> List[str]: def when_mentioned(bot: Union[Bot, AutoShardedBot], msg: Message) -> List[str]:
"""A callable that implements a command prefix equivalent to being mentioned. """A callable that implements a command prefix equivalent to being mentioned.

View File

@ -465,7 +465,6 @@ class Context(discord.abc.Messageable, Generic[BotT]):
kwargs.pop("nonce", None) kwargs.pop("nonce", None)
kwargs.pop("stickers", None) kwargs.pop("stickers", None)
kwargs.pop("reference", None) kwargs.pop("reference", None)
kwargs.pop("delete_after", None)
kwargs.pop("mention_author", None) kwargs.pop("mention_author", None)
if not ( if not (

View File

@ -337,7 +337,7 @@ class Interaction:
self._state.store_view(view, message.id) self._state.store_view(view, message.id)
return message return message
async def delete_original_message(self) -> None: async def delete_original_message(self, delay: Optional[float] = None) -> None:
"""|coro| """|coro|
Deletes the original interaction response message. Deletes the original interaction response message.
@ -345,6 +345,14 @@ class Interaction:
This is a lower level interface to :meth:`InteractionMessage.delete` in case This is a lower level interface to :meth:`InteractionMessage.delete` in case
you do not want to fetch the message and save an HTTP request. you do not want to fetch the message and save an HTTP request.
Parameters
------------
delay: Optional[:class:`float`]
If provided, the number of seconds to wait before deleting the message.
The waiting is done in the background and deletion failures are ignored.
.. versionadded:: 2.0
Raises Raises
------- -------
HTTPException HTTPException
@ -352,6 +360,8 @@ class Interaction:
Forbidden Forbidden
Deleted a message that is not yours. Deleted a message that is not yours.
""" """
if delay is not None:
await asyncio.sleep(delay)
adapter = async_context.get() adapter = async_context.get()
await adapter.delete_original_interaction_response( await adapter.delete_original_interaction_response(
self.application_id, self.application_id,
@ -460,6 +470,7 @@ class InteractionResponse:
view: View = MISSING, view: View = MISSING,
tts: bool = False, tts: bool = False,
ephemeral: bool = False, ephemeral: bool = False,
delete_after: Optional[float] = None,
) -> None: ) -> None:
"""|coro| """|coro|
@ -483,6 +494,9 @@ class InteractionResponse:
Indicates if the message should only be visible to the user who started the interaction. Indicates if the message should only be visible to the user who started the interaction.
If a view is sent with an ephemeral message and it has no timeout set then the timeout If a view is sent with an ephemeral message and it has no timeout set then the timeout
is set to 15 minutes. is set to 15 minutes.
delete_after: Optional[:class:`float`]
The amount of seconds the bot should wait before deleting the message sent.
.. versionadded:: 2.0
Raises Raises
------- -------
@ -539,6 +553,8 @@ class InteractionResponse:
self._parent._state.store_view(view) self._parent._state.store_view(view)
self.responded_at = utils.utcnow() self.responded_at = utils.utcnow()
if delete_after is not None:
self._parent.delete_original_message(delay=delete_after)
async def edit_message( async def edit_message(
self, self,
@ -733,7 +749,7 @@ class InteractionMessage(Message):
allowed_mentions=allowed_mentions, allowed_mentions=allowed_mentions,
) )
async def delete(self, *, delay: Optional[float] = None) -> None: async def delete(self, *, delay: Optional[float] = None, silent: bool = False) -> None:
"""|coro| """|coro|
Deletes the message. Deletes the message.
@ -743,6 +759,12 @@ class InteractionMessage(Message):
delay: Optional[:class:`float`] delay: Optional[:class:`float`]
If provided, the number of seconds to wait before deleting the message. If provided, the number of seconds to wait before deleting the message.
The waiting is done in the background and deletion failures are ignored. The waiting is done in the background and deletion failures are ignored.
silent: :class:`bool`
If silent is set to ``True``, the error will not be raised, it will be ignored.
This defaults to ``False`
.. versionadded:: 2.0
Raises Raises
------ ------
@ -757,12 +779,15 @@ class InteractionMessage(Message):
if delay is not None: if delay is not None:
async def inner_call(delay: float = delay): async def inner_call(delay: float = delay):
await asyncio.sleep(delay)
try: try:
await self._state._interaction.delete_original_message() await self._state._interaction.delete_original_message(delay=delay)
except HTTPException: except HTTPException:
pass pass
asyncio.create_task(inner_call()) asyncio.create_task(inner_call())
else: else:
await self._state._interaction.delete_original_message() try:
await self._state._interaction.delete_original_message(delay=delay)
except Exception:
if not silent:
raise

View File

@ -84,7 +84,6 @@ __all__ = (
"escape_mentions", "escape_mentions",
"as_chunks", "as_chunks",
"format_dt", "format_dt",
"generate_snowflake",
) )
DISCORD_EPOCH = 1420070400000 DISCORD_EPOCH = 1420070400000
@ -1021,23 +1020,3 @@ def format_dt(dt: datetime.datetime, /, style: Optional[TimestampStyle] = None)
if style is None: if style is None:
return f"<t:{int(dt.timestamp())}>" return f"<t:{int(dt.timestamp())}>"
return f"<t:{int(dt.timestamp())}:{style}>" return f"<t:{int(dt.timestamp())}:{style}>"
def generate_snowflake(dt: Optional[datetime.datetime] = None) -> int:
"""Returns a numeric snowflake pretending to be created at the given date but more accurate and random than time_snowflake.
If No dt is not passed, it makes one from the current time using utcnow.
Parameters
-----------
dt: :class:`datetime.datetime`
A datetime object to convert to a snowflake.
If naive, the timezone is assumed to be local time.
Returns
--------
:class:`int`
The snowflake representing the time given.
"""
dt = dt or utcnow()
return int(dt.timestamp() * 1000 - DISCORD_EPOCH) << 22 | 0x3fffff

View File

@ -717,7 +717,7 @@ class WebhookMessage(Message):
allowed_mentions=allowed_mentions, allowed_mentions=allowed_mentions,
) )
async def delete(self, *, delay: Optional[float] = None) -> None: async def delete(self, *, delay: Optional[float] = None, silent: bool = False) -> None:
"""|coro| """|coro|
Deletes the message. Deletes the message.
@ -727,6 +727,12 @@ class WebhookMessage(Message):
delay: Optional[:class:`float`] delay: Optional[:class:`float`]
If provided, the number of seconds to wait before deleting the message. If provided, the number of seconds to wait before deleting the message.
The waiting is done in the background and deletion failures are ignored. The waiting is done in the background and deletion failures are ignored.
silent: :class:`bool`
If silent is set to ``True``, the error will not be raised, it will be ignored.
This defaults to ``False`
.. versionadded:: 2.0
Raises Raises
------ ------
@ -741,15 +747,18 @@ class WebhookMessage(Message):
if delay is not None: if delay is not None:
async def inner_call(delay: float = delay): async def inner_call(delay: float = delay):
await asyncio.sleep(delay)
try: try:
await self._state._webhook.delete_message(self.id) await self._state._webhook.delete_message(self.id, delay)
except HTTPException: except HTTPException:
pass pass
asyncio.create_task(inner_call()) asyncio.create_task(inner_call())
else: else:
await self._state._webhook.delete_message(self.id) try:
await self._state._webhook.delete_message(self.id, delay)
except Exception:
if not silent:
raise
class BaseWebhook(Hashable): class BaseWebhook(Hashable):
@ -1270,6 +1279,7 @@ class Webhook(BaseWebhook):
view: View = MISSING, view: View = MISSING,
thread: Snowflake = MISSING, thread: Snowflake = MISSING,
wait: bool = False, wait: bool = False,
delete_after: Optional[float] = None,
) -> Optional[WebhookMessage]: ) -> Optional[WebhookMessage]:
"""|coro| """|coro|
@ -1335,6 +1345,11 @@ class Webhook(BaseWebhook):
The thread to send this webhook to. The thread to send this webhook to.
.. versionadded:: 2.0 .. versionadded:: 2.0
delete_after: Optional[:class:`float`]
If provided, the number of seconds to wait before deleting the message.
The waiting is done in the background and deletion failures are ignored.
.. versionadded:: 2.0
Raises Raises
-------- --------
@ -1416,6 +1431,9 @@ class Webhook(BaseWebhook):
if view is not MISSING and not view.is_finished(): if view is not MISSING and not view.is_finished():
message_id = None if msg is None else msg.id message_id = None if msg is None else msg.id
self._state.store_view(view, message_id) self._state.store_view(view, message_id)
if delete_after is not None and msg is not None:
await msg.delete(delay=delete_after)
return msg return msg
@ -1570,7 +1588,7 @@ class Webhook(BaseWebhook):
self._state.store_view(view, message_id) self._state.store_view(view, message_id)
return message return message
async def delete_message(self, message_id: int, /) -> None: async def delete_message(self, message_id: int, delay: Optional[float] = None, /) -> None:
"""|coro| """|coro|
Deletes a message owned by this webhook. Deletes a message owned by this webhook.
@ -1584,6 +1602,12 @@ class Webhook(BaseWebhook):
------------ ------------
message_id: :class:`int` message_id: :class:`int`
The message ID to delete. The message ID to delete.
delay: Optional[:class:`float`]
If provided, the number of seconds to wait before deleting the message.
The waiting is done in the background and deletion failures are ignored.
.. versionadded:: 2.0
Raises Raises
------- -------
@ -1595,6 +1619,9 @@ class Webhook(BaseWebhook):
if self.token is None: if self.token is None:
raise InvalidArgument("This webhook does not have a token associated with it") raise InvalidArgument("This webhook does not have a token associated with it")
if delay is not None:
await asyncio.sleep(delay)
adapter = async_context.get() adapter = async_context.get()
await adapter.delete_webhook_message( await adapter.delete_webhook_message(
self.id, self.id,

View File

@ -1136,8 +1136,6 @@ Utility Functions
.. autofunction:: discord.utils.as_chunks .. autofunction:: discord.utils.as_chunks
.. autofunction:: discord.utils.generate_snowflake
.. _discord-api-enums: .. _discord-api-enums:
Enumerations Enumerations