diff --git a/tchap-beta.py b/tchap-beta.py index 8649fe0..b63f463 100644 --- a/tchap-beta.py +++ b/tchap-beta.py @@ -1,16 +1,18 @@ import asyncio +from functools import wraps -from nio import MatrixRoom, Event, AsyncClient +from nio import MatrixRoom, Event from nio.crypto import ENCRYPTION_ENABLED from pydantic import Field from matrix_bot.bot import MatrixBot from matrix_bot.client import MatrixClient -from matrix_bot.callbacks import properly_fail from matrix_bot.eventparser import MessageEventParser, ignore_when_not_concerned, EventNotConcerned +from matrix_bot.config import logger from tchap_bot.config import Config + from markov import parle @@ -19,6 +21,29 @@ class ConfigProxy(Config): env_config = ConfigProxy() + +def properly_fail(function): + """use this decorator so that your async callback never crash, log the error and return a message to the room""" + + @wraps(function) + def decorated(room: MatrixRoom, message: Event, matrix_client: MatrixClient): + function_instance = function(room, message, matrix_client) + + async def inner(): + try: + return await function_instance + except Exception as unexpected_exception: # noqa + await matrix_client.send_text_message(room.room_id, "Oups, j'ai buggué 😿", "m.notice") + logger.warning(f"command failed with exception : {unexpected_exception}") + exit() + finally: + await matrix_client.room_typing(room.room_id, typing_state=False) + + return inner() + + return decorated + + # le décorateur @properly_fail va permettre à la commande de laisser un message d'erreur si la commande plante et # d'envoyer le message que le bot n'est plus en train d'écrire # la fonction va être appelée dans tous les cas, le décorateur @ignore_when_not_concerned