1
Fork 0
mirror of https://github.com/RYGhub/royalnet.git synced 2024-11-27 21:44:21 +00:00

Better exception handling

This commit is contained in:
Steffo 2018-09-13 18:38:21 +02:00
parent d6ed556713
commit 021009e785
3 changed files with 47 additions and 63 deletions

View file

@ -87,22 +87,6 @@ song_special_messages = {
"jump up superstar": ":arrow_forward: Is {song} the Tengen Toppa Guren Lagann opening?" "jump up superstar": ":arrow_forward: Is {song} the Tengen Toppa Guren Lagann opening?"
} }
# noinspection PyUnreachableCode
if __debug__:
version = "Dev"
commit_msg = "_in sviluppo_"
else:
# Find the latest git tag
old_wd = os.getcwd()
try:
os.chdir(os.path.dirname(__file__))
version = str(subprocess.check_output(["git", "describe", "--tags"]), encoding="utf8").strip()
commit_msg = str(subprocess.check_output(["git", "log", "-1", "--pretty=%B"]), encoding="utf8").strip()
except Exception:
version = ""
finally:
os.chdir(old_wd)
# FFmpeg settings # FFmpeg settings
ffmpeg_settings = {} ffmpeg_settings = {}
@ -111,8 +95,8 @@ executor = concurrent.futures.ThreadPoolExecutor(max_workers=3)
# Init the Sentry client # Init the Sentry client
sentry = raven.Client(config["Sentry"]["token"], sentry = raven.Client(config["Sentry"]["token"],
release=version, release=raven.fetch_git_sha(os.path.dirname(__file__)),
install_logger_hook=False, install_logging_hook=False,
hook_libraries=[]) hook_libraries=[])
@ -308,8 +292,6 @@ class RoyalDiscordBot(discord.Client):
self.main_guild = self.get_guild(int(config["Discord"]["server_id"])) self.main_guild = self.get_guild(int(config["Discord"]["server_id"]))
if not isinstance(self.main_guild, discord.Guild): if not isinstance(self.main_guild, discord.Guild):
raise InvalidConfigError("The main guild does not exist!") raise InvalidConfigError("The main guild does not exist!")
await self.main_channel.send(f" Royal Bot avviato e pronto a ricevere comandi!\n"
f"Ultimo aggiornamento: `{version}: {commit_msg}`")
await self.change_presence(status=discord.Status.online, activity=None) await self.change_presence(status=discord.Status.online, activity=None)
async def on_message(self, message: discord.Message): async def on_message(self, message: discord.Message):
@ -342,6 +324,7 @@ class RoyalDiscordBot(discord.Client):
async def on_error(self, event_method, *args, **kwargs): async def on_error(self, event_method, *args, **kwargs):
ei = sys.exc_info() ei = sys.exc_info()
logger.error(f"Critical error: {repr(ei[1])}") logger.error(f"Critical error: {repr(ei[1])}")
# noinspection PyBroadException
try: try:
await self.main_channel.send(f"☢️ **ERRORE CRITICO NELL'EVENTO** `{event_method}`\n" await self.main_channel.send(f"☢️ **ERRORE CRITICO NELL'EVENTO** `{event_method}`\n"
f"Il bot si è chiuso e si dovrebbe riavviare entro qualche minuto.\n" f"Il bot si è chiuso e si dovrebbe riavviare entro qualche minuto.\n"
@ -352,8 +335,8 @@ class RoyalDiscordBot(discord.Client):
f"```") f"```")
await self.change_presence(status=discord.Status.invisible) await self.change_presence(status=discord.Status.invisible)
await self.close() await self.close()
except Exception as e: except Exception:
logger.error("Double critical error: {repr(sys.exc_info())}") logger.error(f"Double critical error: {sys.exc_info()}")
loop.stop() loop.stop()
sentry.captureException(exc_info=ei) sentry.captureException(exc_info=ei)
exit(1) exit(1)

View file

@ -17,25 +17,9 @@ logging.getLogger().setLevel(level=logging.ERROR)
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
logger.setLevel(level=logging.DEBUG) logger.setLevel(level=logging.DEBUG)
# noinspection PyUnreachableCode
if __debug__:
version = "Dev"
commit_msg = "_in sviluppo_"
else:
# Find the latest git tag
old_wd = os.getcwd()
try:
os.chdir(os.path.dirname(__file__))
version = str(subprocess.check_output(["git", "describe", "--tags"]), encoding="utf8").strip()
commit_msg = str(subprocess.check_output(["git", "log", "-1", "--pretty=%B"]), encoding="utf8").strip()
except Exception:
version = ""
finally:
os.chdir(old_wd)
sentry = raven.Client(config["Sentry"]["token"], sentry = raven.Client(config["Sentry"]["token"],
release=version, release=raven.fetch_git_sha(os.path.dirname(__file__)),
install_logger_hook=False, install_logging_hook=False,
hook_libraries=[]) hook_libraries=[])

