removed bot.logger, have each cog handle logging

This commit is contained in:
phixxy 2024-02-14 00:00:58 -08:00
parent 95d585b5dd
commit bdcdd87348
13 changed files with 107 additions and 85 deletions

View file

@ -1,6 +1,7 @@
#Adds administrative commands to the bot #Adds administrative commands to the bot
import os import os
import sys import sys
import logging
import subprocess import subprocess
from discord.ext import commands from discord.ext import commands
@ -10,6 +11,7 @@ class Admin(commands.Cog):
self.bot = bot self.bot = bot
self.admin_ids = [242018983241318410] self.admin_ids = [242018983241318410]
self.log_file = "logs/info.log" self.log_file = "logs/info.log"
self.logger = logging.getLogger("bot")
@commands.command( @commands.command(
description="Kill", description="Kill",
@ -20,11 +22,11 @@ class Admin(commands.Cog):
async def kill(self, ctx): async def kill(self, ctx):
"Kills the bot" "Kills the bot"
if ctx.author.id in self.admin_ids: 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() exit()
else: else:
await ctx.channel.send("You don't have permission to do that.") 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( @commands.command(
description="Reset", description="Reset",
@ -34,12 +36,12 @@ class Admin(commands.Cog):
) )
async def reset(self, ctx): async def reset(self, ctx):
if ctx.author.id in self.admin_ids: 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 python = sys.executable
os.execl(python, python, *sys.argv) os.execl(python, python, *sys.argv)
else: else:
await ctx.channel.send("You don't have permission to do that.") 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( @commands.command(
description="Update", description="Update",
@ -49,7 +51,7 @@ class Admin(commands.Cog):
) )
async def update(self, ctx): async def update(self, ctx):
if ctx.author.id in self.admin_ids: 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) output = subprocess.run(["git","pull"],capture_output=True)
if output.stderr: if output.stderr:
await ctx.send("Update Attempted") await ctx.send("Update Attempted")
@ -58,7 +60,7 @@ class Admin(commands.Cog):
await ctx.send(output.stdout.decode('utf-8')) await ctx.send(output.stdout.decode('utf-8'))
else: else:
await ctx.send("You don't have permission to do this.") 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): def is_error(self, log_line):
if "ERROR" in log_line: if "ERROR" in log_line:
@ -74,7 +76,7 @@ class Admin(commands.Cog):
) )
async def errors(self, ctx, amount=5): async def errors(self, ctx, amount=5):
if ctx.author.id in self.admin_ids: 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: with open(self.log_file, 'r', encoding="utf-8") as log:
data = log.readlines() data = log.readlines()
log.close() log.close()
@ -87,7 +89,7 @@ class Admin(commands.Cog):
await ctx.send("```\n" + "\n".join(errors[::-1]) + "```") await ctx.send("```\n" + "\n".join(errors[::-1]) + "```")
else: else:
await ctx.send("You don't have permission to do this.") 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): async def setup(bot):
await bot.add_cog(Admin(bot)) await bot.add_cog(Admin(bot))

View file

@ -1,4 +1,5 @@
import random import random
import logging
import aiohttp import aiohttp
from discord.ext import commands from discord.ext import commands
import discord import discord
@ -9,6 +10,7 @@ class Anime(commands.Cog):
self.bot = bot self.bot = bot
self.url = "https://api.waifu.im/search" self.url = "https://api.waifu.im/search"
self.http_session = self.create_aiohttp_session() self.http_session = self.create_aiohttp_session()
self.logger = logging.getLogger("bot")
def create_aiohttp_session(self): def create_aiohttp_session(self):
return aiohttp.ClientSession() return aiohttp.ClientSession()
@ -25,10 +27,10 @@ class Anime(commands.Cog):
return image['url'] return image['url']
except: except:
if resp_data['detail'] == "No image found matching the criteria given.": 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." return "No image found matching the criteria given."
else: else:
self.bot.logger.exception("Something went wrong") self.logger.exception("Something went wrong")
return "Something went wrong" return "Something went wrong"
async def get_anime_from_img(self, img_url): async def get_anime_from_img(self, img_url):

