From 660207ff318e57eecba49720c0d3e7e268095045 Mon Sep 17 00:00:00 2001 From: froge Date: Sun, 25 Feb 2024 13:26:48 +1000 Subject: [PATCH] Add logging and environment variable loading --- .gitignore | 3 +++ frogbot.py | 53 ++++++++++++++++++++++++++++++++++++++++++++++++ requirements.txt | 1 + 3 files changed, 57 insertions(+) create mode 100644 frogbot.py create mode 100644 requirements.txt diff --git a/.gitignore b/.gitignore index 5ceb386..160b32a 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,4 @@ venv +frogbot.log +# environment vars for development +.env diff --git a/frogbot.py b/frogbot.py new file mode 100644 index 0000000..f853b8a --- /dev/null +++ b/frogbot.py @@ -0,0 +1,53 @@ +import os +import logging +import logging.handlers +import discord +from dotenv import load_dotenv + + +# Set discord library logging level to INFO +# Configure logging to disk and stderr +logger = logging.getLogger('discord') +logger.setLevel(logging.INFO) + +stderr_loghandler = logging.StreamHandler() +loghandler = logging.handlers.RotatingFileHandler( + filename='frogbot.log', + encoding='utf-8', + maxBytes=128 * 1024 * 1024, # 128 MiB + backupCount=10, # Rotate through 10 files +) + +logger_dt_fmt = '%Y-%m-%d %H:%M:%S' +logger_formatter = logging.Formatter('[{asctime}] [{levelname:<8}] {name}: {message}', logger_dt_fmt, style='{') + +loghandler.setFormatter(logger_formatter) +stderr_loghandler.setFormatter(logger_formatter) + +logger.addHandler(stderr_loghandler) +logger.addHandler(loghandler) + +# Set up discord intents +intents = discord.Intents.default() +intents.message_content = True + +client = discord.Client(intents=intents) + +# Grab bot tokens and other data from environment variables +load_dotenv() +bot_token = os.getenv("FROGTOKEN", None) + +@client.event +async def on_ready(): + logging.info(f'We have logged in as {client.user}') + +@client.event +async def on_message(message): + if message.author == client.user: + return + + if message.content.startswith('$hello'): + await message.channel.send('Hello!') + +# Suppress the default configuration since we have our own +client.run(token=bot_token, log_handler=None) diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..3324f44 --- /dev/null +++ b/requirements.txt @@ -0,0 +1 @@ +python-dotenv==1.0.1