From 4735d145b684547fa72acfea979e25ea284c3096 Mon Sep 17 00:00:00 2001 From: Stefano Pigozzi Date: Tue, 9 Apr 2019 11:49:36 +0200 Subject: [PATCH] Add error_if_none parameter to call.get_author --- royalnet/bots/telegram.py | 6 ++++-- royalnet/commands/diario.py | 5 +---- royalnet/commands/error_handler.py | 5 ++++- royalnet/utils/__init__.py | 4 ++-- royalnet/utils/call.py | 9 +++++++-- 5 files changed, 18 insertions(+), 11 deletions(-) diff --git a/royalnet/bots/telegram.py b/royalnet/bots/telegram.py index c3bd336b..0aab1b40 100644 --- a/royalnet/bots/telegram.py +++ b/royalnet/bots/telegram.py @@ -4,7 +4,7 @@ import typing import logging as _logging import sys from ..commands import NullCommand -from ..utils import asyncify, Call, Command +from ..utils import asyncify, Call, Command, UnregisteredError from ..network import RoyalnetLink, Message from ..database import Alchemy, relationshiplinkchain @@ -71,10 +71,12 @@ class TelegramBot: response = await self.network.request(message, destination) return response - async def get_author(call): + async def get_author(call, error_if_none=False): update: telegram.Update = call.kwargs["update"] user: telegram.User = update.effective_user if user is None: + if error_if_none: + raise UnregisteredError("Author is not registered!") return None query = call.session.query(self.master_table) for link in self.identity_chain: diff --git a/royalnet/commands/diario.py b/royalnet/commands/diario.py index 7159bddf..c078cffc 100644 --- a/royalnet/commands/diario.py +++ b/royalnet/commands/diario.py @@ -45,10 +45,7 @@ class DiarioCommand(Command): @classmethod async def common(cls, call: Call): # Find the creator of the quotes - creator = await call.get_author() - if creator is None: - await call.reply("⚠️ Devi essere registrato a Royalnet per usare questo comando!") - return + creator = await call.get_author(error_if_none=True) # Recreate the full sentence raw_text = " ".join(call.args) # Pass the sentence through the diario regex diff --git a/royalnet/commands/error_handler.py b/royalnet/commands/error_handler.py index 744ff7c3..70c6a521 100644 --- a/royalnet/commands/error_handler.py +++ b/royalnet/commands/error_handler.py @@ -1,6 +1,6 @@ import traceback from logging import Logger -from ..utils import Command, CommandArgs, Call, InvalidInputError, UnsupportedError +from ..utils import Command, CommandArgs, Call, InvalidInputError, UnsupportedError, UnregisteredError class ErrorHandlerCommand(Command): @@ -24,6 +24,9 @@ class ErrorHandlerCommand(Command): command = call.kwargs["previous_command"] await call.reply(f"⚠️ Sintassi non valida.\nSintassi corretta: [c]/{command.command_name} {command.command_syntax}[/c]") return + if e_type == UnregisteredError: + await call.reply("⚠️ Devi essere registrato a Royalnet per usare questo comando!") + return await call.reply(f"❌ Eccezione non gestita durante l'esecuzione del comando:\n[b]{e_type.__name__}[/b]\n{e_value}") formatted_tb: str = '\n'.join(traceback.format_tb(e_tb)) call.logger.error(f"Unhandled exception - {e_type.__name__}: {e_value}\n{formatted_tb}") diff --git a/royalnet/utils/__init__.py b/royalnet/utils/__init__.py index 7768a23b..7060c955 100644 --- a/royalnet/utils/__init__.py +++ b/royalnet/utils/__init__.py @@ -1,9 +1,9 @@ from .asyncify import asyncify -from .call import Call +from .call import Call, UnregisteredError from .command import Command, CommandArgs, InvalidInputError, UnsupportedError, InvalidConfigError, ExternalError from .safeformat import safeformat from .classdictjanitor import cdj from .sleepuntil import sleep_until __all__ = ["asyncify", "Call", "Command", "safeformat", "InvalidInputError", "UnsupportedError", "CommandArgs", - "cdj", "InvalidConfigError", "ExternalError", "sleep_until"] + "cdj", "InvalidConfigError", "ExternalError", "sleep_until", "UnregisteredError"] diff --git a/royalnet/utils/call.py b/royalnet/utils/call.py index ab31c6bc..9d0afba2 100644 --- a/royalnet/utils/call.py +++ b/royalnet/utils/call.py @@ -10,6 +10,10 @@ if typing.TYPE_CHECKING: loop = asyncio.get_event_loop() +class UnregisteredError(Exception): + pass + + class Call: """A command call. Still an abstract class, subbots should create a new call from this.""" @@ -27,9 +31,10 @@ class Call: The data must be pickleable.""" raise NotImplementedError() - async def get_author(self): + async def get_author(self, error_if_none=False): """Try to find the universal identifier of the user that sent the message. - That probably means, the database row identifying the user.""" + That probably means, the database row identifying the user. + Raise a UnregisteredError if error_if_none is set to True and no author is found.""" raise NotImplementedError() # These parameters / methods should be left alone