View file

@ -1,6 +1,7 @@
import os import os
import time import time
import json import json
import logging
import random import random
import asyncio import asyncio
import aiofiles import aiofiles
@ -19,6 +20,7 @@ class ChatGPT(commands.Cog):
self.folder_setup() self.folder_setup()
self.remind_me_loop.start() self.remind_me_loop.start()
self.http_session = self.create_aiohttp_session() self.http_session = self.create_aiohttp_session()
self.logger = logging.getLogger("bot")
def create_aiohttp_session(self): def create_aiohttp_session(self):
return aiohttp.ClientSession( return aiohttp.ClientSession(
@ -43,7 +45,7 @@ class ChatGPT(commands.Cog):
os.mkdir(folder) os.mkdir(folder)
except Exception as e: 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): def create_channel_config(self, filepath):
@ -57,7 +59,7 @@ class ChatGPT(commands.Cog):
with open(filepath,"w") as f: with open(filepath,"w") as f:
json.dump(config_dict,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): async def get_channel_config(self, channel_id):
filepath = f"{self.data_dir}config/{channel_id}.json" filepath = f"{self.data_dir}config/{channel_id}.json"
@ -104,7 +106,7 @@ class ChatGPT(commands.Cog):
return response return response
except Exception as error: 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" return "Error occurred in answer_question"
@ -214,7 +216,7 @@ class ChatGPT(commands.Cog):
return response return response
except Exception as error: except Exception as error:
self.bot.logger.exception("Error occurred in dalle") self.logger.exception("Error occurred in dalle")
return "Error occurred in dalle" return "Error occurred in dalle"
async def download_image(self, url, destination): async def download_image(self, url, destination):
@ -293,12 +295,12 @@ class ChatGPT(commands.Cog):
try: try:
async with self.http_session.post(url, json=data) as resp: async with self.http_session.post(url, json=data) as resp:
response_data = await resp.json() response_data = await resp.json()
self.bot.logger.debug(response_data) self.logger.debug(response_data)
answer = response_data['choices'][0]['message']['content'] answer = response_data['choices'][0]['message']['content']
except Exception as error: 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)] chunks = [answer[i:i+1999] for i in range(0, len(answer), 1999)]
for chunk in chunks: for chunk in chunks:
@ -336,7 +338,7 @@ class ChatGPT(commands.Cog):
#CREATE FILEDUMP #CREATE FILEDUMP
reminder_data[target_time] = {"user_id":user_id,"response":response} 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) self.save_to_db(reminders_path,reminder_data)
@tasks.loop(seconds=60) # THIS ONE NEEDS TO POP AND THEN CALL THE REMIND FUNC @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] reminder_dict = data[remind_time]
sent = await self.remind(reminder_dict) #THIS SENDS THE REMINDER DICT TO REMIND FUNC sent = await self.remind(reminder_dict) #THIS SENDS THE REMINDER DICT TO REMIND FUNC
if sent: 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 trash.append(remind_time) #NEED TO POP OR THEY WILL GET REMINDED AD INFINITUM
for key in trash: for key in trash:
if data.pop(key): 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) self.save_to_db(reminders_path,data)
@ -367,7 +369,7 @@ class ChatGPT(commands.Cog):
log_line += ctx.content log_line += ctx.content
log_line = ctx.author.name + ": " + log_line +"\n" log_line = ctx.author.name + ": " + log_line +"\n"
chat_history = "" 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: with open(logfile, "a", encoding="utf-8") as f:
f.write(log_line) f.write(log_line)
with open(logfile, "r", encoding="utf-8") as f: with open(logfile, "r", encoding="utf-8") as f:
@ -406,7 +408,7 @@ class ChatGPT(commands.Cog):
else: else:
await ctx.add_reaction("😓") await ctx.add_reaction("😓")
except Exception as error: 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 def chat_response(self, ctx, channel_vars, chat_history_string):
async with ctx.channel.typing(): async with ctx.channel.typing():
@ -435,7 +437,7 @@ class ChatGPT(commands.Cog):
await ctx.channel.send(message) await ctx.channel.send(message)
except Exception as error: 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() @commands.Cog.listener()
async def on_reaction_add(self, reaction, user): async def on_reaction_add(self, reaction, user):

