diff --git a/extensions/_essentials.py b/extensions/_essentials.py deleted file mode 100644 index dab6427..0000000 --- a/extensions/_essentials.py +++ /dev/null @@ -1,83 +0,0 @@ -#plugin for sparkytron 3000 -import json -import os -import time - -from discord.ext import commands - -async def handle_error(error): - print(error) - current_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) - log_line = current_time + ': ' + str(error) + '\n' - with open("data/error_log.txt", 'a') as f: - f.write(log_line) - return error - -''' -#stable diffusion command!!! -@commands.command( - description="View Images", - help="Enable or disable bot viewing images in this channel. Usage !viewimages (enable|disable)", - brief="Enable or disable bot viewing images" - ) -async def view_images(ctx, message): - if "enable" in message: - edit_channel_config(ctx.channel.id, "look_at_images", True) - await ctx.send("Viewing Enabled") - elif "disable" in message: - edit_channel_config(ctx.channel.id, "look_at_images", False) - await ctx.send("Viewing Disabled") - else: - await ctx.send("Usage: !viewimages (enable|disable)")''' - - -''' -@commands.command( - description="Commands", - help="Enable or disable bot commands in this channel. Usage !enable_commands (enable|disable)", - brief="Enable or disable bot commands" - ) -async def enable_commands(ctx, message): - if "disable" in message or "false" in message: - edit_channel_config(ctx.channel.id, "commands_enabled", False) - await ctx.send("Commands Disabled") - else: - edit_channel_config(ctx.channel.id, "commands_enabled", True) - await ctx.send("Commands Enabled")''' - - -''' -@commands.command( - description="Feature", - help="Suggest a feature. Usage: !feature (feature)", - brief="Suggest a feature" - ) -async def feature(ctx): - try: - feature = ctx.message.content.split(" ", maxsplit=1)[1] - with open("features.txt",'a') as f: - f.writelines('\n' + feature) - await ctx.send("Added " + feature) - except Exception as error: - await handle_error(error) - - with open("features.txt",'r') as f: - features = f.read() - await ctx.send(features)''' - -'''@commands.command( - description="Errors", - help="Shows the last errors that were logged.", - brief="Display Errors" - ) -async def errors(ctx, amount="5"): - output = "" - amount = int(amount) - try: - with open("data/error_log.txt", 'r') as f: - for line in (f.readlines() [-amount:]): - output += line - await ctx.send(output) - except Exception as error: - await handle_error(error)''' - diff --git a/sparkytron3000.py b/sparkytron3000.py index 6f5727a..8013bda 100644 --- a/sparkytron3000.py +++ b/sparkytron3000.py @@ -1,109 +1,11 @@ -import discord -from discord.ext import commands, tasks -import shutil -import time import os from dotenv import load_dotenv -import aiohttp -import src.logger as logger +from src.bot import bot - -load_dotenv() -discord_token = os.getenv('discord_token') - -intents = discord.Intents.all() -intents.message_content = True -bot = commands.Bot(command_prefix='!', intents=intents) - - - -async def folder_setup(): - try: - folder_names = ["tmp", "extensions", "data", "logs"] - for folder_name in folder_names: - if not os.path.exists(folder_name): - os.mkdir(folder_name) - except Exception as e: - bot.logger.exception(f"Error setting up folders: {e}") - -async def delete_all_files(path): - try: - for filename in os.listdir(path): - if os.path.isfile(path+filename): - os.remove(path+filename) - except Exception as e: - bot.logger.exception(f"Error deleting files: {e}") - -@tasks.loop(seconds=1) # Run the task every second -async def task_loop(): - try: - current_time = time.localtime() - #Run daily tasks - if current_time.tm_hour == 0 and current_time.tm_min == 0 and current_time.tm_sec == 0: - await delete_all_files("tmp/") - bot.logger.info("Deleted tmp/ files.") - except Exception as e: - bot.logger.exception(f"Error in task loop: {e}") - -async def create_session(): - return aiohttp.ClientSession() - -async def close_session(http_session): - await http_session.close() - -@bot.event -async def on_connect(): - bot.http_session = await create_session() - -@bot.event -async def on_resumed(): - bot.http_session = await create_session() - -@bot.event -async def on_disconnect(): - await close_session(bot.http_session) - -def logger_setup(logger): - if not os.path.isdir("logs"): - os.mkdir("logs") - with open("logs/info.log", "a") as f: - pass - logger = logger.logging.getLogger("bot") - return logger - - -@bot.event -async def on_ready(): - try: - await delete_all_files("tmp/") - await folder_setup() - # Import plugins from extensions folder - for plugin_file in os.listdir('extensions/'): - if plugin_file[0] != '_' and plugin_file[-3:] == '.py': - try: - await bot.load_extension(f'extensions.{plugin_file[:-3]}') - bot.logger.info(f"Successfully loaded plugin {plugin_file}") - except: - bot.logger.exception(f"Failed to load plugin {plugin_file}") - bot.logger.info('We have logged in as {0.user}'.format(bot)) - task_loop.start() - except Exception as e: - bot.logger.warning(f"Error in on_ready: {e}") - raise - -@bot.event -async def on_message(ctx): - try: - await bot.process_commands(ctx) - except commands.CommandNotFound: - bot.logger.info("Command not found.") - except discord.ext.commands.errors.CommandNotFound: - bot.logger.info("Command not found.") - except Exception as e: - bot.logger.warning(f"Error processing commands: {e}") - -bot.logger = logger_setup(logger) -try: +def main(): + load_dotenv() + discord_token = os.getenv('discord_token') bot.run(discord_token, root_logger=True) -except Exception as e: - logger.critical(f"Fatal error running bot: {e}") + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/src/bot.py b/src/bot.py new file mode 100644 index 0000000..a02b1f6 --- /dev/null +++ b/src/bot.py @@ -0,0 +1,60 @@ +import os +import discord +from discord.ext import commands +import aiohttp +from dotenv import load_dotenv +import src.logger as logger +import src.utils as utils + +intents = discord.Intents.all() +intents.message_content = True +bot = commands.Bot(command_prefix='!', intents=intents) +bot.logger = logger.logger_setup() + +async def create_session(): + return aiohttp.ClientSession() + +async def close_session(http_session): + await http_session.close() + +async def load_cogs(bot: commands.Bot, cog_path: str) -> None: + for plugin_file in os.listdir(cog_path): + if plugin_file[-3:] == '.py': + try: + await bot.load_extension(f'extensions.{plugin_file[:-3]}') + bot.logger.info(f"Successfully loaded plugin {plugin_file}") + except: + bot.logger.exception(f"Failed to load plugin {plugin_file}") + +@bot.event +async def on_connect(): + bot.http_session = await create_session() + +@bot.event +async def on_resumed(): + bot.http_session = await create_session() + +@bot.event +async def on_disconnect(): + await close_session(bot.http_session) + +@bot.event +async def on_ready(): + try: + await utils.delete_all_files("tmp/") + await utils.folder_setup() + await load_cogs(bot, 'extensions/') + bot.logger.info('We have logged in as {0.user}'.format(bot)) + except: + bot.logger.warning(f"Error in on_ready") + +@bot.event +async def on_message(ctx): + try: + await bot.process_commands(ctx) + except commands.CommandNotFound: + bot.logger.info("Command not found.") + except discord.ext.commands.errors.CommandNotFound: + bot.logger.info("Command not found.") + except Exception as e: + bot.logger.warning(f"Error processing commands: {e}") diff --git a/src/logger.py b/src/logger.py index 206ffff..7caeccd 100644 --- a/src/logger.py +++ b/src/logger.py @@ -2,6 +2,15 @@ import logging import os from logging.config import dictConfig +def logger_setup(): + if not os.path.isdir("logs"): + os.mkdir("logs") + with open("logs/info.log", "a") as f: + pass + logger = logging.getLogger("bot") + return logger + + LOGGING_CONFIG = { "version": 1, "disabled_existing_loggers": False, @@ -41,8 +50,4 @@ LOGGING_CONFIG = { }, } -if not os.path.isdir("logs"): - os.mkdir("logs") -with open("logs/info.log", "a") as f: - pass dictConfig(LOGGING_CONFIG) \ No newline at end of file diff --git a/src/utils.py b/src/utils.py new file mode 100644 index 0000000..7a5b510 --- /dev/null +++ b/src/utils.py @@ -0,0 +1,12 @@ +import os + +async def folder_setup() -> None: + folder_names = ["tmp", "extensions", "data", "logs"] + for folder_name in folder_names: + if not os.path.exists(folder_name): + os.mkdir(folder_name) + +async def delete_all_files(path: str) -> None: + for filename in os.listdir(path): + if os.path.isfile(path+filename): + os.remove(path+filename)