diff --git a/extensions/admin.py b/extensions/admin.py index 7e400b6..f7d65b6 100644 --- a/extensions/admin.py +++ b/extensions/admin.py @@ -1,6 +1,7 @@ #Adds administrative commands to the bot import os import sys +import logging import subprocess from discord.ext import commands @@ -10,6 +11,7 @@ class Admin(commands.Cog): self.bot = bot self.admin_ids = [242018983241318410] self.log_file = "logs/info.log" + self.logger = logging.getLogger("bot") @commands.command( description="Kill", @@ -20,11 +22,11 @@ class Admin(commands.Cog): async def kill(self, ctx): "Kills the bot" if ctx.author.id in self.admin_ids: - self.bot.logger.info(f"Kill command ran by {ctx.author.id}") + self.logger.info(f"Kill command ran by {ctx.author.id}") exit() else: await ctx.channel.send("You don't have permission to do that.") - self.bot.logger.info(f"Kill command attempted by {ctx.author.id}") + self.logger.info(f"Kill command attempted by {ctx.author.id}") @commands.command( description="Reset", @@ -34,12 +36,12 @@ class Admin(commands.Cog): ) async def reset(self, ctx): if ctx.author.id in self.admin_ids: - self.bot.logger.info(f"Reset command ran by {ctx.author.id}") + self.logger.info(f"Reset command ran by {ctx.author.id}") python = sys.executable os.execl(python, python, *sys.argv) else: await ctx.channel.send("You don't have permission to do that.") - self.bot.logger.info(f"Reset command attempted by {ctx.author.id}") + self.logger.info(f"Reset command attempted by {ctx.author.id}") @commands.command( description="Update", @@ -49,7 +51,7 @@ class Admin(commands.Cog): ) async def update(self, ctx): if ctx.author.id in self.admin_ids: - self.bot.logger.info(f"Update command ran by {ctx.author.id}") + self.logger.info(f"Update command ran by {ctx.author.id}") output = subprocess.run(["git","pull"],capture_output=True) if output.stderr: await ctx.send("Update Attempted") @@ -58,7 +60,7 @@ class Admin(commands.Cog): await ctx.send(output.stdout.decode('utf-8')) else: await ctx.send("You don't have permission to do this.") - self.bot.logger.info(f"Update command attempted by {ctx.author.id}") + self.logger.info(f"Update command attempted by {ctx.author.id}") def is_error(self, log_line): if "ERROR" in log_line: @@ -74,7 +76,7 @@ class Admin(commands.Cog): ) async def errors(self, ctx, amount=5): if ctx.author.id in self.admin_ids: - self.bot.logger.info(f"Errors command ran by {ctx.author.id}") + self.logger.info(f"Errors command ran by {ctx.author.id}") with open(self.log_file, 'r', encoding="utf-8") as log: data = log.readlines() log.close() @@ -87,7 +89,7 @@ class Admin(commands.Cog): await ctx.send("```\n" + "\n".join(errors[::-1]) + "```") else: await ctx.send("You don't have permission to do this.") - self.bot.logger.info(f"Update command attempted by {ctx.author.id}") + self.logger.info(f"Update command attempted by {ctx.author.id}") async def setup(bot): await bot.add_cog(Admin(bot)) \ No newline at end of file diff --git a/extensions/anime.py b/extensions/anime.py index a0dd25e..ef0455f 100644 --- a/extensions/anime.py +++ b/extensions/anime.py @@ -1,4 +1,5 @@ import random +import logging import aiohttp from discord.ext import commands import discord @@ -9,6 +10,7 @@ class Anime(commands.Cog): self.bot = bot self.url = "https://api.waifu.im/search" self.http_session = self.create_aiohttp_session() + self.logger = logging.getLogger("bot") def create_aiohttp_session(self): return aiohttp.ClientSession() @@ -25,10 +27,10 @@ class Anime(commands.Cog): return image['url'] except: if resp_data['detail'] == "No image found matching the criteria given.": - self.bot.logger.info("No image found matching the criteria given.") + self.logger.info("No image found matching the criteria given.") return "No image found matching the criteria given." else: - self.bot.logger.exception("Something went wrong") + self.logger.exception("Something went wrong") return "Something went wrong" async def get_anime_from_img(self, img_url): diff --git a/extensions/chatgpt.py b/extensions/chatgpt.py index c973498..09a3ccc 100644 --- a/extensions/chatgpt.py +++ b/extensions/chatgpt.py @@ -1,6 +1,7 @@ import os import time import json +import logging import random import asyncio import aiofiles @@ -19,6 +20,7 @@ class ChatGPT(commands.Cog): self.folder_setup() self.remind_me_loop.start() self.http_session = self.create_aiohttp_session() + self.logger = logging.getLogger("bot") def create_aiohttp_session(self): return aiohttp.ClientSession( @@ -43,7 +45,7 @@ class ChatGPT(commands.Cog): os.mkdir(folder) except Exception as e: - self.bot.logger.exception(f"ChatGPT failed to make directories: {e}") + self.logger.exception(f"ChatGPT failed to make directories: {e}") def create_channel_config(self, filepath): @@ -57,7 +59,7 @@ class ChatGPT(commands.Cog): with open(filepath,"w") as f: json.dump(config_dict,f) - self.bot.logger.debug("Wrote ChatGPT config variables to file.") + self.logger.debug("Wrote ChatGPT config variables to file.") async def get_channel_config(self, channel_id): filepath = f"{self.data_dir}config/{channel_id}.json" @@ -104,7 +106,7 @@ class ChatGPT(commands.Cog): return response except Exception as error: - self.bot.logger.exception("Error occurred in answer_question") + self.logger.exception("Error occurred in answer_question") return "Error occurred in answer_question" @@ -214,7 +216,7 @@ class ChatGPT(commands.Cog): return response except Exception as error: - self.bot.logger.exception("Error occurred in dalle") + self.logger.exception("Error occurred in dalle") return "Error occurred in dalle" async def download_image(self, url, destination): @@ -293,12 +295,12 @@ class ChatGPT(commands.Cog): try: async with self.http_session.post(url, json=data) as resp: response_data = await resp.json() - self.bot.logger.debug(response_data) + self.logger.debug(response_data) answer = response_data['choices'][0]['message']['content'] except Exception as error: - self.bot.logger.exception("error occurred in looker") + self.logger.exception("error occurred in looker") chunks = [answer[i:i+1999] for i in range(0, len(answer), 1999)] for chunk in chunks: @@ -336,7 +338,7 @@ class ChatGPT(commands.Cog): #CREATE FILEDUMP reminder_data[target_time] = {"user_id":user_id,"response":response} - self.bot.logger.info(f"Reminding user {ctx.author.id} in {duration_s} seconds || Target time (ns): {target_time}") + self.logger.info(f"Reminding user {ctx.author.id} in {duration_s} seconds || Target time (ns): {target_time}") self.save_to_db(reminders_path,reminder_data) @tasks.loop(seconds=60) # THIS ONE NEEDS TO POP AND THEN CALL THE REMIND FUNC @@ -352,12 +354,12 @@ class ChatGPT(commands.Cog): reminder_dict = data[remind_time] sent = await self.remind(reminder_dict) #THIS SENDS THE REMINDER DICT TO REMIND FUNC if sent: - self.bot.logger.info(f"Reminder sent successfully to {reminder_dict['user_id']}") + self.logger.info(f"Reminder sent successfully to {reminder_dict['user_id']}") trash.append(remind_time) #NEED TO POP OR THEY WILL GET REMINDED AD INFINITUM for key in trash: if data.pop(key): - self.bot.logger.debug("Fulfilled reminders successfully purged") + self.logger.debug("Fulfilled reminders successfully purged") self.save_to_db(reminders_path,data) @@ -367,7 +369,7 @@ class ChatGPT(commands.Cog): log_line += ctx.content log_line = ctx.author.name + ": " + log_line +"\n" chat_history = "" - self.bot.logger.debug("Logging: " + log_line, end="") + self.logger.debug("Logging: " + log_line, end="") with open(logfile, "a", encoding="utf-8") as f: f.write(log_line) with open(logfile, "r", encoding="utf-8") as f: @@ -406,7 +408,7 @@ class ChatGPT(commands.Cog): else: await ctx.add_reaction("😓") except Exception as error: - self.bot.logger.exception("Some error happened while trying to react to a message") + self.logger.exception("Some error happened while trying to react to a message") async def chat_response(self, ctx, channel_vars, chat_history_string): async with ctx.channel.typing(): @@ -435,7 +437,7 @@ class ChatGPT(commands.Cog): await ctx.channel.send(message) except Exception as error: - self.bot.logger.exception("Problem with chat_response in chatgpt") + self.logger.exception("Problem with chat_response in chatgpt") @commands.Cog.listener() async def on_reaction_add(self, reaction, user): diff --git a/extensions/donate.py b/extensions/donate.py index a2ed638..dc3e195 100644 --- a/extensions/donate.py +++ b/extensions/donate.py @@ -1,4 +1,4 @@ -#plugin to show message count as a graph +import logging import os import time import matplotlib.pyplot as plt @@ -14,13 +14,14 @@ class Donate(commands.Cog): self.data_dir = "data/donate/" self.donor_file = "data/donate/supporters.txt" self.folder_setup() + self.logger = logging.getLogger("bot") def folder_setup(self): try: if not os.path.exists(self.data_dir): os.mkdir(self.data_dir) except: - self.bot.logger.exception("Donate failed to make directories") + self.logger.exception("Donate failed to make directories") @commands.command( description="Donate", diff --git a/extensions/highscores.py b/extensions/highscores.py index 0411ccb..eb622b9 100644 --- a/extensions/highscores.py +++ b/extensions/highscores.py @@ -1,4 +1,5 @@ -#plugin to show message count as a graph +#cog to show message count as a graph +import logging import os import time import matplotlib.pyplot as plt @@ -10,6 +11,7 @@ class Highscores(commands.Cog): def __init__(self, bot): self.bot = bot + self.logger = logging.getLogger("bot") @commands.command( description="Highscores", @@ -42,7 +44,7 @@ class Highscores(commands.Cog): if user != "" and len(user) <= 32: user_message_counts[user] += 1 except Exception as error: - self.bot.logger.exception("Error occurred in highscores") + self.logger.exception("Error occurred in highscores") sorted_message_counts = sorted(user_message_counts.items(), key=lambda x:x[1]) sorted_dict = dict(sorted_message_counts[-limit::]) @@ -94,7 +96,7 @@ class Highscores(commands.Cog): if user != "" and len(user) <= 32: user_message_counts[user] += 1 except Exception as error: - self.bot.logger.exception("Error occurred in highscores_server") + self.logger.exception("Error occurred in highscores_server") sorted_message_counts = sorted(user_message_counts.items(), key=lambda x:x[1]) sorted_dict = dict(sorted_message_counts[-limit::]) diff --git a/extensions/inky_phat.py b/extensions/inky_phat.py index f4a3a99..deed2b2 100644 --- a/extensions/inky_phat.py +++ b/extensions/inky_phat.py @@ -1,5 +1,6 @@ import socket # used to get local IP import time +import logging import os import datetime import psutil @@ -23,6 +24,7 @@ class InkyScreen(commands.Cog): self.start_time = time.time() self.admin_ids = [242018983241318410] self.font_size = 18 + self.logger = logging.getLogger("bot") self.message_loop.start() def setup(self): @@ -38,7 +40,7 @@ class InkyScreen(commands.Cog): #try: # image = Image.open("data/inky/bg.png") #except: - # self.bot.logger.exception("InkyScreen: Failed to load background image.") + # self.logger.exception("InkyScreen: Failed to load background image.") image = Image.new("P", (self.display.WIDTH, self.display.HEIGHT), (self.display.BLACK)) draw = ImageDraw.Draw(image) width = self.display.WIDTH @@ -47,8 +49,8 @@ class InkyScreen(commands.Cog): try: height_diff = height/lines except: - self.bot.logger.exception("InkyScreen: Failed to calculate height_diff.") - self.bot.logger.info(f"InkyScreen: Text: {text}") + self.logger.exception("InkyScreen: Failed to calculate height_diff.") + self.logger.info(f"InkyScreen: Text: {text}") return x = 0 y = 0 @@ -57,14 +59,14 @@ class InkyScreen(commands.Cog): draw.text((x, y), line, self.display.YELLOW, font=ImageFont.load_default(size=self.font_size)) y += height_diff else: - self.bot.logger.warning("InkyScreen: Text too long to fit on image.") + self.logger.warning("InkyScreen: Text too long to fit on image.") image = image.rotate(180) self.display.set_image(image) self.display.show() - self.bot.logger.info("InkyScreen: Text successfully written to image.") + self.logger.info("InkyScreen: Text successfully written to image.") self.old_message = text else: - self.bot.logger.info("InkyScreen: Text is the same as the previous message, not writing to image.") + self.logger.info("InkyScreen: Text is the same as the previous message, not writing to image.") def get_ip_address(self): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) @@ -123,7 +125,7 @@ class InkyScreen(commands.Cog): message_list.append(self.get_disk_usage()) except Exception as e: - self.bot.logger.error(f"Error generating InkyScreen message: {e}") + self.logger.error(f"Error generating InkyScreen message: {e}") return message_list diff --git a/extensions/meme.py b/extensions/meme.py index b9af245..e1557a1 100644 --- a/extensions/meme.py +++ b/extensions/meme.py @@ -3,6 +3,7 @@ import os import random import aiohttp from discord.ext import commands +import logging class Meme(commands.Cog): @@ -11,6 +12,7 @@ class Meme(commands.Cog): self.working_dir = "tmp/meme/" self.folder_setup() self.http_session = self.create_aiohttp_session() + self.logger = logging.getLogger("bot") def create_aiohttp_session(self): return aiohttp.ClientSession() @@ -20,7 +22,7 @@ class Meme(commands.Cog): if not os.path.exists(self.working_dir): os.mkdir(self.working_dir) except: - self.bot.logger.exception("Meme failed to make directories") + self.logger.exception("Meme failed to make directories") async def answer_question(self, topic, model="gpt-3.5-turbo"): headers = { @@ -40,7 +42,7 @@ class Meme(commands.Cog): response_data = await resp.json() response = response_data['choices'][0]['message']['content'] return response - except Exception as error: + except: return "error occurred in meme" @commands.command( @@ -89,8 +91,8 @@ class Meme(commands.Cog): async with self.http_session.post(URL, params=params) as resp: response = await resp.json() image_link = response['data']['url'] - except Exception as error: - self.bot.logger.exception("Error occurred in meme") + except: + self.logger.exception("Error occurred in meme") try: #------------------------------------Saving Image Using Aiohttp---------------------------------# filename = memepics[id-1]['name'] @@ -105,7 +107,7 @@ class Meme(commands.Cog): break file.write(chunk) except: - self.bot.logger.exception("Something's Wrong with the aiohttp in meme So try again") + self.logger.exception("Something's Wrong with the aiohttp in meme So try again") return image_link, filename try: @@ -113,8 +115,8 @@ class Meme(commands.Cog): await ctx.send(f'Generating {topic} meme') link, filepath = await generate_random_meme(topic) await ctx.send(link) - except Exception as error: - self.bot.logger.exception("Error occurred in meme") + except: + self.logger.exception("Error occurred in meme") await ctx.send('Something went wrong try again. Usage: !meme (topic)') async def setup(bot): diff --git a/extensions/phixxycom.py b/extensions/phixxycom.py index 8536eb7..5fd3f9a 100644 --- a/extensions/phixxycom.py +++ b/extensions/phixxycom.py @@ -1,6 +1,7 @@ import os import io import base64 +import logging import time import html import aiohttp @@ -19,6 +20,7 @@ class PhixxyCom(commands.Cog): self.data_dir = "data/phixxy.com/" self.folder_setup() self.stable_diffusion_log = "data/stable_diffusion/stable_diffusion.log" + self.logger = logging.getLogger("bot") self.phixxy_loop.start() self.blog_loop.start() self.http_session = self.create_aiohttp_session() @@ -33,7 +35,7 @@ class PhixxyCom(commands.Cog): if not os.path.exists(self.data_dir): os.mkdir(self.data_dir) except: - self.bot.logger.exception("PhixxyCom failed to make directories") + self.logger.exception("PhixxyCom failed to make directories") def find_prompt_from_filename(self, sd_log, filename): with open(sd_log, 'r') as f: @@ -45,7 +47,7 @@ class PhixxyCom(commands.Cog): prompt = ''.join(prompt.rsplit(',', 1)) # Remove the last comma return html.escape(prompt) except: - self.bot.logger.exception("PhixxyCom failed to find prompt from filename") + self.logger.exception("PhixxyCom failed to find prompt from filename") return "Unknown Prompt" return "Unknown Prompt" @@ -66,10 +68,10 @@ class PhixxyCom(commands.Cog): for filename in (await sftp.listdir(server_folder)): if '.png' in filename: try: - self.bot.logger.debug("Deleting", filename) + self.logger.debug("Deleting", filename) await sftp.remove(server_folder+filename) except: - self.bot.logger.exception("Couldn't delete", filename) + self.logger.exception("Couldn't delete", filename) async def extract_image_tags(self,code): count = code.count("' @@ -165,9 +167,9 @@ class PhixxyCom(commands.Cog): for filename in os.listdir(folder): if filename[-4:] == '.png': filepath = folder + filename - self.bot.logger.info(f"Found file = {filename}") + self.logger.info(f"Found file = {filename}") prompt = self.find_prompt_from_filename(ai_dict[folder], filename) - self.bot.logger.info(f"Found prompt = {prompt}") + self.logger.info(f"Found prompt = {prompt}") html_file = f"{self.data_dir}ai-images/index.html" html_insert = '''
@@ -177,7 +179,7 @@ class PhixxyCom(commands.Cog): server_folder = (os.getenv('ftp_public_html') + 'ai-images/') new_filename = str(time.time_ns()) + ".png" await self.upload_sftp(filepath, server_folder, new_filename) - self.bot.logger.info(f"Uploaded {new_filename}") + self.logger.info(f"Uploaded {new_filename}") with open(html_file, 'r') as f: html_data = f.read() html_insert = html_insert.replace("", new_filename) @@ -188,7 +190,7 @@ class PhixxyCom(commands.Cog): await self.upload_sftp(html_file, server_folder, "index.html") os.rename(filepath, f"tmp/{new_filename}") except: - self.bot.logger.exception("Something went wrong in upload_ftp_ai_images") + self.logger.exception("Something went wrong in upload_ftp_ai_images") async def answer_question(self, topic, model="gpt-3.5-turbo"): headers = { @@ -257,11 +259,11 @@ class PhixxyCom(commands.Cog): with open(blogpost_file, 'w') as f: f.write(blogpost_topics) if topic != '': - self.bot.logger.info("Writing blogpost") + self.logger.info("Writing blogpost") else: messages = self.get_last_5_messages() question = f"you have a blog and you are inspired based on this short text chat interaction:\n{messages}\nwhat will the topic of your next blog be? just tell me the topic and a one sentence description" - self.bot.logger.info("No topic given for blogpost, generating one.") + self.logger.info("No topic given for blogpost, generating one.") topic = await self.answer_question(question) post_div = '''
@@ -290,7 +292,7 @@ class PhixxyCom(commands.Cog): f.write(html_data) await self.upload_sftp(filename, (os.getenv('ftp_public_html') + 'ai-blog/'), "index.html") run_time = time.time() - start_time - self.bot.logger.debug("It took " + str(run_time) + " seconds to generate the blog post!") + self.logger.debug("It took " + str(run_time) + " seconds to generate the blog post!") output = "Blog Updated! (" + str(run_time) + " seconds) https://ai.phixxy.com/ai-blog" return output @@ -337,7 +339,7 @@ class PhixxyCom(commands.Cog): await ctx.send("Finished https://ai.phixxy.com/ai-webpage/") except Exception as error: #await ctx.send("Failed, Try again.") - self.bot.logger.exception("Website Error") + self.logger.exception("Website Error") @tasks.loop(seconds=60) async def phixxy_loop(self): @@ -359,7 +361,7 @@ class PhixxyCom(commands.Cog): if message: await bot_stuff_channel.send(message) except Exception as error: - self.bot.logger.exception("Failed to generate blog") + self.logger.exception("Failed to generate blog") @commands.command( description="Moderate", diff --git a/extensions/pokedex.py b/extensions/pokedex.py index b1a2839..6d5ce76 100644 --- a/extensions/pokedex.py +++ b/extensions/pokedex.py @@ -1,3 +1,4 @@ +import logging import aiohttp from discord.ext import commands import discord @@ -69,7 +70,7 @@ class Pokedex(commands.Cog): embed.set_footer(text=footer) await ctx.send(embed=embed) except: - self.bot.logger.exception("Something went wrong in pokedex") + self.logger.exception("Something went wrong in pokedex") message = "No data for " + str(pokemon) await ctx.channel.send(message) diff --git a/extensions/pokemon.py b/extensions/pokemon.py index 8ffd124..3848892 100644 --- a/extensions/pokemon.py +++ b/extensions/pokemon.py @@ -1,4 +1,5 @@ import random +import logging import os import json import math @@ -16,6 +17,7 @@ class PokemonGame(commands.Cog): self.data_dir = "data/pokemon/" self.folder_setup() self.http_session = self.create_aiohttp_session() + self.logger = logging.getLogger("bot") def create_aiohttp_session(self): return aiohttp.ClientSession() @@ -32,7 +34,7 @@ class PokemonGame(commands.Cog): if not os.path.exists(self.data_dir): os.mkdir(self.data_dir) except: - self.bot.logger.exception("PokemonGame failed to make directories") + self.logger.exception("PokemonGame failed to make directories") async def starter_picker(self, id): #id = pokedex number url = "https://pokeapi.co/api/v2/pokemon-species/" + str(id) diff --git a/extensions/stable_diffusion.py b/extensions/stable_diffusion.py index 7f62c2c..cf3560d 100644 --- a/extensions/stable_diffusion.py +++ b/extensions/stable_diffusion.py @@ -1,6 +1,6 @@ -# Extension for sparkytron 3000 # This extension enables the ability to generate AI artwork using the AUTOMATIC1111 API import io +import logging import base64 import os import time @@ -21,6 +21,7 @@ class StableDiffusion(commands.Cog): self.default_neg_prompt = "easynegative, badhandv4, verybadimagenegative_v1.3" self.folder_setup() self.http_session = self.create_aiohttp_session() + self.logger = logging.getLogger("bot") def create_aiohttp_session(self): return aiohttp.ClientSession() @@ -34,7 +35,7 @@ class StableDiffusion(commands.Cog): if not os.path.exists(self.data_dir): os.mkdir(self.data_dir) except: - self.bot.logger.exception("StableDiffusion failed to make directories") + self.logger.exception("StableDiffusion failed to make directories") """ answer_question asynchronously calls the OpenAI API to get a response for the given question/topic using the specified model. @@ -153,12 +154,12 @@ class StableDiffusion(commands.Cog): return "Stable Diffusion is disabled, could not look at image" for attachment in ctx.attachments: if attachment.url.endswith(('.jpg', '.png')): - self.bot.logger.debug("image seen") + self.logger.debug("image seen") async with self.http_session.get(attachment.url) as response: imageName = self.working_dir + str(time.time_ns()) + '.png' with open(imageName, 'wb') as out_file: - self.bot.logger.debug('Saving image: ' + imageName) + self.logger.debug('Saving image: ' + imageName) while True: chunk = await response.content.read(1024) if not chunk: @@ -175,7 +176,7 @@ class StableDiffusion(commands.Cog): description = description.split(',')[0] metadata += f"\n" except aiohttp.ClientError: - self.bot.logger.exception("ERROR: CLIP may not be running. Could not look at image.") + self.logger.exception("ERROR: CLIP may not be running. Could not look at image.") return "ERROR: CLIP may not be running. Could not look at image." return metadata @@ -281,7 +282,7 @@ class StableDiffusion(commands.Cog): file_url = ctx.message.content.split(" ", maxsplit=1)[1] return file_url except: - self.bot.logger.info("Couldn't find image.") + self.logger.info("Couldn't find image.") return None """ @@ -309,16 +310,16 @@ class StableDiffusion(commands.Cog): async with self.http_session.post(url, headers=headers, json=payload) as resp: if resp.status != 200: await ctx.send(f"{resp.status} {resp.reason}") - self.bot.logger.exception(f"{resp.status} {resp.reason}") + self.logger.exception(f"{resp.status} {resp.reason}") return r = await resp.json() except ConnectionRefusedError: await ctx.send("Failed to connect to image generation service") - self.bot.logger.exception("Failed to connect to image generation service") + self.logger.exception("Failed to connect to image generation service") return except: await ctx.send("Failed to generate image") - self.bot.logger.exception("Failed to generate image") + self.logger.exception("Failed to generate image") return await self.send_generated_image(ctx, r['images'], prompt) @@ -336,7 +337,7 @@ class StableDiffusion(commands.Cog): async with self.http_session.get(url) as response: image_name = self.working_dir + str(time.time_ns()) + ".png" with open(image_name, 'wb') as out_file: - self.bot.logger.debug(f"Saving image: {image_name}") + self.logger.debug(f"Saving image: {image_name}") while True: chunk = await response.content.read(1024) if not chunk: @@ -379,16 +380,16 @@ class StableDiffusion(commands.Cog): async with self.http_session.post(url, headers=headers, json=payload) as resp: if resp.status != 200: await ctx.send(f"{resp.status} {resp.reason}") - self.bot.logger.error(f"{resp.status} {resp.reason}") + self.logger.error(f"{resp.status} {resp.reason}") return r = await resp.json() except ConnectionRefusedError: await ctx.send("Failed to connect to image generation service") - self.bot.logger.exception("Failed to connect to image generation service") + self.logger.exception("Failed to connect to image generation service") return except: await ctx.send("Failed to generate image") - self.bot.logger.exception("Failed to generate image") + self.logger.exception("Failed to generate image") return await self.send_generated_image(ctx, r['images'], prompt) @@ -493,7 +494,7 @@ class StableDiffusion(commands.Cog): r = await response.json() await ctx.send(r.get("caption")) except: - self.bot.logger.exception("error in describe") + self.logger.exception("error in describe") await ctx.send("My image generation service may not be running.") @commands.command( diff --git a/extensions/tts.py b/extensions/tts.py index b1004a3..c5a5765 100644 --- a/extensions/tts.py +++ b/extensions/tts.py @@ -1,5 +1,6 @@ import time import os +import logging import aiohttp import discord from discord.ext import commands @@ -12,6 +13,7 @@ class TextToSpeech(commands.Cog): self.data_dir = "data/tts/" self.folder_setup() self.http_session = self.create_aiohttp_session() + self.logger = logging.getLogger("bot") def create_aiohttp_session(self): return aiohttp.ClientSession() @@ -23,7 +25,7 @@ class TextToSpeech(commands.Cog): if not os.path.exists(self.data_dir): os.mkdir(self.data_dir) except: - self.bot.logger.exception("TextToSpeech failed to make directories") + self.logger.exception("TextToSpeech failed to make directories") async def text_to_speech(self, prompt): CHUNK_SIZE = 1024 @@ -98,7 +100,7 @@ class TextToSpeech(commands.Cog): await ctx.send(file=discord.File(filepath)) except: await ctx.send("Error in tts") - self.bot.logger.exception("Error in tts") + self.logger.exception("Error in tts") @commands.command() async def opentts(self, ctx): @@ -113,7 +115,7 @@ class TextToSpeech(commands.Cog): await ctx.send(file=discord.File(filepath)) except: await ctx.send("Error in tts") - self.bot.logger.exception("Error in tts") + self.logger.exception("Error in tts") async def setup(bot): await bot.add_cog(TextToSpeech(bot)) \ No newline at end of file diff --git a/src/bot.py b/src/bot.py index f3f278a..802951d 100644 --- a/src/bot.py +++ b/src/bot.py @@ -2,22 +2,23 @@ import os import discord from discord.ext import commands from dotenv import load_dotenv -import src.logger as logger +import src.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() +logger = src.logger.logger_setup() + 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}") + logger.info(f"Successfully loaded plugin {plugin_file}") except: - bot.logger.exception(f"Failed to load plugin {plugin_file}") + logger.exception(f"Failed to load plugin {plugin_file}") @bot.event async def on_ready(): @@ -25,17 +26,17 @@ async def on_ready(): 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)) + logger.info('We have logged in as {0.user}'.format(bot)) except: - bot.logger.warning(f"Error in on_ready") + 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.") + logger.info("Command not found.") except discord.ext.commands.errors.CommandNotFound: - bot.logger.info("Command not found.") + logger.info("Command not found.") except Exception as e: - bot.logger.warning(f"Error processing commands: {e}") + logger.warning(f"Error processing commands: {e}")