from dotenv import load_dotenv import os, logging, asyncpg, socket import discord def config_missing(): if not os.path.exists(".env"): logging.error("Environment variable file not found, creating .env file") with open(".env", "w") as settings_file: settings_file.writelines( [ "# LOG_LEVEL options: DEBUG, INFO, WARNING, ERROR, CRITICAL\n", "LOG_LEVEL = \"WARNING\"\n", "\n", "DISCORD_TOKEN = \"\"\n", "OUTPUT_CHANNEL_ID = \n", "\n", "DATABASE_HOST = 127.0.0.1\n", "DATABASE_NAME = \n", "DATABASE_USER = \n", "DATABASE_PASSWORD = \n" ] ) logging.critical("Configure the settings by editing the .env file and restart the bot to continue.") quit() async def create_db_pool(): # Connect to database try: bot.pg = await asyncpg.create_pool( database=str(os.getenv("DATABASE_NAME")), user=str(os.getenv("DATABASE_USER")), host=str(os.getenv("DATABASE_HOST")), password=str(os.getenv("DATABASE_PASSWORD")), ) except socket.gaierror: logging.error("Unable to connect to database - GAI error: PLease verify the DATABASE_HOST.") config_missing() except asyncpg.exceptions.InvalidPasswordError: logging.error("Unable to connect to database - Invalid password: Please verify credentials.") config_missing() except asyncpg.exceptions.InvalidCatalogNameError: logging.error("Unable to connect to database - Invalid catalog name: Please verify the database name.") config_missing() await init_db(bot.pg) # Load variables from .env file load_dotenv() # Set loglevel try: logging.basicConfig(level=str(os.getenv("LOG_LEVEL").upper())) except AttributeError: config_missing() # Set intent intents = discord.Intents.none() intents.bans = True intents.guilds = True intents.invites = True intents.members = True intents.messages = True bot = discord.Bot(intents=intents) bot.OUTPUT_CHANNEL_ID = int(os.getenv("OUTPUT_CHANNEL_ID")) if not bot.OUTPUT_CHANNEL_ID: logging.error("OUTPUT_CHANNEL not defined, the bot requires a guild channel to report to.") config_missing() # Create database pool bot.loop.create_task(create_db_pool()) # Create database tables if they do not exist from query.initialise_database import init_db # Load cogs cogs_list = [ 'events', 'idlerpg', 'admin' ] for cog in cogs_list: bot.load_extension(f'cogs.{cog}') # Run bot try: bot.run(str(os.getenv("DISCORD_TOKEN"))) except discord.errors.LoginFailure: logging.error("Login Failure") config_missing()