View file

@ -8,7 +8,7 @@ from telegram import Bot, Update, InlineKeyboardMarkup, InlineKeyboardButton
from telegram.ext import Updater, CommandHandler, CallbackQueryHandler from telegram.ext import Updater, CommandHandler, CallbackQueryHandler
import telegram.error import telegram.error
import dice import dice
import subprocess import sys
import os import os
import time import time
import cast import cast
@ -16,6 +16,7 @@ import re
import logging import logging
import configparser import configparser
import markovify import markovify
import raven
# Markov model # Markov model
try: try:
@ -34,21 +35,44 @@ config.read("config.ini")
discord_connection = None discord_connection = None
# Find the latest git tag # Init the Sentry client
if __debug__: sentry = raven.Client(config["Sentry"]["token"],
version = "Dev" release=raven.fetch_git_sha(os.path.dirname(__file__)),
commit_msg = "_in sviluppo_" install_logging_hook=False,
else: hook_libraries=[])
# Find the latest git tag
old_wd = os.getcwd()
def on_error(bot: Bot, update: Update, exc: Exception):
# noinspection PyBroadException
try: try:
os.chdir(os.path.dirname(__file__)) raise exc
version = str(subprocess.check_output(["git", "describe", "--tags"]), encoding="utf8").strip()
commit_msg = str(subprocess.check_output(["git", "log", "-1", "--pretty=%B"]), encoding="utf8").strip()
except Exception: except Exception:
version = "" logger.error(f"Critical error: {sys.exc_info()}")
finally: # noinspection PyBroadException
os.chdir(old_wd) try:
bot.send_message(int(config["Telegram"]["main_group"]),
"☢ **ERRORE CRITICO:** \n"
f"Il bot si è chiuso e si dovrebbe riavviare entro qualche minuto.\n"
f"Una segnalazione di errore è stata automaticamente mandata a @Steffo.\n\n"
f"Dettagli dell'errore:\n"
f"```\n"
f"{repr(ei[1])}\n"
f"```", parse_mode="Markdown")
except Exception:
logger.error(f"Double critical error: {sys.exc_info()}")
if not __debug__:
sentry.user_context({
"id": update.effective_user.id,
"telegram": {
"username": update.effective_user.username,
"first_name": update.effective_user.first_name,
"last_name": update.effective_user.last_name
}
})
sentry.extra_context({
"update": update.to_dict()
})
sentry.captureException()
def cmd_register(bot: Bot, update: Update): def cmd_register(bot: Bot, update: Update):
@ -506,14 +530,10 @@ def cmd_markov(bot: Bot, update: Update):
def cmd_roll(bot: Bot, update: Update): def cmd_roll(bot: Bot, update: Update):
dice_string = update.message.text.split(" ", 1)[1] dice_string = update.message.text.split(" ", 1)[1]
try: try:
result = dice.roll(dice_string) result = dice.roll(f"{dice_string}t")
except dice.DiceBaseException: except dice.DiceBaseException:
bot.send_message(update.message.chat.id, "⚠ Il tiro dei dadi è fallito. Controlla la sintassi!") bot.send_message(update.message.chat.id, "⚠ Il tiro dei dadi è fallito. Controlla la sintassi!")
return return
if isinstance(result, list):
result = "\n".join([str(r) for r in result])
elif isinstance(result, int):
result = str(result)
bot.send_message(update.message.chat.id, f"🎲 {result}") bot.send_message(update.message.chat.id, f"🎲 {result}")
@ -546,11 +566,8 @@ def process(arg_discord_connection):
u.dispatcher.add_handler(CommandHandler("roll", cmd_roll)) u.dispatcher.add_handler(CommandHandler("roll", cmd_roll))
u.dispatcher.add_handler(CommandHandler("r", cmd_roll)) u.dispatcher.add_handler(CommandHandler("r", cmd_roll))
u.dispatcher.add_handler(CallbackQueryHandler(on_callback_query)) u.dispatcher.add_handler(CallbackQueryHandler(on_callback_query))
u.dispatcher.add_error_handler(on_error)
logger.info("Handlers registered.") logger.info("Handlers registered.")
u.bot.send_message(config["Telegram"]["main_group"],
f" Royal Bot avviato e pronto a ricevere comandi!\n"
f"Ultimo aggiornamento: `{version}: {commit_msg}`",
parse_mode="Markdown", disable_notification=True)
while True: while True:
try: try:
u.start_polling() u.start_polling()