From ba5b9f68b7d24a1ce2bca2bf6ca95413b92b236a Mon Sep 17 00:00:00 2001 From: Stefano Pigozzi Date: Fri, 22 Feb 2019 00:58:55 +0100 Subject: [PATCH] Guess the author if specified in the diario text --- db.py | 4 ++-- strings.py | 1 + telegrambot.py | 16 +++++++++++++++- 3 files changed, 18 insertions(+), 3 deletions(-) diff --git a/db.py b/db.py index 1d108904..7149579e 100644 --- a/db.py +++ b/db.py @@ -808,9 +808,9 @@ class Diario(Base): return f"{self.id} - {self.timestamp} - {self.author}: {self.text}" def to_telegram(self): - return '#{id} di {author}\n{text}'.format( + return '#{id} di {author}\n{text}'.format( id=self.id, - author=self.author, + author=f"{self.author}" if self.author is not None else strings.DIARIO.ANONYMOUS, text=escape(self.text)) def to_html(self): diff --git a/strings.py b/strings.py index a0848235..2dc6ede2 100644 --- a/strings.py +++ b/strings.py @@ -70,6 +70,7 @@ COLOR = "I am sorry, unknown error occured during working with your request, # Diario class DIARIO: SUCCESS = "✅ Riga aggiunta al diario:\n{diario}" + ANONYMOUS = "Anonimo" class ERRORS: INVALID_SYNTAX = "⚠ Sintassi del comando errata.\nSintassi: /diario (frase), oppure rispondi a un messaggio con /diario." diff --git a/telegrambot.py b/telegrambot.py index 84f8b8fc..f480b96f 100644 --- a/telegrambot.py +++ b/telegrambot.py @@ -223,6 +223,20 @@ def cmd_balurage(bot: telegram.Bot, update: telegram.Update, session: db.Session bot.send_message(update.message.chat.id, f"😡 Stai sfogando la tua ira sul bot!") +def find_author(session: db.Session, text: str): + author_match = re.match(r".*(?:—|-{1,2}) ?@?([A-Za-z0-9_]+)$", text) + if author_match is None: + return None + author_string = author_match.group(1).lower() + author = session.query(db.Royal).filter(db.func.lower(db.Royal.username) == author_string).first().telegram[0] + if author is not None: + return author + author = session.query(db.Telegram).filter(db.func.lower(db.Telegram.username) == author_string).first() + if author is not None: + return author + return None + + @command @database_access def cmd_diario(bot: telegram.Bot, update: telegram.Update, session: db.Session): @@ -233,7 +247,7 @@ def cmd_diario(bot: telegram.Bot, update: telegram.Update, session: db.Session): try: text = update.message.text.split(" ", 1)[1] saver = session.query(db.Telegram).filter_by(telegram_id=update.message.from_user.id).one_or_none() - author = None + author = find_author(session, text) except IndexError: if update.message.reply_to_message is None: reply(bot, update, strings.DIARIO.ERRORS.INVALID_SYNTAX)