Manage exceptions better

This commit is contained in:
n07070
2026-10-16 15:31:06 +02:00
parent f185ba2fe0
commit dedfef9be3

View File

@@ -1,8 +1,15 @@
"""
Mastodon welcome bot. Listens for notifications regarding new singups,
and sends a welcome message to the new user.
"""
import logging
import sys
import toml # Used for the config file parsing
from mastodon import Mastodon, StreamListener
from mastodon.errors import MastodonError
from mastodon.errors import MastodonError, MastodonNetworkError
import requests
import time
logger = logging.getLogger(__name__)
@@ -52,12 +59,16 @@ class BotListener(StreamListener):
else:
logger.debug("Notification type: %s", kind)
except Exception:
except MastodonError:
# Keep one failed response from interrupting notification handling.
logger.exception("Failed to handle notification")
def main():
"""
Setup loggin, configuration and connexion to Mastodon
Then, run the bot via a Listener
"""
logging.basicConfig(
filename="botato.log",
level=logging.DEBUG,
@@ -67,16 +78,26 @@ def main():
try:
with open("config/botato.toml", "r", encoding="utf-8") as f:
configuration = toml.load(f)
logger.debug("Loaded configuration file")
except (OSError, toml.TomlDecodeError, TypeError):
logger.exception("Unable to load config/configuration file")
logger.exception("Unable to load configuration file")
sys.exit(1)
mastodon = Mastodon(
api_base_url=configuration["mastodon"]["instance"],
access_token=configuration["mastodon"]["access_token"],
)
# while not connected:
logger.debug("Trying to start the bot...")
try:
# comment:
mastodon = Mastodon(
api_base_url=configuration["mastodon"]["instance"],
access_token=configuration["mastodon"]["access_token"],
)
except Exception:
logger.exception("Unable to connect to the Mastodon instance")
listener = BotListener(mastodon, configuration["messages"])
try:
listener = BotListener(mastodon, configuration["messages"])
except Exception:
logger.exception("Unable to start the listener for the bot's notifications")
try:
# Blocking call: runs until interrupted or the connection fails.
@@ -84,10 +105,21 @@ def main():
mastodon.stream_user(listener)
except KeyboardInterrupt:
logger.info("Stopping bot")
except MastodonError:
logger.exception("Mastodon streaming error")
raise
sys.exit(0)
except MastodonError as e:
if "Unauthorized" in e:
logger.error("The connexion to the instance is unauthorized, are you sure your access token is valid ? ")
else:
logger.error("Mastodon streaming error : %s", str(e))
sys.exit(1)
except requests.exceptions.ConnectionError:
logger.error("Unable to connect to the instance : Are you sure you're connected to the Internet is the URL in the configuration file is good ? ")
except MastodonNetworkError as e:
logger.error("Error while connecting to the server %s", str(e))
sys.exit(1)
# else:
# logger.error("Unable to start streaming the bot's notifications...")
# sys.exit(1)
if __name__ == "__main__":
main()