add error handler

This commit is contained in:
grey-cat-1908 2022-04-10 16:31:53 +03:00
parent bd3c67d107
commit 3e82c4f78d
8 changed files with 48 additions and 53 deletions

View file

@ -4,6 +4,8 @@
import logging import logging
import asyncio import asyncio
import signal import signal
import sys
import traceback
from typing import Dict, List, Union, Any, Iterable, Optional from typing import Dict, List, Union, Any, Iterable, Optional
@ -59,15 +61,15 @@ class Client:
""" """
def __init__( def __init__(
self, self,
token: str, token: str,
*, *,
asyncio_debug: bool = False, asyncio_debug: bool = False,
intents: Union[Intents, Iterable[Intents]] = None, intents: Union[Intents, Iterable[Intents]] = None,
activity: Optional[Activity] = None, activity: Optional[Activity] = None,
status: str = None, status: str = None,
mobile: bool = False, mobile: bool = False,
logs: Union[None, int, str, Dict[str, Any]] = "INFO", logs: Union[None, int, str, Dict[str, Any]] = "INFO",
): ):
self.shards: Dict[int, Shard] = {} self.shards: Dict[int, Shard] = {}
self.http: HTTPClient = HTTPClient(token) self.http: HTTPClient = HTTPClient(token)
@ -85,7 +87,7 @@ class Client:
self.intents = sum(intents) self.intents = sum(intents)
elif intents is None: elif intents is None:
self.intents = ( self.intents = (
Intents.all() - Intents.GUILD_PRESENCES - Intents.GUILD_MEMBERS Intents.all() - Intents.GUILD_PRESENCES - Intents.GUILD_MEMBERS
) )
else: else:
self.intents = intents self.intents = intents
@ -135,6 +137,33 @@ class Client:
_logger.debug(f"Listener {callback.__qualname__} added successfully!") _logger.debug(f"Listener {callback.__qualname__} added successfully!")
return self return self
async def dispatch(
self,
name: str,
*args
):
"""
Dispatches an event
Parameters
----------
name: :class:`str`
Name of the event to dispatch.
"""
coro = self._events.get(name)
if coro is not None:
try:
await coro(*args)
except Exception as exc:
custom_error = self._events.get("on_error")
if custom_error is not None:
asyncio.ensure_future(custom_error(exc))
else:
print(f"Ignoring exception in {name}", file=sys.stderr)
traceback.print_exc()
def run(self) -> None: def run(self) -> None:
""" """
Run Bot without shards (only 0 shard) Run Bot without shards (only 0 shard)
@ -227,7 +256,7 @@ class Client:
return Guild.from_dict(data) return Guild.from_dict(data)
async def fetch_channel( async def fetch_channel(
self, channel_id: Union[Snowflake, str, int] self, channel_id: Union[Snowflake, str, int]
) -> Union[Channel, Any]: ) -> Union[Channel, Any]:
""" """
Fetch Channel from the Discord API (by id). Fetch Channel from the Discord API (by id).

View file

@ -3,8 +3,6 @@
from __future__ import annotations from __future__ import annotations
import asyncio
from ..utils.types import Coro from ..utils.types import Coro
from ..models.guild import Channel, ChannelType, channel_types_for_converting from ..models.guild import Channel, ChannelType, channel_types_for_converting
@ -18,10 +16,7 @@ async def channel_create_listener(self, gateway, payload: dict):
channel = channel_cls.from_dict(payload) channel = channel_cls.from_dict(payload)
custom_listener = self._events.get("on_channel_create") await self.dispatch("on_channel_create", channel)
if custom_listener is not None:
asyncio.ensure_future(custom_listener(channel))
return return

View file

@ -3,8 +3,6 @@
from __future__ import annotations from __future__ import annotations
import asyncio
from ..utils.types import Coro from ..utils.types import Coro
from ..models.guild import Channel, ChannelType, channel_types_for_converting from ..models.guild import Channel, ChannelType, channel_types_for_converting
@ -18,10 +16,7 @@ async def channel_delete_listener(self, gateway, payload: dict):
channel = channel_cls.from_dict(payload) channel = channel_cls.from_dict(payload)
custom_listener = self._events.get("on_channel_delete") await self.dispatch("on_channel_delete", channel)
if custom_listener is not None:
asyncio.ensure_future(custom_listener(channel))
return return

View file

@ -3,8 +3,6 @@
from __future__ import annotations from __future__ import annotations
import asyncio
from ..utils.types import Coro from ..utils.types import Coro
from ..models.guild import Channel, ChannelType, channel_types_for_converting from ..models.guild import Channel, ChannelType, channel_types_for_converting
@ -19,10 +17,7 @@ async def channel_update_listener(self, gateway, payload: dict):
channel = channel_cls.from_dict(payload) channel = channel_cls.from_dict(payload)
custom_listener = self._events.get("on_channel_update") await self.dispatch("on_channel_update", None, channel)
if custom_listener is not None:
asyncio.ensure_future(custom_listener(None, channel))
return return

View file

@ -3,8 +3,6 @@
from __future__ import annotations from __future__ import annotations
import asyncio
from ..utils.types import Coro from ..utils.types import Coro
from ..models.guild import Guild from ..models.guild import Guild
@ -21,10 +19,8 @@ async def guild_create_listener(self, gateway, payload: dict):
self.guilds[str(guild.id)] = guild self.guilds[str(guild.id)] = guild
custom_listener = self._events.get("on_guild_create") if guild_was_cached_as_none is False:
await self.dispatch("on_guild_create", guild)
if custom_listener is not None and guild_was_cached_as_none is False:
asyncio.ensure_future(custom_listener(guild))
return return

View file

@ -3,8 +3,6 @@
from __future__ import annotations from __future__ import annotations
import asyncio
from ..utils.types import Coro from ..utils.types import Coro
from ..models.guild import UnavailableGuild from ..models.guild import UnavailableGuild
@ -16,10 +14,7 @@ async def guild_delete_listener(self, gateway, payload: dict):
self.guilds.pop(guild.id, None) self.guilds.pop(guild.id, None)
custom_listener = self._events.get("on_guild_remove") await self.dispatch("on_guild_remove", guild)
if custom_listener is not None:
asyncio.ensure_future(custom_listener(guild))
return return

View file

@ -3,8 +3,6 @@
from __future__ import annotations from __future__ import annotations
import asyncio
from ..utils.types import Coro from ..utils.types import Coro
from ..models.guild import Guild from ..models.guild import Guild
@ -17,10 +15,7 @@ async def guild_update_listener(self, gateway, payload: dict):
self.guilds[new_guild.id] = new_guild self.guilds[new_guild.id] = new_guild
custom_listener = self._events.get("on_guild_update") await self.dispatch("on_channel_create", old_guild, new_guild)
if custom_listener is not None:
asyncio.ensure_future(custom_listener(old_guild, new_guild))
return return

View file

@ -3,8 +3,6 @@
from __future__ import annotations from __future__ import annotations
import asyncio
from ..utils.types import Coro from ..utils.types import Coro
from ..models.user import User from ..models.user import User
@ -20,10 +18,7 @@ async def on_ready_listener(self, gateway, payload: dict):
self.user = User.from_dict(payload.get("user")) self.user = User.from_dict(payload.get("user"))
custom_listener = self._events.get("on_shard_ready") await self.dispatch("on_shard_ready", gateway.shard_id)
if custom_listener is not None:
asyncio.ensure_future(custom_listener(gateway.shard_id))
return return