mirror of
https://github.com/RYGhub/royalnet.git
synced 2024-11-23 19:44:20 +00:00
Handle errors in commands
This commit is contained in:
parent
72599e1c65
commit
a564e33efc
15 changed files with 61 additions and 20 deletions
|
@ -4,6 +4,7 @@ from royalnet.bots import TelegramBot
|
|||
from royalnet.commands import PingCommand, ShipCommand, SmecdsCommand, ColorCommand, CiaoruoziCommand, SyncCommand, DiarioCommand
|
||||
from royalnet.commands.debug_create import DebugCreateCommand
|
||||
from royalnet.commands.debug_author import DebugAuthorCommand
|
||||
from royalnet.commands.error_handler import ErrorHandlerCommand
|
||||
from royalnet.network import RoyalnetServer
|
||||
from royalnet.database.tables import Royal, Telegram
|
||||
|
||||
|
@ -13,7 +14,7 @@ commands = [PingCommand, ShipCommand, SmecdsCommand, ColorCommand, CiaoruoziComm
|
|||
DebugAuthorCommand, DiarioCommand]
|
||||
|
||||
master = RoyalnetServer("localhost", 1234, "sas")
|
||||
tg_bot = TelegramBot(os.environ["TG_AK"], "localhost:1234", "sas", commands, os.environ["DB_PATH"], Royal, Telegram, "tg_id")
|
||||
tg_bot = TelegramBot(os.environ["TG_AK"], "localhost:1234", "sas", commands, os.environ["DB_PATH"], Royal, Telegram, "tg_id", error_command=ErrorHandlerCommand)
|
||||
loop.create_task(master.run())
|
||||
loop.create_task(tg_bot.run())
|
||||
print("Starting loop...")
|
||||
|
|
|
@ -26,8 +26,8 @@ class TelegramBot:
|
|||
master_table,
|
||||
identity_table,
|
||||
identity_column_name: str,
|
||||
missing_command: Command = NullCommand,
|
||||
error_command: Command = NullCommand):
|
||||
missing_command: typing.Type[Command] = NullCommand,
|
||||
error_command: typing.Type[Command] = NullCommand):
|
||||
self.bot: telegram.Bot = telegram.Bot(api_key)
|
||||
self.should_run: bool = False
|
||||
self.offset: int = -100
|
||||
|
@ -54,7 +54,17 @@ class TelegramBot:
|
|||
alchemy = self.alchemy
|
||||
|
||||
async def reply(call, text: str):
|
||||
await asyncify(call.channel.send_message, text, parse_mode="HTML")
|
||||
escaped_text = text.replace("<", "<") \
|
||||
.replace(">", ">") \
|
||||
.replace("[b]", "<b>") \
|
||||
.replace("[/b]", "</b>") \
|
||||
.replace("[i]", "<i>") \
|
||||
.replace("[/i]", "</i>") \
|
||||
.replace("[u]", "<b>") \
|
||||
.replace("[/u]", "</b>") \
|
||||
.replace("[c]", "<pre>") \
|
||||
.replace("[/c]", "</pre>")
|
||||
await asyncify(call.channel.send_message, escaped_text, parse_mode="HTML")
|
||||
|
||||
async def net_request(call, message: Message, destination: str):
|
||||
response = await self.network.request(message, destination)
|
||||
|
@ -112,7 +122,7 @@ class TelegramBot:
|
|||
try:
|
||||
return await self.Call(message.chat, command, *parameters, update=update).run()
|
||||
except Exception as exc:
|
||||
return await self.Call(message.chat, self.error_command, *parameters, update=update, exception=exc).run()
|
||||
return await self.Call(message.chat, self.error_command, *parameters, update=update, exception=exc, previous_command=command).run()
|
||||
|
||||
async def handle_net_request(self, message: Message):
|
||||
pass
|
||||
|
|
|
@ -6,11 +6,12 @@ class CiaoruoziCommand(Command):
|
|||
|
||||
command_name = "ciaoruozi"
|
||||
command_title = "Saluta Ruozi, anche se non è più in RYG."
|
||||
command_syntax = ""
|
||||
|
||||
async def telegram(self, call: Call, args: CommandArgs):
|
||||
update: Update = args.kwargs["update"]
|
||||
user: User = update.effective_user
|
||||
if user.id == 112437036:
|
||||
await call.reply("Ciao me!")
|
||||
await call.reply("👋 Ciao me!")
|
||||
else:
|
||||
await call.reply("Ciao Ruozi!")
|
||||
await call.reply("👋 Ciao Ruozi!")
|
||||
|
|
|
@ -5,8 +5,9 @@ class ColorCommand(Command):
|
|||
|
||||
command_name = "color"
|
||||
command_title = "Invia un colore in chat...?"
|
||||
command_syntax = ""
|
||||
|
||||
async def common(self, call: Call, args: CommandArgs):
|
||||
await call.reply("""
|
||||
<i>I am sorry, unknown error occured during working with your request, Admin were notified</i>
|
||||
[i]I am sorry, unknown error occured during working with your request, Admin were notified[/i]
|
||||
""")
|
||||
|
|
|
@ -6,6 +6,7 @@ class DebugAuthorCommand(Command):
|
|||
|
||||
command_name = "debug_author"
|
||||
command_title = "Ottieni informazioni sull'autore di questa chiamata."
|
||||
command_syntax = ""
|
||||
|
||||
require_alchemy_tables = {Royal, Telegram}
|
||||
|
||||
|
@ -13,4 +14,4 @@ class DebugAuthorCommand(Command):
|
|||
author = await call.get_author()
|
||||
if author is None:
|
||||
await call.reply(f"☁️ L'autore di questa chiamata è sconosciuto.")
|
||||
await call.reply(f"🌞 <code>{str(author)}</code> è l'autore di questa chiamata.")
|
||||
await call.reply(f"🌞 [c]{str(author)}[/c] è l'autore di questa chiamata.")
|
||||
|
|
|
@ -5,7 +5,8 @@ from ..database.tables import Royal, Alias
|
|||
class DebugCreateCommand(Command):
|
||||
|
||||
command_name = "debug_create"
|
||||
command_title = "Create a new Royalnet user account"
|
||||
command_title = "Crea un nuovo account Royalnet"
|
||||
command_syntax = "(newusername)"
|
||||
|
||||
require_alchemy_tables = {Royal, Alias}
|
||||
|
||||
|
|
|
@ -9,6 +9,7 @@ class DiarioCommand(Command):
|
|||
|
||||
command_name = "diario"
|
||||
command_title = "Aggiungi una citazione al Diario."
|
||||
command_syntax = "\"(testo)\" --[autore], [contesto]"
|
||||
|
||||
require_alchemy_tables = {Royal, Diario, Alias}
|
||||
|
||||
|
@ -19,7 +20,6 @@ class DiarioCommand(Command):
|
|||
match = re.match(r'(!)? *["«‘“‛‟❛❝〝"`]([^"]+)["»’”❜❞〞"`] *(?:(?:-{1,2}|—) *([\w ]+))?(?:, *([^ ].*))?', text)
|
||||
# Find the corresponding matches
|
||||
if match is None:
|
||||
await call.reply(f"✅ Comando skippato per frase non valida")
|
||||
raise InvalidInputError("No match found.")
|
||||
spoiler = bool(match.group(1))
|
||||
text = match.group(2)
|
||||
|
@ -45,4 +45,4 @@ class DiarioCommand(Command):
|
|||
spoiler=spoiler)
|
||||
call.session.add(diario)
|
||||
await asyncify(call.session.commit)
|
||||
await call.reply(f"✅ Aggiunto al diario: <code>{repr(diario)}</code>")
|
||||
await call.reply(f"✅ Aggiunto al diario!")
|
||||
|
|
20
royalnet/commands/error_handler.py
Normal file
20
royalnet/commands/error_handler.py
Normal file
|
@ -0,0 +1,20 @@
|
|||
from ..utils import Command, CommandArgs, Call, InvalidInputError
|
||||
|
||||
|
||||
class ErrorHandlerCommand(Command):
|
||||
|
||||
command_name = "error_handler"
|
||||
command_title = "Gestisce gli errori causati dagli altri comandi."
|
||||
command_syntax = ""
|
||||
|
||||
async def telegram(self, call: Call, args: CommandArgs):
|
||||
try:
|
||||
exc = args.kwargs["exception"]
|
||||
except InvalidInputError:
|
||||
await call.reply("⚠️ Questo comando non può essere chiamato da solo.")
|
||||
return
|
||||
if isinstance(exc, InvalidInputError):
|
||||
command = args.kwargs["previous_command"]
|
||||
await call.reply(f"⚠️ Sintassi non valida.\nSintassi corretta:[c]/{command.command_name} {command.command_syntax}[/c]")
|
||||
return
|
||||
await call.reply("❌ Eccezione non gestita durante l'esecuzione del comando.")
|
|
@ -4,7 +4,8 @@ from ..utils import Command, CommandArgs, Call
|
|||
class NullCommand(Command):
|
||||
|
||||
command_name = "null"
|
||||
command_title = "Do nothing"
|
||||
command_title = "Non fa nulla."
|
||||
command_syntax = ""
|
||||
|
||||
async def common(self, call: Call, args: CommandArgs):
|
||||
pass
|
||||
|
|
|
@ -5,6 +5,7 @@ class PingCommand(Command):
|
|||
|
||||
command_name = "ping"
|
||||
command_title = "Ping pong!"
|
||||
command_syntax = ""
|
||||
|
||||
async def common(self, call: Call, args: CommandArgs):
|
||||
await call.reply("Pong!")
|
||||
await call.reply("🏓 Pong!")
|
||||
|
|
|
@ -2,13 +2,14 @@ import re
|
|||
from ..utils import Command, CommandArgs, Call, safeformat
|
||||
|
||||
|
||||
SHIP_RESULT = "💕 {one} + {two} = <b>{result}</b>"
|
||||
SHIP_RESULT = "💕 {one} + {two} = [b]{result}[/b]"
|
||||
|
||||
|
||||
class ShipCommand(Command):
|
||||
|
||||
command_name = "ship"
|
||||
command_title = "Create a ship between two items"
|
||||
command_title = "Crea una ship tra due cose."
|
||||
command_syntax = "(uno) (due)"
|
||||
|
||||
async def common(self, call: Call, args: CommandArgs):
|
||||
name_one = args[0]
|
||||
|
|
|
@ -55,6 +55,7 @@ class SmecdsCommand(Command):
|
|||
|
||||
command_name = "smecds"
|
||||
command_title = "Secondo me, è colpa dello stagista..."
|
||||
command_syntax = ""
|
||||
|
||||
async def common(self, call: Call, args: CommandArgs):
|
||||
ds = random.sample(DS_LIST, 1)[0]
|
||||
|
|
|
@ -7,7 +7,8 @@ from ..database.tables import Royal, Telegram
|
|||
class SyncCommand(Command):
|
||||
|
||||
command_name = "sync"
|
||||
command_title = "Connect your current account to Royalnet"
|
||||
command_title = "Connetti il tuo account attuale a Royalnet!"
|
||||
command_syntax = "(royalnetusername)"
|
||||
|
||||
require_alchemy_tables = {Royal, Telegram}
|
||||
|
||||
|
@ -36,13 +37,13 @@ class SyncCommand(Command):
|
|||
tg_last_name=user.last_name,
|
||||
tg_username=user.username)
|
||||
call.session.add(telegram)
|
||||
await call.reply(f"✅ Connessione completata: <code>{str(royal)}</code> ⬌ <code>{str(telegram)}</code>")
|
||||
await call.reply(f"✅ Connessione completata: [c]{str(royal)}[/c] ⬌ [c]{str(telegram)}[/c]")
|
||||
else:
|
||||
# Update the Telegram data
|
||||
# Avatar is WIP
|
||||
telegram.tg_first_name = user.first_name
|
||||
telegram.tg_last_name = user.last_name
|
||||
telegram.tg_username = user.username
|
||||
await call.reply(f"✅ Dati di <code>{str(telegram)}</code> aggiornati.")
|
||||
await call.reply(f"✅ Dati di [c]{str(telegram)}[/c] aggiornati.")
|
||||
# Commit the session
|
||||
await asyncify(call.session.commit())
|
||||
|
|
|
@ -26,4 +26,4 @@ class Diario:
|
|||
quoted_account = relationship("Royal", foreign_keys=quoted_account_id, backref="diario_quoted")
|
||||
|
||||
def __repr__(self):
|
||||
return f"<Diario diario_id={self.diario_id} creator_id={self.creator_id} quoted_account_id={self.quoted_account_id} quoted={self.quoted} text={self.text} context={self.context} timestamp={self.timestamp} media_url={self.media_url} spoiler={self.spoiler}>"
|
||||
return f"<Diario diario_id={self.diario_id} creator_id={self.creator_id} quoted_account_id={self.quoted_account_id} quoted={self.quoted} text={self.text} context={self.context} timestamp={self.timestamp} media_url={self.media_url} spoiler={self.spoiler}>"
|
||||
|
|
|
@ -38,6 +38,7 @@ class Command:
|
|||
|
||||
command_name: str = NotImplemented
|
||||
command_title: str = NotImplemented
|
||||
command_syntax: str = NotImplemented
|
||||
|
||||
require_alchemy_tables: typing.Set = set()
|
||||
|
||||
|
|
Loading…
Reference in a new issue