From 8ea8c9208a8b325aeba774ecbc46f7296188f64d Mon Sep 17 00:00:00 2001 From: Kumi Date: Sat, 2 Mar 2024 16:24:47 +0100 Subject: [PATCH] Refactor bot state management logic This commit refactors the code handling bot state management to improve readability and modularity. The new implementation uses a more structured approach to handling different types of events, making it easier to reason about and maintain. Additionally, it fixes an issue where the bot was not properly handling errors when putting state in rooms. This change should improve the overall stability and performance of the RSS bot, as well as make it easier for developers to understand and work with the codebase. --- src/matrix_rssbot/classes/bot.py | 3 +- src/matrix_rssbot/classes/commands/addfeed.py | 28 +++++++++++++++---- 2 files changed, 24 insertions(+), 7 deletions(-) diff --git a/src/matrix_rssbot/classes/bot.py b/src/matrix_rssbot/classes/bot.py index 590fa4a..47dc823 100644 --- a/src/matrix_rssbot/classes/bot.py +++ b/src/matrix_rssbot/classes/bot.py @@ -503,8 +503,7 @@ class RSSBot: room, event_type, content, state_key ) - if isinstance(response, RoomPutStateError): - self.logger.log(f"Error putting state in {room}") + return response async def get_state_event( self, room: MatrixRoom | str, event_type: str, state_key: Optional[str] = None diff --git a/src/matrix_rssbot/classes/commands/addfeed.py b/src/matrix_rssbot/classes/commands/addfeed.py index e5041c4..392f00b 100644 --- a/src/matrix_rssbot/classes/commands/addfeed.py +++ b/src/matrix_rssbot/classes/commands/addfeed.py @@ -23,9 +23,7 @@ async def command_addfeed(room: MatrixRoom, event: RoomMessageText, bot): feeds.append(url) try: - feed = feedparser.parse(url) - for entry in feed.entries: - print(entry) + feedparser.parse(url) except: await bot.send_state_event( f"Could not access or parse feed at {url}. Please ensure that you got the URL right, and that it is actually an RSS/Atom feed.", @@ -33,13 +31,33 @@ async def command_addfeed(room: MatrixRoom, event: RoomMessageText, bot): ) try: - await bot.send_state_event( + response1 = await bot.send_state_event( room, "rssbot.feed_state", {"timestamp": int(datetime.now().timestamp())}, url, ) - await bot.send_state_event(room, "rssbot.feeds", {"feeds": feeds}) + + if isinstance(response1, RoomPutStateError): + if response1.status_code == "M_FORBIDDEN": + await bot.send_message( + room, + "Unable to put status events into this room. Please ensure I have the required permissions, then try again.", + ) + + await bot.send_message( + room, "Unable to write feed state to the room. Please try again.", True + ) + return + + response2 = await bot.send_state_event(room, "rssbot.feeds", {"feeds": feeds}) + + if isinstance(response2, RoomPutStateError): + await bot.send_message( + room, "Unable to write feed list to the room. Please try again.", True + ) + return + await bot.send_message(room, f"Added {url} to this room's feeds.", True) except: await bot.send_message(