Add __dispatch__ method

This commit is contained in:
Louis Chauvet 2020-04-24 10:36:06 +02:00
parent 7a6003c931
commit 0a70d4039d
Signed by: fomys
GPG Key ID: 1ECA046A9615ABA0

View File

@ -1,13 +1,38 @@
import asyncio
import inspect import inspect
import traceback
from config import Config from config import Config
import os import os
import toml import toml
class BasePython: class BasePython:
def __init__(self, client): def __init__(self, client):
with open(os.path.join(os.path.dirname(inspect.getfile(self.__class__)),"infos.toml")) as f: with open(os.path.join(os.path.dirname(inspect.getfile(self.__class__)), "infos.toml")) as f:
self.infos = toml.load(f) self.infos = toml.load(f)
self.name = self.infos["name"] self.name = self.infos["name"]
self.client = client self.client = client
self.config = Config(path=os.path.join(client.config["data_folder"], self.name.lower())) self.config = Config(path=os.path.join(client.config["data_folder"], self.name.lower(), "config.toml"))
async def _run_event(self, coro, event_name, *args, **kwargs):
try:
await coro(*args, **kwargs)
except asyncio.CancelledError:
pass
except Exception:
traceback.print_exc()
try:
self.client.dispatch('error', event_name, *args, **kwargs)
except asyncio.CancelledError:
pass
def __dispatch__(self, event, *args, **kwargs):
method = 'on_' + event
try:
coro = getattr(self, method)
except AttributeError:
pass
else:
asyncio.ensure_future(self._run_event(coro, method, *args, **kwargs), loop=self.client.loop)