1
Fork 0
mirror of https://github.com/RYGhub/royalnet.git synced 2024-11-23 19:44:20 +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
def catch_and_report(func: "function"):
# noinspection PyUnresolvedReferences
def command(func: "function"):
def new_func(bot: telegram.Bot, update: telegram.Update):
# noinspection PyBroadException
try:
return func(bot, update)
session = db.Session()
return func(bot, update, session)
except TimedOut:
logger.warning(f"Telegram timed out in {update}")
except Exception:
@ -104,16 +106,18 @@ def catch_and_report(func: "function"):
"update": update.to_dict()
})
sentry.captureException()
finally:
session.close()
return new_func
@catch_and_report
def cmd_ping(bot: telegram.Bot, update: telegram.Update):
@command
def cmd_ping(bot: telegram.Bot, update: telegram.Update, session: db.Session):
reply(bot, update, strings.PONG)
@catch_and_report
def cmd_link(bot: telegram.Bot, update: telegram.Update):
@command
def cmd_link(bot: telegram.Bot, update: telegram.Update, session: db.Session):
session = db.Session()
try:
try:
@ -141,8 +145,8 @@ def cmd_link(bot: telegram.Bot, update: telegram.Update):
session.close()
@catch_and_report
def cmd_cv(bot: telegram.Bot, update: telegram.Update):
@command
def cmd_cv(bot: telegram.Bot, update: telegram.Update, session: db.Session):
if discord_connection is None:
reply(bot, update, strings.TELEGRAM.ERRORS.INACTIVE_BRIDGE)
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")
@catch_and_report
def cmd_cast(bot: telegram.Bot, update: telegram.Update):
@command
def cmd_cast(bot: telegram.Bot, update: telegram.Update, session: db.Session):
try:
spell: str = update.message.text.split(" ", 1)[1]
except IndexError:
@ -176,28 +180,28 @@ def cmd_cast(bot: telegram.Bot, update: telegram.Update):
parse_mode="HTML")
@catch_and_report
def cmd_color(bot: telegram.Bot, update: telegram.Update):
@command
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,"
" Admin were notified")
@catch_and_report
def cmd_smecds(bot: telegram.Bot, update: telegram.Update):
@command
def cmd_smecds(bot: telegram.Bot, update: telegram.Update, session: db.Session):
ds = random.sample(stagismo.listona, 1)[0]
bot.send_message(update.message.chat.id, f"Secondo me, è colpa {ds}.")
@catch_and_report
def cmd_ciaoruozi(bot: telegram.Bot, update: telegram.Update):
@command
def cmd_ciaoruozi(bot: telegram.Bot, update: telegram.Update, session: db.Session):
if update.message.from_user.username.lstrip("@") == "MeStakes":
bot.send_message(update.message.chat.id, "Ciao me!")
else:
bot.send_message(update.message.chat.id, "Ciao Ruozi!")
@catch_and_report
def cmd_ahnonlosoio(bot: telegram.Bot, update: telegram.Update):
@command
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 [
"/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!")
@catch_and_report
def cmd_balurage(bot: telegram.Bot, update: telegram.Update):
@command
def cmd_balurage(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()
@ -231,10 +235,8 @@ def cmd_balurage(bot: telegram.Bot, update: telegram.Update):
session.close()
@catch_and_report
def cmd_diario(bot: telegram.Bot, update: telegram.Update):
session = db.Session()
try:
@command
def cmd_diario(bot: telegram.Bot, update: telegram.Update, session: db.Session):
user = session.query(db.Telegram).filter_by(telegram_id=update.message.from_user.id).one_or_none()
if user is None:
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.commit()
reply(bot, update, strings.DIARIO.SUCCESS, ignore_escaping=True, diario=diario.to_telegram())
except Exception:
raise
finally:
session.close()
@catch_and_report
def cmd_vote(bot: telegram.Bot, update: telegram.Update):
session = db.Session()
try:
@command
def cmd_vote(bot: telegram.Bot, update: telegram.Update, session: db.Session):
user = session.query(db.Telegram).filter_by(telegram_id=update.message.from_user.id).one_or_none()
if user is None:
bot.send_message(update.message.chat.id,
@ -303,8 +299,6 @@ def cmd_vote(bot: telegram.Bot, update: telegram.Update):
parse_mode="HTML")
vote.message_id = message.message_id
session.commit()
finally:
session.close()
def generate_search_message(term, entries):
@ -324,10 +318,8 @@ def generate_search_message(term, entries):
return msg
@catch_and_report
def cmd_search(bot: telegram.Bot, update: telegram.Update):
session = db.Session()
try:
@command
def cmd_search(bot: telegram.Bot, update: telegram.Update, session: db.Session):
try:
query = update.message.text.split(" ", 1)[1]
except IndexError:
@ -341,14 +333,10 @@ def cmd_search(bot: telegram.Bot, update: telegram.Update):
.order_by(db.Diario.id.desc())\
.all()
bot.send_message(update.message.chat.id, generate_search_message(f"<b>{query}</b>", entries), parse_mode="HTML")
finally:
session.close()
@catch_and_report
def cmd_regex(bot: telegram.Bot, update: telegram.Update):
session = db.Session()
try:
@command
def cmd_regex(bot: telegram.Bot, update: telegram.Update, session: db.Session):
try:
query = update.message.text.split(" ", 1)[1]
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")
except (BadRequest, TelegramError):
reply(bot, update, strings.DIARIOSEARCH.ERRORS.RESULTS_TOO_LONG)
finally:
session.close()
@catch_and_report
def cmd_mm(bot: telegram.Bot, update: telegram.Update):
session = db.Session()
try:
@command
def cmd_mm(bot: telegram.Bot, update: telegram.Update, session: db.Session):
user = session.query(db.Telegram).filter_by(telegram_id=update.message.from_user.id).one_or_none()
if user is None:
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)
db_match.message_id = message.message_id
session.commit()
finally:
session.close()
@catch_and_report
def on_callback_query(bot: telegram.Bot, update: telegram.Update):
@command
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 == "vote_yes":
status = db.VoteChoices.YES
@ -410,8 +392,6 @@ def on_callback_query(bot: telegram.Bot, update: telegram.Update):
emoji = "⚫️"
else:
raise NotImplementedError()
session = db.Session()
try:
user = session.query(db.Telegram).filter_by(telegram_id=update.callback_query.from_user.id).one_or_none()
if user is None:
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),
reply_markup=inline_keyboard,
parse_mode="HTML")
finally:
session.close()
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()
if user is None:
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")
except BadRequest:
pass
finally:
session.close()
@catch_and_report
def cmd_eat(bot: telegram.Bot, update: telegram.Update):
@command
def cmd_eat(bot: telegram.Bot, update: telegram.Update, session: db.Session):
try:
food: str = update.message.text.split(" ", 1)[1].capitalize()
except IndexError:
@ -525,8 +499,8 @@ def cmd_eat(bot: telegram.Bot, update: telegram.Update):
reply(bot, update, strings.EAT.NORMAL, food=food)
@catch_and_report
def cmd_ship(bot: telegram.Bot, update: telegram.Update):
@command
def cmd_ship(bot: telegram.Bot, update: telegram.Update, session: db.Session):
try:
_, name_one, name_two = update.message.text.split(" ", 2)
except ValueError:
@ -546,8 +520,8 @@ def cmd_ship(bot: telegram.Bot, update: telegram.Update):
result=mixed.capitalize())
@catch_and_report
def cmd_bridge(bot: telegram.Bot, update: telegram.Update):
@command
def cmd_bridge(bot: telegram.Bot, update: telegram.Update, session: db.Session):
try:
data = update.message.text.split(" ", 1)[1]
except IndexError:
@ -612,8 +586,8 @@ def parse_timestring(timestring: str) -> typing.Union[datetime.timedelta, dateti
raise ValueError("Nothing was found.")
@catch_and_report
def cmd_newevent(bot: telegram.Bot, update: telegram.Update):
@command
def cmd_newevent(bot: telegram.Bot, update: telegram.Update, session: db.Session):
try:
_, timestring, name_desc = update.message.text.split(" ", 2)
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")
return
# Create the event
session = db.Session()
telegram_user = session.query(db.Telegram)\
.filter_by(telegram_id=update.message.from_user.id)\
.join(db.Royal)\
@ -662,15 +635,12 @@ def cmd_newevent(bot: telegram.Bot, update: telegram.Update):
# Save the event
session.add(event)
session.commit()
session.close()
bot.send_message(update.message.chat.id, "✅ Evento aggiunto al Calendario Royal Games!")
@catch_and_report
def cmd_calendar(bot: telegram.Bot, update: telegram.Update):
session = db.Session()
@command
def cmd_calendar(bot: telegram.Bot, update: telegram.Update, session: db.Session):
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"
for event in next_events:
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)
@catch_and_report
def cmd_markov(bot: telegram.Bot, update: telegram.Update):
@command
def cmd_markov(bot: telegram.Bot, update: telegram.Update, session: db.Session):
if model is None:
bot.send_message(update.message.chat.id, strings.MARKOV.ERRORS.NO_MODEL)
return
@ -710,8 +680,8 @@ def cmd_markov(bot: telegram.Bot, update: telegram.Update):
bot.send_message(update.message.chat.id, sentence)
@catch_and_report
def cmd_roll(bot: telegram.Bot, update: telegram.Update):
@command
def cmd_roll(bot: telegram.Bot, update: telegram.Update, session: db.Session):
dice_string = update.message.text.split(" ", 1)[1]
try:
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}")
@catch_and_report
def cmd_start(bot: telegram.Bot, update: telegram.Update):
@command
def cmd_start(bot: telegram.Bot, update: telegram.Update, session: db.Session):
reply(bot, update, strings.TELEGRAM.BOT_STARTED)