moved functions to their own modules

deleted unused _essentials.py
This commit is contained in:
phixxy 2024-02-13 01:17:33 -08:00
parent b023724e09
commit b1beb57dfc
5 changed files with 88 additions and 192 deletions

View file

@ -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)'''

View file

@ -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
def main():
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:
bot.run(discord_token, root_logger=True)
except Exception as e:
logger.critical(f"Fatal error running bot: {e}")
if __name__ == "__main__":
main()

60
src/bot.py Normal file
View file

@ -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}")

View file

@ -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)

12
src/utils.py Normal file
View file

@ -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)