View file

@ -1,4 +1,4 @@
#plugin to show message count as a graph import logging
import os import os
import time import time
import matplotlib.pyplot as plt import matplotlib.pyplot as plt
@ -14,13 +14,14 @@ class Donate(commands.Cog):
self.data_dir = "data/donate/" self.data_dir = "data/donate/"
self.donor_file = "data/donate/supporters.txt" self.donor_file = "data/donate/supporters.txt"
self.folder_setup() self.folder_setup()
self.logger = logging.getLogger("bot")
def folder_setup(self): def folder_setup(self):
try: try:
if not os.path.exists(self.data_dir): if not os.path.exists(self.data_dir):
os.mkdir(self.data_dir) os.mkdir(self.data_dir)
except: except:
self.bot.logger.exception("Donate failed to make directories") self.logger.exception("Donate failed to make directories")
@commands.command( @commands.command(
description="Donate", description="Donate",

View file

@ -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 os
import time import time
import matplotlib.pyplot as plt import matplotlib.pyplot as plt
@ -10,6 +11,7 @@ class Highscores(commands.Cog):
def __init__(self, bot): def __init__(self, bot):
self.bot = bot self.bot = bot
self.logger = logging.getLogger("bot")
@commands.command( @commands.command(
description="Highscores", description="Highscores",
@ -42,7 +44,7 @@ class Highscores(commands.Cog):
if user != "" and len(user) <= 32: if user != "" and len(user) <= 32:
user_message_counts[user] += 1 user_message_counts[user] += 1
except Exception as error: 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_message_counts = sorted(user_message_counts.items(), key=lambda x:x[1])
sorted_dict = dict(sorted_message_counts[-limit::]) sorted_dict = dict(sorted_message_counts[-limit::])
@ -94,7 +96,7 @@ class Highscores(commands.Cog):
if user != "" and len(user) <= 32: if user != "" and len(user) <= 32:
user_message_counts[user] += 1 user_message_counts[user] += 1
except Exception as error: 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_message_counts = sorted(user_message_counts.items(), key=lambda x:x[1])
sorted_dict = dict(sorted_message_counts[-limit::]) sorted_dict = dict(sorted_message_counts[-limit::])

View file

@ -1,5 +1,6 @@
import socket # used to get local IP import socket # used to get local IP
import time import time
import logging
import os import os
import datetime import datetime
import psutil import psutil
@ -23,6 +24,7 @@ class InkyScreen(commands.Cog):
self.start_time = time.time() self.start_time = time.time()
self.admin_ids = [242018983241318410] self.admin_ids = [242018983241318410]
self.font_size = 18 self.font_size = 18
self.logger = logging.getLogger("bot")
self.message_loop.start() self.message_loop.start()
def setup(self): def setup(self):
@ -38,7 +40,7 @@ class InkyScreen(commands.Cog):
#try: #try:
# image = Image.open("data/inky/bg.png") # image = Image.open("data/inky/bg.png")
#except: #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)) image = Image.new("P", (self.display.WIDTH, self.display.HEIGHT), (self.display.BLACK))
draw = ImageDraw.Draw(image) draw = ImageDraw.Draw(image)
width = self.display.WIDTH width = self.display.WIDTH
@ -47,8 +49,8 @@ class InkyScreen(commands.Cog):
try: try:
height_diff = height/lines height_diff = height/lines
except: except:
self.bot.logger.exception("InkyScreen: Failed to calculate height_diff.") self.logger.exception("InkyScreen: Failed to calculate height_diff.")
self.bot.logger.info(f"InkyScreen: Text: {text}") self.logger.info(f"InkyScreen: Text: {text}")
return return
x = 0 x = 0
y = 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)) draw.text((x, y), line, self.display.YELLOW, font=ImageFont.load_default(size=self.font_size))
y += height_diff y += height_diff
else: 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) image = image.rotate(180)
self.display.set_image(image) self.display.set_image(image)
self.display.show() 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 self.old_message = text
else: 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): def get_ip_address(self):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
@ -123,7 +125,7 @@ class InkyScreen(commands.Cog):
message_list.append(self.get_disk_usage()) message_list.append(self.get_disk_usage())
except Exception as e: 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 return message_list

