Skip to content

Commit

Permalink
impr: ignore message history in groups
Browse files Browse the repository at this point in the history
  • Loading branch information
nalgeon committed Nov 12, 2023
1 parent bdbc1a2 commit 0e27ba1
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 9 deletions.
23 changes: 15 additions & 8 deletions bot/bot.py
Expand Up @@ -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()
Expand Down
17 changes: 16 additions & 1 deletion bot/questions.py
Expand Up @@ -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
Expand All @@ -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
Expand Down

0 comments on commit 0e27ba1

Please sign in to comment.