From 0e27ba169cd726a3f2c54ef56e11031d56e560f7 Mon Sep 17 00:00:00 2001 From: Anton Date: Sun, 12 Nov 2023 19:23:58 +0500 Subject: [PATCH] impr: ignore message history in groups --- bot/bot.py | 23 +++++++++++++++-------- bot/questions.py | 17 ++++++++++++++++- 2 files changed, 31 insertions(+), 9 deletions(-) diff --git a/bot/bot.py b/bot/bot.py index 5e376d7..29a4bb9 100644 --- a/bot/bot.py +++ b/bot/bot.py @@ -196,15 +196,22 @@ async def _ask_question( logger.debug(f"Prepared question: {question}") user = UserData(context.user_data) - if is_follow_up: - # this is a follow-up question, - # so the bot should retain the previous history - history = user.messages.as_list() + if message.chat.type == Chat.PRIVATE: + # in private chats the bot remembers previous messages + if is_follow_up: + # this is a follow-up question, + # so the bot should retain the previous history + history = user.messages.as_list() + else: + # user is asking a question 'from scratch', + # so the bot should forget the previous history + user.messages.clear() + history = [] else: - # user is asking a question 'from scratch', - # so the bot should forget the previous history - user.messages.clear() - history = [] + # in group chats the bot only answers direct questions + # or follow-up questions to the bot messages + prev_message = questions.extract_prev(message, context) + history = [("", prev_message)] if prev_message else [] chat = ChatData(context.chat_data) start = time.perf_counter_ns() diff --git a/bot/questions.py b/bot/questions.py index 7a77792..0cdf1c3 100644 --- a/bot/questions.py +++ b/bot/questions.py @@ -42,7 +42,9 @@ def extract_group(message: Message, context: CallbackContext) -> tuple[str, Mess # the message is mentioning the bot, # so remove the mention to get the question - question = message.text[: mention.offset] + message.text[mention.offset + mention.length :] + question = ( + message.text[: mention.offset] + message.text[mention.offset + mention.length :] + ) question = question.strip() # messages in topics are technically replies to the 'topic created' message @@ -59,6 +61,19 @@ def extract_group(message: Message, context: CallbackContext) -> tuple[str, Mess return question, message +def extract_prev(message: Message, context: CallbackContext) -> str: + """Extracts the previous message by the bot, if any.""" + if ( + message.reply_to_message + and message.reply_to_message.from_user.username == context.bot.username + ): + # treat a reply to the bot as a follow-up question + return message.reply_to_message.text + + # otherwise, ignore previous messages + return "" + + def prepare(question: str) -> tuple[str, bool]: """ Returns the question without the special commands