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

Handle database sessions in the telegram bot differently

This commit is contained in:
Steffo 2019-02-09 20:10:52 +01:00
parent 11b119b08e
commit 80a2a7642b

View file

@ -75,11 +75,13 @@ def reply(bot: telegram.Bot, update: telegram.Update, string: str, ignore_escapi
pass pass
def catch_and_report(func: "function"): # noinspection PyUnresolvedReferences
def command(func: "function"):
def new_func(bot: telegram.Bot, update: telegram.Update): def new_func(bot: telegram.Bot, update: telegram.Update):
# noinspection PyBroadException # noinspection PyBroadException
try: try:
return func(bot, update) session = db.Session()
return func(bot, update, session)
except TimedOut: except TimedOut:
logger.warning(f"Telegram timed out in {update}") logger.warning(f"Telegram timed out in {update}")
except Exception: except Exception:
@ -104,16 +106,18 @@ def catch_and_report(func: "function"):
"update": update.to_dict() "update": update.to_dict()
}) })
sentry.captureException() sentry.captureException()
finally:
session.close()
return new_func return new_func
@catch_and_report @command
def cmd_ping(bot: telegram.Bot, update: telegram.Update): def cmd_ping(bot: telegram.Bot, update: telegram.Update, session: db.Session):
reply(bot, update, strings.PONG) reply(bot, update, strings.PONG)
@catch_and_report @command
def cmd_link(bot: telegram.Bot, update: telegram.Update): def cmd_link(bot: telegram.Bot, update: telegram.Update, session: db.Session):
session = db.Session() session = db.Session()
try: try:
try: try:
@ -141,8 +145,8 @@ def cmd_link(bot: telegram.Bot, update: telegram.Update):
session.close() session.close()
@catch_and_report @command
def cmd_cv(bot: telegram.Bot, update: telegram.Update): def cmd_cv(bot: telegram.Bot, update: telegram.Update, session: db.Session):
if discord_connection is None: if discord_connection is None:
reply(bot, update, strings.TELEGRAM.ERRORS.INACTIVE_BRIDGE) reply(bot, update, strings.TELEGRAM.ERRORS.INACTIVE_BRIDGE)
return return
@ -155,8 +159,8 @@ def cmd_cv(bot: telegram.Bot, update: telegram.Update):
bot.send_message(update.message.chat.id, message, disable_web_page_preview=True, parse_mode="HTML") bot.send_message(update.message.chat.id, message, disable_web_page_preview=True, parse_mode="HTML")
@catch_and_report @command
def cmd_cast(bot: telegram.Bot, update: telegram.Update): def cmd_cast(bot: telegram.Bot, update: telegram.Update, session: db.Session):
try: try:
spell: str = update.message.text.split(" ", 1)[1] spell: str = update.message.text.split(" ", 1)[1]
except IndexError: except IndexError:
@ -176,28 +180,28 @@ def cmd_cast(bot: telegram.Bot, update: telegram.Update):
parse_mode="HTML") parse_mode="HTML")
@catch_and_report @command
def cmd_color(bot: telegram.Bot, update: telegram.Update): def cmd_color(bot: telegram.Bot, update: telegram.Update, session: db.Session):
bot.send_message(update.message.chat.id, "I am sorry, unknown error occured during working with your request," bot.send_message(update.message.chat.id, "I am sorry, unknown error occured during working with your request,"
" Admin were notified") " Admin were notified")
@catch_and_report @command
def cmd_smecds(bot: telegram.Bot, update: telegram.Update): def cmd_smecds(bot: telegram.Bot, update: telegram.Update, session: db.Session):
ds = random.sample(stagismo.listona, 1)[0] ds = random.sample(stagismo.listona, 1)[0]
bot.send_message(update.message.chat.id, f"Secondo me, è colpa {ds}.") bot.send_message(update.message.chat.id, f"Secondo me, è colpa {ds}.")
@catch_and_report @command
def cmd_ciaoruozi(bot: telegram.Bot, update: telegram.Update): def cmd_ciaoruozi(bot: telegram.Bot, update: telegram.Update, session: db.Session):
if update.message.from_user.username.lstrip("@") == "MeStakes": if update.message.from_user.username.lstrip("@") == "MeStakes":
bot.send_message(update.message.chat.id, "Ciao me!") bot.send_message(update.message.chat.id, "Ciao me!")
else: else:
bot.send_message(update.message.chat.id, "Ciao Ruozi!") bot.send_message(update.message.chat.id, "Ciao Ruozi!")
@catch_and_report @command
def cmd_ahnonlosoio(bot: telegram.Bot, update: telegram.Update): def cmd_ahnonlosoio(bot: telegram.Bot, update: telegram.Update, session: db.Session):
if update.message.reply_to_message is not None and update.message.reply_to_message.text in [ if update.message.reply_to_message is not None and update.message.reply_to_message.text in [
"/ahnonlosoio", "/ahnonlosoio@royalgamesbot", "Ah, non lo so io!", "Ah, non lo so neppure io!" "/ahnonlosoio", "/ahnonlosoio@royalgamesbot", "Ah, non lo so io!", "Ah, non lo so neppure io!"
]: ]:
@ -206,8 +210,8 @@ def cmd_ahnonlosoio(bot: telegram.Bot, update: telegram.Update):
bot.send_message(update.message.chat.id, "Ah, non lo so io!") bot.send_message(update.message.chat.id, "Ah, non lo so io!")
@catch_and_report @command
def cmd_balurage(bot: telegram.Bot, update: telegram.Update): def cmd_balurage(bot: telegram.Bot, update: telegram.Update, session: db.Session):
session = db.Session() session = db.Session()
try: try:
user = session.query(db.Telegram).filter_by(telegram_id=update.message.from_user.id).one_or_none() user = session.query(db.Telegram).filter_by(telegram_id=update.message.from_user.id).one_or_none()
@ -231,10 +235,8 @@ def cmd_balurage(bot: telegram.Bot, update: telegram.Update):
session.close() session.close()
@catch_and_report @command
def cmd_diario(bot: telegram.Bot, update: telegram.Update): def cmd_diario(bot: telegram.Bot, update: telegram.Update, session: db.Session):
session = db.Session()
try:
user = session.query(db.Telegram).filter_by(telegram_id=update.message.from_user.id).one_or_none() user = session.query(db.Telegram).filter_by(telegram_id=update.message.from_user.id).one_or_none()
if user is None: if user is None:
reply(bot, update, strings.TELEGRAM.ERRORS.ROYALNET_NOT_LINKED) reply(bot, update, strings.TELEGRAM.ERRORS.ROYALNET_NOT_LINKED)
@ -261,16 +263,10 @@ def cmd_diario(bot: telegram.Bot, update: telegram.Update):
session.add(diario) session.add(diario)
session.commit() session.commit()
reply(bot, update, strings.DIARIO.SUCCESS, ignore_escaping=True, diario=diario.to_telegram()) reply(bot, update, strings.DIARIO.SUCCESS, ignore_escaping=True, diario=diario.to_telegram())
except Exception:
raise
finally:
session.close()
@catch_and_report @command
def cmd_vote(bot: telegram.Bot, update: telegram.Update): def cmd_vote(bot: telegram.Bot, update: telegram.Update, session: db.Session):
session = db.Session()
try:
user = session.query(db.Telegram).filter_by(telegram_id=update.message.from_user.id).one_or_none() user = session.query(db.Telegram).filter_by(telegram_id=update.message.from_user.id).one_or_none()
if user is None: if user is None:
bot.send_message(update.message.chat.id, bot.send_message(update.message.chat.id,
@ -303,8 +299,6 @@ def cmd_vote(bot: telegram.Bot, update: telegram.Update):
parse_mode="HTML") parse_mode="HTML")
vote.message_id = message.message_id vote.message_id = message.message_id
session.commit() session.commit()
finally:
session.close()
def generate_search_message(term, entries): def generate_search_message(term, entries):
@ -324,10 +318,8 @@ def generate_search_message(term, entries):
return msg return msg
@catch_and_report @command
def cmd_search(bot: telegram.Bot, update: telegram.Update): def cmd_search(bot: telegram.Bot, update: telegram.Update, session: db.Session):
session = db.Session()
try:
try: try:
query = update.message.text.split(" ", 1)[1] query = update.message.text.split(" ", 1)[1]
except IndexError: except IndexError:
@ -341,14 +333,10 @@ def cmd_search(bot: telegram.Bot, update: telegram.Update):
.order_by(db.Diario.id.desc())\ .order_by(db.Diario.id.desc())\
.all() .all()
bot.send_message(update.message.chat.id, generate_search_message(f"<b>{query}</b>", entries), parse_mode="HTML") bot.send_message(update.message.chat.id, generate_search_message(f"<b>{query}</b>", entries), parse_mode="HTML")
finally:
session.close()
@catch_and_report @command
def cmd_regex(bot: telegram.Bot, update: telegram.Update): def cmd_regex(bot: telegram.Bot, update: telegram.Update, session: db.Session):
session = db.Session()
try:
try: try:
query = update.message.text.split(" ", 1)[1] query = update.message.text.split(" ", 1)[1]
except IndexError: except IndexError:
@ -360,14 +348,10 @@ def cmd_regex(bot: telegram.Bot, update: telegram.Update):
bot.send_message(update.message.chat.id, generate_search_message(f"<code>{query}</code>", entries), parse_mode="HTML") bot.send_message(update.message.chat.id, generate_search_message(f"<code>{query}</code>", entries), parse_mode="HTML")
except (BadRequest, TelegramError): except (BadRequest, TelegramError):
reply(bot, update, strings.DIARIOSEARCH.ERRORS.RESULTS_TOO_LONG) reply(bot, update, strings.DIARIOSEARCH.ERRORS.RESULTS_TOO_LONG)
finally:
session.close()
@catch_and_report @command
def cmd_mm(bot: telegram.Bot, update: telegram.Update): def cmd_mm(bot: telegram.Bot, update: telegram.Update, session: db.Session):
session = db.Session()
try:
user = session.query(db.Telegram).filter_by(telegram_id=update.message.from_user.id).one_or_none() user = session.query(db.Telegram).filter_by(telegram_id=update.message.from_user.id).one_or_none()
if user is None: if user is None:
reply(bot, update, strings.TELEGRAM.ERRORS.ROYALNET_NOT_LINKED) reply(bot, update, strings.TELEGRAM.ERRORS.ROYALNET_NOT_LINKED)
@ -392,12 +376,10 @@ def cmd_mm(bot: telegram.Bot, update: telegram.Update):
reply_markup=inline_keyboard) reply_markup=inline_keyboard)
db_match.message_id = message.message_id db_match.message_id = message.message_id
session.commit() session.commit()
finally:
session.close()
@catch_and_report @command
def on_callback_query(bot: telegram.Bot, update: telegram.Update): def on_callback_query(bot: telegram.Bot, update: telegram.Update, session: db.Session):
if update.callback_query.data.startswith("vote_"): if update.callback_query.data.startswith("vote_"):
if update.callback_query.data == "vote_yes": if update.callback_query.data == "vote_yes":
status = db.VoteChoices.YES status = db.VoteChoices.YES
@ -410,8 +392,6 @@ def on_callback_query(bot: telegram.Bot, update: telegram.Update):
emoji = "⚫️" emoji = "⚫️"
else: else:
raise NotImplementedError() raise NotImplementedError()
session = db.Session()
try:
user = session.query(db.Telegram).filter_by(telegram_id=update.callback_query.from_user.id).one_or_none() user = session.query(db.Telegram).filter_by(telegram_id=update.callback_query.from_user.id).one_or_none()
if user is None: if user is None:
bot.answer_callback_query(update.callback_query.id, show_alert=True, bot.answer_callback_query(update.callback_query.id, show_alert=True,
@ -442,11 +422,7 @@ def on_callback_query(bot: telegram.Bot, update: telegram.Update):
text=question.generate_text(session), text=question.generate_text(session),
reply_markup=inline_keyboard, reply_markup=inline_keyboard,
parse_mode="HTML") parse_mode="HTML")
finally:
session.close()
elif update.callback_query.data.startswith("match_"): elif update.callback_query.data.startswith("match_"):
session = db.Session()
try:
user = session.query(db.Telegram).filter_by(telegram_id=update.callback_query.from_user.id).one_or_none() user = session.query(db.Telegram).filter_by(telegram_id=update.callback_query.from_user.id).one_or_none()
if user is None: if user is None:
bot.answer_callback_query(update.callback_query.id, bot.answer_callback_query(update.callback_query.id,
@ -508,12 +484,10 @@ def on_callback_query(bot: telegram.Bot, update: telegram.Update):
parse_mode="HTML") parse_mode="HTML")
except BadRequest: except BadRequest:
pass pass
finally:
session.close()
@catch_and_report @command
def cmd_eat(bot: telegram.Bot, update: telegram.Update): def cmd_eat(bot: telegram.Bot, update: telegram.Update, session: db.Session):
try: try:
food: str = update.message.text.split(" ", 1)[1].capitalize() food: str = update.message.text.split(" ", 1)[1].capitalize()
except IndexError: except IndexError:
@ -525,8 +499,8 @@ def cmd_eat(bot: telegram.Bot, update: telegram.Update):
reply(bot, update, strings.EAT.NORMAL, food=food) reply(bot, update, strings.EAT.NORMAL, food=food)
@catch_and_report @command
def cmd_ship(bot: telegram.Bot, update: telegram.Update): def cmd_ship(bot: telegram.Bot, update: telegram.Update, session: db.Session):
try: try:
_, name_one, name_two = update.message.text.split(" ", 2) _, name_one, name_two = update.message.text.split(" ", 2)
except ValueError: except ValueError:
@ -546,8 +520,8 @@ def cmd_ship(bot: telegram.Bot, update: telegram.Update):
result=mixed.capitalize()) result=mixed.capitalize())
@catch_and_report @command
def cmd_bridge(bot: telegram.Bot, update: telegram.Update): def cmd_bridge(bot: telegram.Bot, update: telegram.Update, session: db.Session):
try: try:
data = update.message.text.split(" ", 1)[1] data = update.message.text.split(" ", 1)[1]
except IndexError: except IndexError:
@ -612,8 +586,8 @@ def parse_timestring(timestring: str) -> typing.Union[datetime.timedelta, dateti
raise ValueError("Nothing was found.") raise ValueError("Nothing was found.")
@catch_and_report @command
def cmd_newevent(bot: telegram.Bot, update: telegram.Update): def cmd_newevent(bot: telegram.Bot, update: telegram.Update, session: db.Session):
try: try:
_, timestring, name_desc = update.message.text.split(" ", 2) _, timestring, name_desc = update.message.text.split(" ", 2)
except ValueError: except ValueError:
@ -645,7 +619,6 @@ def cmd_newevent(bot: telegram.Bot, update: telegram.Update):
"per favore inserisci una data futura.\n", parse_mode="Markdown") "per favore inserisci una data futura.\n", parse_mode="Markdown")
return return
# Create the event # Create the event
session = db.Session()
telegram_user = session.query(db.Telegram)\ telegram_user = session.query(db.Telegram)\
.filter_by(telegram_id=update.message.from_user.id)\ .filter_by(telegram_id=update.message.from_user.id)\
.join(db.Royal)\ .join(db.Royal)\
@ -662,15 +635,12 @@ def cmd_newevent(bot: telegram.Bot, update: telegram.Update):
# Save the event # Save the event
session.add(event) session.add(event)
session.commit() session.commit()
session.close()
bot.send_message(update.message.chat.id, "✅ Evento aggiunto al Calendario Royal Games!") bot.send_message(update.message.chat.id, "✅ Evento aggiunto al Calendario Royal Games!")
@catch_and_report @command
def cmd_calendar(bot: telegram.Bot, update: telegram.Update): def cmd_calendar(bot: telegram.Bot, update: telegram.Update, session: db.Session):
session = db.Session()
next_events = session.query(db.Event).filter(db.Event.time > datetime.datetime.now()).order_by(db.Event.time).all() next_events = session.query(db.Event).filter(db.Event.time > datetime.datetime.now()).order_by(db.Event.time).all()
session.close()
msg = "📆 Prossimi eventi\n" msg = "📆 Prossimi eventi\n"
for event in next_events: for event in next_events:
if event.time_left.days >= 1: if event.time_left.days >= 1:
@ -683,8 +653,8 @@ def cmd_calendar(bot: telegram.Bot, update: telegram.Update):
bot.send_message(update.message.chat.id, msg, parse_mode="HTML", disable_web_page_preview=True) bot.send_message(update.message.chat.id, msg, parse_mode="HTML", disable_web_page_preview=True)
@catch_and_report @command
def cmd_markov(bot: telegram.Bot, update: telegram.Update): def cmd_markov(bot: telegram.Bot, update: telegram.Update, session: db.Session):
if model is None: if model is None:
bot.send_message(update.message.chat.id, strings.MARKOV.ERRORS.NO_MODEL) bot.send_message(update.message.chat.id, strings.MARKOV.ERRORS.NO_MODEL)
return return
@ -710,8 +680,8 @@ def cmd_markov(bot: telegram.Bot, update: telegram.Update):
bot.send_message(update.message.chat.id, sentence) bot.send_message(update.message.chat.id, sentence)
@catch_and_report @command
def cmd_roll(bot: telegram.Bot, update: telegram.Update): def cmd_roll(bot: telegram.Bot, update: telegram.Update, session: db.Session):
dice_string = update.message.text.split(" ", 1)[1] dice_string = update.message.text.split(" ", 1)[1]
try: try:
result = dice.roll(f"{dice_string}t") result = dice.roll(f"{dice_string}t")
@ -721,8 +691,8 @@ def cmd_roll(bot: telegram.Bot, update: telegram.Update):
bot.send_message(update.message.chat.id, f"🎲 {result}") bot.send_message(update.message.chat.id, f"🎲 {result}")
@catch_and_report @command
def cmd_start(bot: telegram.Bot, update: telegram.Update): def cmd_start(bot: telegram.Bot, update: telegram.Update, session: db.Session):
reply(bot, update, strings.TELEGRAM.BOT_STARTED) reply(bot, update, strings.TELEGRAM.BOT_STARTED)