Skip to content

Commit

Permalink
Error handling initiating bot
Browse files Browse the repository at this point in the history
  • Loading branch information
geirawsm committed Dec 17, 2024
1 parent 4558b64 commit e5a55b7
Show file tree
Hide file tree
Showing 4 changed files with 73 additions and 50 deletions.
2 changes: 1 addition & 1 deletion .dockerignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
sausage_bot/data/*
sausage_bot/data*/*
sausage_bot/tempfiles/*
.cache
*.code-workspace
Expand Down
5 changes: 3 additions & 2 deletions dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ WORKDIR /app/

RUN pip install --upgrade pip
RUN pip install pipenv
RUN pipenv install --system --deploy --ignore-pipfile

VOLUME [ "/data" ]

Expand All @@ -24,5 +23,7 @@ RUN echo -e \
"\"LAST_RUN_NUMBER\": \"${LAST_RUN_NUMBER}\"}"\
> /app/sausage_bot/version.json

RUN pipenv install --system --deploy --ignore-pipfile

# Run bot
CMD ["python", "-m", "sausage_bot", "--log", "--log-print", "--log-database", "--debug", "--log-file", "--data-dir", "/data"]
CMD ["python", "-m", "sausage_bot", "--log", "--log-print", "--log-error", "--log-database", "--debug", "--log-file", "--data-dir", "/data"]
25 changes: 3 additions & 22 deletions sausage_bot/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,10 @@
import discord
from discord.ext import commands
from discord.app_commands import locale_str
import os
from tabulate import tabulate
from sys import exit
import typing


from sausage_bot.util.args import args
from sausage_bot.util import config, envs, file_io, cogs, db_helper
from sausage_bot.util import discord_commands
Expand Down Expand Up @@ -137,24 +136,6 @@ async def locales_autocomplete(
]


# Create necessary folders before starting
check_and_create_folders = [
envs.DB_DIR,
envs.LOG_DIR
]
for folder in check_and_create_folders:
try:
os.makedirs(folder)
except (FileExistsError):
pass

# Create necessary files before starting
if args.create_env:
log.verbose('Create .env file')
file_io.ensure_file(envs.env_file, envs.env_template)
exit()


@config.bot.event
async def on_ready():
'''
Expand Down Expand Up @@ -209,8 +190,8 @@ async def on_ready():
)
)
# Make sure that the BOT_CHANNEL is present
if config.BOT_CHANNEL not in discord_commands.get_text_channel_list():
bot_channel = config.BOT_CHANNEL
bot_channel = config.BOT_CHANNEL
if bot_channel not in discord_commands.get_text_channel_list():
log.debug(f'Bot channel `{bot_channel}` does not exist, creating...')
guild = discord_commands.get_guild()
overwrites = {
Expand Down
91 changes: 66 additions & 25 deletions sausage_bot/util/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,44 +4,85 @@

import discord
from discord.ext import commands
import json
from sys import exit
from . import envs
from environs import Env, EnvError
from .log import log
from contextlib import suppress
import os
from pathlib import Path

from . import envs


# Create necessary folders before starting
check_and_create_folders = [
envs.DB_DIR,
envs.LOG_DIR
]
for folder in check_and_create_folders:
with suppress(FileExistsError):
os.makedirs(folder)

env = Env()
env.read_env(path=envs.env_file)

def ensure_file(file_path_in: str, file_template=False):
def ensure_folder(folder_path: str):
'''
Create folders in `folder_path` if it doesn't exist
'''
folder_path = str(folder_path)
# Make the folders if necessary
if not os.path.exists(folder_path):
_dirs = str(folder_path).split(os.sep)
_path = ''
for _dir in _dirs:
_path += '{}/'.format(_dir)
Path(_path).mkdir(parents=True, exist_ok=True)

def config():
full_file_path = str(file_path_in).split(os.sep)
folder_path = '/'.join(full_file_path[0:-1])
folder_path += '/'
# Make the folders if necessary
ensure_folder(folder_path)
try:
with open(envs.env_file) as f:
return dict(json.load(f))
except json.JSONDecodeError as e:
log.error(f"Error when reading json from {envs.env_file}:\n{e}")
except OSError as e:
log.error(f"File can't be read {envs.env_file}:\n{e}")
return None


# Set basic env values
PREFIX = env('PREFIX', default='!')
BOT_CHANNEL = env('BOT_DUMP_CHANNEL', default='bot-log')
TIMEZONE = env('TIMEZONE', default='Europe/Oslo')
LOCALE = env('LOCALE', default='nb_NO')
ROLE_CHANNEL = env('ROLE_CHANNEL', default='roles')
SPOTIFY_ID = env('SPOTIFY_ID', default=None)
SPOTIFY_SECRET = env('SPOTIFY_SECRET', default=None)
os.stat(str(file_path_in), follow_symlinks=True)
file_exist = True
except FileNotFoundError:
file_exist = False
if not file_exist:
with open(file_path_in, 'w+') as fout:
if file_template:
fout.write(file_template)
else:
fout.write('')


# Create necessary files before starting
ensure_file(envs.env_file, envs.env_template)

try:
env = Env()
env.read_env(envs.env_file)
# Set basic env values
DISCORD_TOKEN = env('DISCORD_TOKEN')
DISCORD_GUILD = env('DISCORD_GUILD')
BOT_ID = env('BOT_ID')
DISCORD_TOKEN = env('DISCORD_TOKEN')
PREFIX = env('PREFIX', default='!')
BOT_CHANNEL = env('BOT_DUMP_CHANNEL', default='bot-log')
TIMEZONE = env('TIMEZONE', default='Europe/Oslo')
LOCALE = env('LOCALE', default='nb_NO')
ROLE_CHANNEL = env('ROLE_CHANNEL', default='roles')
SPOTIFY_ID = env('SPOTIFY_ID', default=None)
SPOTIFY_SECRET = env('SPOTIFY_SECRET', default=None)
if any(len(envvar) <= 0 for envvar in [
DISCORD_GUILD, BOT_ID, DISCORD_TOKEN
]):
print('Something is wrong with the env file.')
exit()
except EnvError as e:
print(env.dump())
print(
f'You need to set environment variables for the bot to work: {e}'
)
exit()

try:
intents = discord.Intents.all()
Expand All @@ -50,5 +91,5 @@ def config():
intents=intents
)
except KeyError as e:
log.error(f'Couldn\'t load basic env: {e}')
print(f'Couldn\'t load basic env: {e}')
exit()

0 comments on commit e5a55b7

Please sign in to comment.