Compare commits
19 Commits
Gnome-py/K
...
JDJGInc/2.
Author | SHA1 | Date | |
---|---|---|---|
46d6215646 | |||
c743034e99 | |||
da5ee84abe | |||
061b2e3d90 | |||
0e5cf0f840 | |||
7331957ee4 | |||
e9850566e8 | |||
2bd28a7990 | |||
343d533640 | |||
d2837a34f3 | |||
6a9083a504 | |||
655692d2cc | |||
c360611927 | |||
8bb8283ea8 | |||
675e3250e2 | |||
dea01b189b | |||
5963ec05ca | |||
5133a58d6d | |||
4277f65051 |
@ -28,6 +28,7 @@ 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
|
||||||
@ -72,7 +73,9 @@ 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,
|
||||||
@ -94,10 +97,17 @@ 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 = mentions = []
|
attachments = components = reactions = stickers = []
|
||||||
author: Union[discord.User, discord.Member]
|
|
||||||
tts = False
|
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]
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def from_interaction(
|
def from_interaction(
|
||||||
cls, interaction: discord.Interaction, channel: Union[discord.TextChannel, discord.DMChannel, discord.Thread]
|
cls, interaction: discord.Interaction, channel: Union[discord.TextChannel, discord.DMChannel, discord.Thread]
|
||||||
@ -108,6 +118,22 @@ 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.
|
||||||
|
@ -153,38 +153,38 @@ class GatewayRatelimiter:
|
|||||||
await asyncio.sleep(delta)
|
await asyncio.sleep(delta)
|
||||||
|
|
||||||
|
|
||||||
class KeepAliveHandler:
|
class KeepAliveHandler(threading.Thread):
|
||||||
def __init__(self, *, ws: DiscordWebSocket, shard_id: int = None, interval: float = None) -> None:
|
def __init__(self, *args: Any, **kwargs: Any) -> None:
|
||||||
|
ws = kwargs.pop("ws")
|
||||||
|
interval = kwargs.pop("interval", None)
|
||||||
|
shard_id = kwargs.pop("shard_id", None)
|
||||||
|
threading.Thread.__init__(self, *args, **kwargs)
|
||||||
self.ws: DiscordWebSocket = ws
|
self.ws: DiscordWebSocket = ws
|
||||||
self.shard_id: Optional[int] = shard_id
|
self._main_thread_id: int = ws.thread_id
|
||||||
self.interval: Optional[float] = interval
|
self.interval: Optional[float] = interval
|
||||||
self.heartbeat_timeout: float = self.ws._max_heartbeat_timeout
|
self.daemon: bool = True
|
||||||
|
self.shard_id: Optional[int] = shard_id
|
||||||
self.msg: str = "Keeping shard ID %s websocket alive with sequence %s."
|
self.msg: str = "Keeping shard ID %s websocket alive with sequence %s."
|
||||||
self.block_msg: str = "Shard ID %s heartbeat blocked for more than %s seconds."
|
self.block_msg: str = "Shard ID %s heartbeat blocked for more than %s seconds."
|
||||||
self.behind_msg: str = "Can't keep up, shard ID %s websocket is %.1fs behind."
|
self.behind_msg: str = "Can't keep up, shard ID %s websocket is %.1fs behind."
|
||||||
self._stop_ev: asyncio.Event = asyncio.Event()
|
self._stop_ev: threading.Event = threading.Event()
|
||||||
|
self._last_ack: float = time.perf_counter()
|
||||||
self._last_send: float = time.perf_counter()
|
self._last_send: float = time.perf_counter()
|
||||||
self._last_recv: float = time.perf_counter()
|
self._last_recv: float = time.perf_counter()
|
||||||
self._last_ack: float = time.perf_counter()
|
|
||||||
self.latency: float = float("inf")
|
self.latency: float = float("inf")
|
||||||
|
self.heartbeat_timeout: float = ws._max_heartbeat_timeout
|
||||||
|
|
||||||
async def run(self) -> None:
|
def run(self) -> None:
|
||||||
while True:
|
while not self._stop_ev.wait(self.interval):
|
||||||
try:
|
|
||||||
await asyncio.wait_for(self._stop_ev.wait(), timeout=self.interval)
|
|
||||||
except asyncio.TimeoutError:
|
|
||||||
pass
|
|
||||||
else:
|
|
||||||
return
|
|
||||||
|
|
||||||
if self._last_recv + self.heartbeat_timeout < time.perf_counter():
|
if self._last_recv + self.heartbeat_timeout < time.perf_counter():
|
||||||
_log.warning(
|
_log.warning(
|
||||||
"Shard ID %s has stopped responding to the gateway. Closing and restarting.", self.shard_id
|
"Shard ID %s has stopped responding to the gateway. Closing and restarting.", self.shard_id
|
||||||
)
|
)
|
||||||
|
coro = self.ws.close(4000)
|
||||||
|
f = asyncio.run_coroutine_threadsafe(coro, loop=self.ws.loop)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
await self.ws.close(4000)
|
f.result()
|
||||||
except Exception:
|
except Exception:
|
||||||
_log.exception("An error occurred while stopping the gateway. Ignoring.")
|
_log.exception("An error occurred while stopping the gateway. Ignoring.")
|
||||||
finally:
|
finally:
|
||||||
@ -193,18 +193,24 @@ class KeepAliveHandler:
|
|||||||
|
|
||||||
data = self.get_payload()
|
data = self.get_payload()
|
||||||
_log.debug(self.msg, self.shard_id, data["d"])
|
_log.debug(self.msg, self.shard_id, data["d"])
|
||||||
|
coro = self.ws.send_heartbeat(data)
|
||||||
|
f = asyncio.run_coroutine_threadsafe(coro, loop=self.ws.loop)
|
||||||
try:
|
try:
|
||||||
# block until sending is complete
|
# block until sending is complete
|
||||||
total = 0
|
total = 0
|
||||||
while True:
|
while True:
|
||||||
try:
|
try:
|
||||||
await asyncio.wait_for(self.ws.send_heartbeat(data), timeout=10)
|
f.result(10)
|
||||||
break
|
break
|
||||||
except asyncio.TimeoutError:
|
except concurrent.futures.TimeoutError:
|
||||||
total += 10
|
total += 10
|
||||||
|
try:
|
||||||
stack = "".join(traceback.format_stack())
|
frame = sys._current_frames()[self._main_thread_id]
|
||||||
msg = f"{self.block_msg}\nLoop traceback (most recent call last):\n{stack}"
|
except KeyError:
|
||||||
|
msg = self.block_msg
|
||||||
|
else:
|
||||||
|
stack = "".join(traceback.format_stack(frame))
|
||||||
|
msg = f"{self.block_msg}\nLoop thread traceback (most recent call last):\n{stack}"
|
||||||
_log.warning(msg, self.shard_id, total)
|
_log.warning(msg, self.shard_id, total)
|
||||||
|
|
||||||
except Exception:
|
except Exception:
|
||||||
@ -219,10 +225,6 @@ class KeepAliveHandler:
|
|||||||
"d": self.ws.sequence, # type: ignore
|
"d": self.ws.sequence, # type: ignore
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
def start(self) -> None:
|
|
||||||
self.ws.loop.create_task(self.run())
|
|
||||||
|
|
||||||
def stop(self) -> None:
|
def stop(self) -> None:
|
||||||
self._stop_ev.set()
|
self._stop_ev.set()
|
||||||
|
|
||||||
|
@ -84,6 +84,7 @@ __all__ = (
|
|||||||
"escape_mentions",
|
"escape_mentions",
|
||||||
"as_chunks",
|
"as_chunks",
|
||||||
"format_dt",
|
"format_dt",
|
||||||
|
"generate_snowflake",
|
||||||
)
|
)
|
||||||
|
|
||||||
DISCORD_EPOCH = 1420070400000
|
DISCORD_EPOCH = 1420070400000
|
||||||
@ -1020,3 +1021,23 @@ 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
|
@ -1136,6 +1136,8 @@ 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
|
||||||
|
Reference in New Issue
Block a user