View file

@ -3,6 +3,7 @@ import os
import random import random
import aiohttp import aiohttp
from discord.ext import commands from discord.ext import commands
import logging
class Meme(commands.Cog): class Meme(commands.Cog):
@ -11,6 +12,7 @@ class Meme(commands.Cog):
self.working_dir = "tmp/meme/" self.working_dir = "tmp/meme/"
self.folder_setup() self.folder_setup()
self.http_session = self.create_aiohttp_session() self.http_session = self.create_aiohttp_session()
self.logger = logging.getLogger("bot")
def create_aiohttp_session(self): def create_aiohttp_session(self):
return aiohttp.ClientSession() return aiohttp.ClientSession()
@ -20,7 +22,7 @@ class Meme(commands.Cog):
if not os.path.exists(self.working_dir): if not os.path.exists(self.working_dir):
os.mkdir(self.working_dir) os.mkdir(self.working_dir)
except: 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"): async def answer_question(self, topic, model="gpt-3.5-turbo"):
headers = { headers = {
@ -40,7 +42,7 @@ class Meme(commands.Cog):
response_data = await resp.json() response_data = await resp.json()
response = response_data['choices'][0]['message']['content'] response = response_data['choices'][0]['message']['content']
return response return response
except Exception as error: except:
return "error occurred in meme" return "error occurred in meme"
@commands.command( @commands.command(
@ -89,8 +91,8 @@ class Meme(commands.Cog):
async with self.http_session.post(URL, params=params) as resp: async with self.http_session.post(URL, params=params) as resp:
response = await resp.json() response = await resp.json()
image_link = response['data']['url'] image_link = response['data']['url']
except Exception as error: except:
self.bot.logger.exception("Error occurred in meme") self.logger.exception("Error occurred in meme")
try: try:
#------------------------------------Saving Image Using Aiohttp---------------------------------# #------------------------------------Saving Image Using Aiohttp---------------------------------#
filename = memepics[id-1]['name'] filename = memepics[id-1]['name']
@ -105,7 +107,7 @@ class Meme(commands.Cog):
break break
file.write(chunk) file.write(chunk)
except: 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 return image_link, filename
try: try:
@ -113,8 +115,8 @@ class Meme(commands.Cog):
await ctx.send(f'Generating {topic} meme') await ctx.send(f'Generating {topic} meme')
link, filepath = await generate_random_meme(topic) link, filepath = await generate_random_meme(topic)
await ctx.send(link) await ctx.send(link)
except Exception as error: except:
self.bot.logger.exception("Error occurred in meme") self.logger.exception("Error occurred in meme")
await ctx.send('Something went wrong try again. Usage: !meme (topic)') await ctx.send('Something went wrong try again. Usage: !meme (topic)')
async def setup(bot): async def setup(bot):

View file

@ -1,6 +1,7 @@
import os import os
import io import io
import base64 import base64
import logging
import time import time
import html import html
import aiohttp import aiohttp
@ -19,6 +20,7 @@ class PhixxyCom(commands.Cog):
self.data_dir = "data/phixxy.com/" self.data_dir = "data/phixxy.com/"
self.folder_setup() self.folder_setup()
self.stable_diffusion_log = "data/stable_diffusion/stable_diffusion.log" self.stable_diffusion_log = "data/stable_diffusion/stable_diffusion.log"
self.logger = logging.getLogger("bot")
self.phixxy_loop.start() self.phixxy_loop.start()
self.blog_loop.start() self.blog_loop.start()
self.http_session = self.create_aiohttp_session() self.http_session = self.create_aiohttp_session()
@ -33,7 +35,7 @@ class PhixxyCom(commands.Cog):
if not os.path.exists(self.data_dir): if not os.path.exists(self.data_dir):
os.mkdir(self.data_dir) os.mkdir(self.data_dir)
except: 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): def find_prompt_from_filename(self, sd_log, filename):
with open(sd_log, 'r') as f: with open(sd_log, 'r') as f:
@ -45,7 +47,7 @@ class PhixxyCom(commands.Cog):
prompt = ''.join(prompt.rsplit(',', 1)) # Remove the last comma prompt = ''.join(prompt.rsplit(',', 1)) # Remove the last comma
return html.escape(prompt) return html.escape(prompt)
except: 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"
return "Unknown Prompt" return "Unknown Prompt"
@ -66,10 +68,10 @@ class PhixxyCom(commands.Cog):
for filename in (await sftp.listdir(server_folder)): for filename in (await sftp.listdir(server_folder)):
if '.png' in filename: if '.png' in filename:
try: try:
self.bot.logger.debug("Deleting", filename) self.logger.debug("Deleting", filename)
await sftp.remove(server_folder+filename) await sftp.remove(server_folder+filename)
except: except:
self.bot.logger.exception("Couldn't delete", filename) self.logger.exception("Couldn't delete", filename)
async def extract_image_tags(self,code): async def extract_image_tags(self,code):
count = code.count("<img") count = code.count("<img")
@ -135,10 +137,10 @@ class PhixxyCom(commands.Cog):
pass pass
else: else:
try: try:
self.bot.logger.debug("Deleting", filename) self.logger.debug("Deleting", filename)
await sftp.remove(server_folder+filename) await sftp.remove(server_folder+filename)
except: except:
self.bot.logger.exception("Couldn't delete", filename) self.logger.exception("Couldn't delete", filename)
async def meme_handler(self, folder): async def meme_handler(self, folder):
for f in os.listdir(folder): for f in os.listdir(folder):
@ -149,7 +151,7 @@ class PhixxyCom(commands.Cog):
server_folder = (os.getenv('ftp_public_html') + 'ai-memes/') server_folder = (os.getenv('ftp_public_html') + 'ai-memes/')
new_file_name = str(time.time_ns()) + ".png" new_file_name = str(time.time_ns()) + ".png"
await self.upload_sftp(filename, server_folder, new_file_name) await self.upload_sftp(filename, server_folder, new_file_name)
self.bot.logger.debug(f"Uploaded {new_file_name}") self.logger.debug(f"Uploaded {new_file_name}")
with open(f"{self.data_dir}ai-memes/index.html", 'r') as f: with open(f"{self.data_dir}ai-memes/index.html", 'r') as f:
html_data = f.read() html_data = f.read()
html_insert = '<!--ADD IMG HERE-->\n <img src="' + new_file_name + '" loading="lazy">' html_insert = '<!--ADD IMG HERE-->\n <img src="' + new_file_name + '" loading="lazy">'
@ -165,9 +167,9 @@ class PhixxyCom(commands.Cog):
for filename in os.listdir(folder): for filename in os.listdir(folder):
if filename[-4:] == '.png': if filename[-4:] == '.png':
filepath = folder + filename 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) 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_file = f"{self.data_dir}ai-images/index.html"
html_insert = '''<!--REPLACE THIS COMMENT--> html_insert = '''<!--REPLACE THIS COMMENT-->
<div> <div>
@ -177,7 +179,7 @@ class PhixxyCom(commands.Cog):
server_folder = (os.getenv('ftp_public_html') + 'ai-images/') server_folder = (os.getenv('ftp_public_html') + 'ai-images/')
new_filename = str(time.time_ns()) + ".png" new_filename = str(time.time_ns()) + ".png"
await self.upload_sftp(filepath, server_folder, new_filename) 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: with open(html_file, 'r') as f:
html_data = f.read() html_data = f.read()
html_insert = html_insert.replace("<!--filename-->", new_filename) html_insert = html_insert.replace("<!--filename-->", new_filename)
@ -188,7 +190,7 @@ class PhixxyCom(commands.Cog):
await self.upload_sftp(html_file, server_folder, "index.html") await self.upload_sftp(html_file, server_folder, "index.html")
os.rename(filepath, f"tmp/{new_filename}") os.rename(filepath, f"tmp/{new_filename}")
except: 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"): async def answer_question(self, topic, model="gpt-3.5-turbo"):
headers = { headers = {
@ -257,11 +259,11 @@ class PhixxyCom(commands.Cog):
with open(blogpost_file, 'w') as f: with open(blogpost_file, 'w') as f:
f.write(blogpost_topics) f.write(blogpost_topics)
if topic != '': if topic != '':
self.bot.logger.info("Writing blogpost") self.logger.info("Writing blogpost")
else: else:
messages = self.get_last_5_messages() 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" 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) topic = await self.answer_question(question)
post_div = '''<!--replace this with a post--> post_div = '''<!--replace this with a post-->
<div class="post"> <div class="post">
@ -290,7 +292,7 @@ class PhixxyCom(commands.Cog):
f.write(html_data) f.write(html_data)
await self.upload_sftp(filename, (os.getenv('ftp_public_html') + 'ai-blog/'), "index.html") await self.upload_sftp(filename, (os.getenv('ftp_public_html') + 'ai-blog/'), "index.html")
run_time = time.time() - start_time 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" output = "Blog Updated! (" + str(run_time) + " seconds) https://ai.phixxy.com/ai-blog"
return output return output
@ -337,7 +339,7 @@ class PhixxyCom(commands.Cog):
await ctx.send("Finished https://ai.phixxy.com/ai-webpage/") await ctx.send("Finished https://ai.phixxy.com/ai-webpage/")
except Exception as error: except Exception as error:
#await ctx.send("Failed, Try again.") #await ctx.send("Failed, Try again.")
self.bot.logger.exception("Website Error") self.logger.exception("Website Error")
@tasks.loop(seconds=60) @tasks.loop(seconds=60)
async def phixxy_loop(self): async def phixxy_loop(self):
@ -359,7 +361,7 @@ class PhixxyCom(commands.Cog):
if message: if message:
await bot_stuff_channel.send(message) await bot_stuff_channel.send(message)
except Exception as error: except Exception as error:
self.bot.logger.exception("Failed to generate blog") self.logger.exception("Failed to generate blog")
@commands.command( @commands.command(
description="Moderate", description="Moderate",

View file

@ -1,3 +1,4 @@
import logging
import aiohttp import aiohttp
from discord.ext import commands from discord.ext import commands
import discord import discord
@ -69,7 +70,7 @@ class Pokedex(commands.Cog):
embed.set_footer(text=footer) embed.set_footer(text=footer)
await ctx.send(embed=embed) await ctx.send(embed=embed)
except: except:
self.bot.logger.exception("Something went wrong in pokedex") self.logger.exception("Something went wrong in pokedex")
message = "No data for " + str(pokemon) message = "No data for " + str(pokemon)
await ctx.channel.send(message) await ctx.channel.send(message)

View file

@ -1,4 +1,5 @@
import random import random
import logging
import os import os
import json import json
import math import math
@ -16,6 +17,7 @@ class PokemonGame(commands.Cog):
self.data_dir = "data/pokemon/" self.data_dir = "data/pokemon/"
self.folder_setup() self.folder_setup()
self.http_session = self.create_aiohttp_session() self.http_session = self.create_aiohttp_session()
self.logger = logging.getLogger("bot")
def create_aiohttp_session(self): def create_aiohttp_session(self):
return aiohttp.ClientSession() return aiohttp.ClientSession()
@ -32,7 +34,7 @@ class PokemonGame(commands.Cog):
if not os.path.exists(self.data_dir): if not os.path.exists(self.data_dir):
os.mkdir(self.data_dir) os.mkdir(self.data_dir)
except: 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 async def starter_picker(self, id): #id = pokedex number
url = "https://pokeapi.co/api/v2/pokemon-species/" + str(id) url = "https://pokeapi.co/api/v2/pokemon-species/" + str(id)

View file

@ -1,6 +1,6 @@
# Extension for sparkytron 3000
# This extension enables the ability to generate AI artwork using the AUTOMATIC1111 API # This extension enables the ability to generate AI artwork using the AUTOMATIC1111 API
import io import io
import logging
import base64 import base64
import os import os
import time import time
@ -21,6 +21,7 @@ class StableDiffusion(commands.Cog):
self.default_neg_prompt = "easynegative, badhandv4, verybadimagenegative_v1.3" self.default_neg_prompt = "easynegative, badhandv4, verybadimagenegative_v1.3"
self.folder_setup() self.folder_setup()
self.http_session = self.create_aiohttp_session() self.http_session = self.create_aiohttp_session()
self.logger = logging.getLogger("bot")
def create_aiohttp_session(self): def create_aiohttp_session(self):
return aiohttp.ClientSession() return aiohttp.ClientSession()
@ -34,7 +35,7 @@ class StableDiffusion(commands.Cog):
if not os.path.exists(self.data_dir): if not os.path.exists(self.data_dir):
os.mkdir(self.data_dir) os.mkdir(self.data_dir)
except: 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. 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" return "Stable Diffusion is disabled, could not look at image"
for attachment in ctx.attachments: for attachment in ctx.attachments:
if attachment.url.endswith(('.jpg', '.png')): 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: async with self.http_session.get(attachment.url) as response:
imageName = self.working_dir + str(time.time_ns()) + '.png' imageName = self.working_dir + str(time.time_ns()) + '.png'
with open(imageName, 'wb') as out_file: with open(imageName, 'wb') as out_file:
self.bot.logger.debug('Saving image: ' + imageName) self.logger.debug('Saving image: ' + imageName)
while True: while True:
chunk = await response.content.read(1024) chunk = await response.content.read(1024)
if not chunk: if not chunk:
@ -175,7 +176,7 @@ class StableDiffusion(commands.Cog):
description = description.split(',')[0] description = description.split(',')[0]
metadata += f"<image:{description}>\n" metadata += f"<image:{description}>\n"
except aiohttp.ClientError: 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 "ERROR: CLIP may not be running. Could not look at image."
return metadata return metadata
@ -281,7 +282,7 @@ class StableDiffusion(commands.Cog):
file_url = ctx.message.content.split(" ", maxsplit=1)[1] file_url = ctx.message.content.split(" ", maxsplit=1)[1]
return file_url return file_url
except: except:
self.bot.logger.info("Couldn't find image.") self.logger.info("Couldn't find image.")
return None return None
""" """
@ -309,16 +310,16 @@ class StableDiffusion(commands.Cog):
async with self.http_session.post(url, headers=headers, json=payload) as resp: async with self.http_session.post(url, headers=headers, json=payload) as resp:
if resp.status != 200: if resp.status != 200:
await ctx.send(f"{resp.status} {resp.reason}") 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 return
r = await resp.json() r = await resp.json()
except ConnectionRefusedError: except ConnectionRefusedError:
await ctx.send("Failed to connect to image generation service") 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 return
except: except:
await ctx.send("Failed to generate image") await ctx.send("Failed to generate image")
self.bot.logger.exception("Failed to generate image") self.logger.exception("Failed to generate image")
return return
await self.send_generated_image(ctx, r['images'], prompt) 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: async with self.http_session.get(url) as response:
image_name = self.working_dir + str(time.time_ns()) + ".png" image_name = self.working_dir + str(time.time_ns()) + ".png"
with open(image_name, 'wb') as out_file: 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: while True:
chunk = await response.content.read(1024) chunk = await response.content.read(1024)
if not chunk: if not chunk:
@ -379,16 +380,16 @@ class StableDiffusion(commands.Cog):
async with self.http_session.post(url, headers=headers, json=payload) as resp: async with self.http_session.post(url, headers=headers, json=payload) as resp:
if resp.status != 200: if resp.status != 200:
await ctx.send(f"{resp.status} {resp.reason}") 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 return
r = await resp.json() r = await resp.json()
except ConnectionRefusedError: except ConnectionRefusedError:
await ctx.send("Failed to connect to image generation service") 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 return
except: except:
await ctx.send("Failed to generate image") await ctx.send("Failed to generate image")
self.bot.logger.exception("Failed to generate image") self.logger.exception("Failed to generate image")
return return
await self.send_generated_image(ctx, r['images'], prompt) await self.send_generated_image(ctx, r['images'], prompt)
@ -493,7 +494,7 @@ class StableDiffusion(commands.Cog):
r = await response.json() r = await response.json()
await ctx.send(r.get("caption")) await ctx.send(r.get("caption"))
except: 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.") await ctx.send("My image generation service may not be running.")
@commands.command( @commands.command(

View file

@ -1,5 +1,6 @@
import time import time
import os import os
import logging
import aiohttp import aiohttp
import discord import discord
from discord.ext import commands from discord.ext import commands
@ -12,6 +13,7 @@ class TextToSpeech(commands.Cog):
self.data_dir = "data/tts/" self.data_dir = "data/tts/"
self.folder_setup() self.folder_setup()
self.http_session = self.create_aiohttp_session() self.http_session = self.create_aiohttp_session()
self.logger = logging.getLogger("bot")
def create_aiohttp_session(self): def create_aiohttp_session(self):
return aiohttp.ClientSession() return aiohttp.ClientSession()
@ -23,7 +25,7 @@ class TextToSpeech(commands.Cog):
if not os.path.exists(self.data_dir): if not os.path.exists(self.data_dir):
os.mkdir(self.data_dir) os.mkdir(self.data_dir)
except: 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): async def text_to_speech(self, prompt):
CHUNK_SIZE = 1024 CHUNK_SIZE = 1024
@ -98,7 +100,7 @@ class TextToSpeech(commands.Cog):
await ctx.send(file=discord.File(filepath)) await ctx.send(file=discord.File(filepath))
except: except:
await ctx.send("Error in tts") await ctx.send("Error in tts")
self.bot.logger.exception("Error in tts") self.logger.exception("Error in tts")
@commands.command() @commands.command()
async def opentts(self, ctx): async def opentts(self, ctx):
@ -113,7 +115,7 @@ class TextToSpeech(commands.Cog):
await ctx.send(file=discord.File(filepath)) await ctx.send(file=discord.File(filepath))
except: except:
await ctx.send("Error in tts") await ctx.send("Error in tts")
self.bot.logger.exception("Error in tts") self.logger.exception("Error in tts")
async def setup(bot): async def setup(bot):
await bot.add_cog(TextToSpeech(bot)) await bot.add_cog(TextToSpeech(bot))

View file

@ -2,22 +2,23 @@ import os
import discord import discord
from discord.ext import commands from discord.ext import commands
from dotenv import load_dotenv from dotenv import load_dotenv
import src.logger as logger import src.logger
import src.utils as utils import src.utils as utils
intents = discord.Intents.all() intents = discord.Intents.all()
intents.message_content = True intents.message_content = True
bot = commands.Bot(command_prefix='!', intents=intents) 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: async def load_cogs(bot: commands.Bot, cog_path: str) -> None:
for plugin_file in os.listdir(cog_path): for plugin_file in os.listdir(cog_path):
if plugin_file[-3:] == '.py': if plugin_file[-3:] == '.py':
try: try:
await bot.load_extension(f'extensions.{plugin_file[:-3]}') 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: except:
bot.logger.exception(f"Failed to load plugin {plugin_file}") logger.exception(f"Failed to load plugin {plugin_file}")
@bot.event @bot.event
async def on_ready(): async def on_ready():
@ -25,17 +26,17 @@ async def on_ready():
await utils.delete_all_files("tmp/") await utils.delete_all_files("tmp/")
await utils.folder_setup() await utils.folder_setup()
await load_cogs(bot, 'extensions/') 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: except:
bot.logger.warning(f"Error in on_ready") logger.warning(f"Error in on_ready")
@bot.event @bot.event
async def on_message(ctx): async def on_message(ctx):
try: try:
await bot.process_commands(ctx) await bot.process_commands(ctx)
except commands.CommandNotFound: except commands.CommandNotFound:
bot.logger.info("Command not found.") logger.info("Command not found.")
except discord.ext.commands.errors.CommandNotFound: except discord.ext.commands.errors.CommandNotFound:
bot.logger.info("Command not found.") logger.info("Command not found.")
except Exception as e: except Exception as e:
bot.logger.warning(f"Error processing commands: {e}") logger.warning(f"Error processing commands: {e}")