From 9e804856caa6b7b9a9880ae67c9d330f09df4d29 Mon Sep 17 00:00:00 2001 From: Dory Date: Sun, 17 Aug 2025 11:34:11 -0700 Subject: [PATCH] fix: Only add user message to history on success --- bot.py | 1 + tests/test_bot.py | 21 +++++++++++++++++++++ 2 files changed, 22 insertions(+) diff --git a/bot.py b/bot.py index 1c693f4..fb9976e 100644 --- a/bot.py +++ b/bot.py @@ -99,6 +99,7 @@ async def on_message(message): await message.channel.send(bot_response) except Exception as e: print(f"An error occurred: {e}") + conversation_history[channel_id].pop() # Remove user message on error await message.channel.send("Sorry, I had a little hiccup. Baka!") diff --git a/tests/test_bot.py b/tests/test_bot.py index 772229e..1234ce2 100644 --- a/tests/test_bot.py +++ b/tests/test_bot.py @@ -107,6 +107,27 @@ class TestAoiBot(unittest.IsolatedAsyncioTestCase): # Assertions bot.newchat.callback.assert_awaited_once_with(interaction, prompt=None) + @patch('bot.openai.OpenAI') + async def test_on_message_api_error(self, MockOpenAI): + # Mock the OpenAI client to raise an error + mock_openai_instance = MockOpenAI.return_value + mock_openai_instance.chat.completions.create.side_effect = Exception("API Error") + + # Mock a Discord message + message = AsyncMock() + message.author = MagicMock() + message.author.bot = False + message.channel = AsyncMock() + message.channel.id = 123 + message.content = f"<@!{bot.bot.user.id}> This will fail" + message.attachments = [] + + # Call the on_message event handler + await bot.on_message(message) + + # Assertions + bot.on_message.assert_awaited_once_with(message) + if __name__ == '__main__': unittest.main()