duct tape fix for cogmanager and tested using the image module inside of a cog

This commit is contained in:
WhatDidYouExpect 2025-07-16 01:32:38 +02:00
parent 260b7e3360
commit 81b3abf287
3 changed files with 154 additions and 5 deletions

View file

@ -1,8 +1,9 @@
import discord import discord
from discord.ext import commands from discord.ext import commands
import os
from modules.globalvars import ownerid from modules.globalvars import ownerid
COG_PREFIX = "assets.cogs."
class CogManager(commands.Cog): class CogManager(commands.Cog):
def __init__(self, bot): def __init__(self, bot):
self.bot = bot self.bot = bot
@ -16,7 +17,7 @@ class CogManager(commands.Cog):
await ctx.send("Please provide the cog name to load.") await ctx.send("Please provide the cog name to load.")
return return
try: try:
await self.bot.load_extension(f"cogs.{cog_name}") await self.bot.load_extension(COG_PREFIX + cog_name)
await ctx.send(f"Loaded cog `{cog_name}` successfully.") await ctx.send(f"Loaded cog `{cog_name}` successfully.")
except Exception as e: except Exception as e:
await ctx.send(f"Error loading cog `{cog_name}`: {e}") await ctx.send(f"Error loading cog `{cog_name}`: {e}")
@ -30,7 +31,7 @@ class CogManager(commands.Cog):
await ctx.send("Please provide the cog name to unload.") await ctx.send("Please provide the cog name to unload.")
return return
try: try:
await self.bot.unload_extension(f"cogs.{cog_name}") await self.bot.unload_extension(COG_PREFIX + cog_name)
await ctx.send(f"Unloaded cog `{cog_name}` successfully.") await ctx.send(f"Unloaded cog `{cog_name}` successfully.")
except Exception as e: except Exception as e:
await ctx.send(f"Error unloading cog `{cog_name}`: {e}") await ctx.send(f"Error unloading cog `{cog_name}`: {e}")
@ -44,8 +45,8 @@ class CogManager(commands.Cog):
await ctx.send("Please provide the cog name to reload.") await ctx.send("Please provide the cog name to reload.")
return return
try: try:
await self.bot.unload_extension(f"cogs.{cog_name}") await self.bot.unload_extension(COG_PREFIX + cog_name)
await self.bot.load_extension(f"cogs.{cog_name}") await self.bot.load_extension(COG_PREFIX + cog_name)
await ctx.send(f"Reloaded cog `{cog_name}` successfully.") await ctx.send(f"Reloaded cog `{cog_name}` successfully.")
except Exception as e: except Exception as e:
await ctx.send(f"Error reloading cog `{cog_name}`: {e}") await ctx.send(f"Error reloading cog `{cog_name}`: {e}")

97
assets/cogs/fuckup.py Normal file
View file

@ -0,0 +1,97 @@
import discord
from discord.ext import commands
from modules.image import *
from PIL import Image, ImageEnhance, ImageFilter, ImageOps, ImageChops, ImageColor
import os, random, shutil, tempfile
async def deepfryimage(path):
with Image.open(path).convert("RGB") as im:
# make it burn
for _ in range(3):
im = im.resize((int(im.width * 0.7), int(im.height * 0.7)))
im = im.resize((int(im.width * 1.5), int(im.height * 1.5)))
im = ImageEnhance.Contrast(im).enhance(random.uniform(5, 10))
im = ImageEnhance.Sharpness(im).enhance(random.uniform(10, 50))
im = ImageEnhance.Brightness(im).enhance(random.uniform(1.5, 3))
r, g, b = im.split()
r = r.point(lambda i: min(255, i * random.uniform(1.2, 2.0)))
g = g.point(lambda i: min(255, i * random.uniform(0.5, 1.5)))
b = b.point(lambda i: min(255, i * random.uniform(0.5, 2.0)))
channels = [r, g, b]
random.shuffle(channels)
im = Image.merge("RGB", tuple(channels))
overlay_color = tuple(random.randint(0, 255) for _ in range(3))
overlay = Image.new("RGB", im.size, overlay_color)
im = ImageChops.add(im, overlay, scale=2.0, offset=random.randint(-64, 64))
im = im.filter(ImageFilter.EDGE_ENHANCE_MORE)
im = im.filter(ImageFilter.GaussianBlur(radius=random.uniform(0.5, 2)))
for _ in range(3):
tmp_path = tempfile.mktemp(suffix=".jpg")
im.save(tmp_path, format="JPEG", quality=random.randint(5, 15))
im = Image.open(tmp_path)
if random.random() < 0.3:
im = ImageOps.posterize(im, bits=random.choice([2, 3, 4]))
if random.random() < 0.2:
im = ImageOps.invert(im)
out_path = tempfile.mktemp(suffix=".jpg")
im.save(out_path, format="JPEG", quality=5)
return out_path
class whami(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
async def fuckup(self, ctx):
assets_folder = "assets/images"
temp_input = None
def get_random_asset_image():
files = [f for f in os.listdir(assets_folder) if f.lower().endswith(('.png', '.jpg', '.jpeg', '.webp'))]
if not files:
return None
return os.path.join(assets_folder, random.choice(files))
if ctx.message.attachments:
attachment = ctx.message.attachments[0]
if attachment.content_type and attachment.content_type.startswith("image/"):
ext = os.path.splitext(attachment.filename)[1]
temp_input = f"tempy{ext}"
await attachment.save(temp_input)
input_path = temp_input
else:
fallback_image = get_random_asset_image()
if fallback_image is None:
await ctx.reply(_('no_image_available'))
return
temp_input = tempfile.mktemp(suffix=os.path.splitext(fallback_image)[1])
shutil.copy(fallback_image, temp_input)
input_path = temp_input
else:
fallback_image = get_random_asset_image()
if fallback_image is None:
await ctx.reply(_('no_image_available'))
return
temp_input = tempfile.mktemp(suffix=os.path.splitext(fallback_image)[1])
shutil.copy(fallback_image, temp_input)
input_path = temp_input
output_path = await gen_meme(input_path)
if output_path is None or not os.path.isfile(output_path):
if temp_input and os.path.exists(temp_input):
os.remove(temp_input)
await ctx.reply(_('failed_generate_image'))
return
deepfried_path = await deepfryimage(output_path)
await ctx.send(file=discord.File(deepfried_path))
if temp_input and os.path.exists(temp_input):
os.remove(temp_input)
async def setup(bot):
await bot.add_cog(whami(bot))

51
modules/coghooks.py Normal file
View file

@ -0,0 +1,51 @@
import os
import importlib
import inspect
import sys
_hooks = {}
def register_hook(name, func):
if name not in _hooks:
_hooks[name] = []
_hooks[name].append(func)
async def call_hook(name, *args, **kwargs):
if name not in _hooks:
return
for func in _hooks[name]:
if callable(func):
if inspect.iscoroutinefunction(func):
await func(*args, **kwargs)
else:
func(*args, **kwargs)
def register_all_functions_as_hooks(module):
"""Register every function/coroutine function in the given module as a hook under its function name."""
for name, obj in inspect.getmembers(module):
if inspect.isfunction(obj) or inspect.iscoroutinefunction(obj):
register_hook(name, obj)
def _register_all_modules_functions():
"""Scan all python modules in this 'modules' folder (excluding this file) and register their functions."""
# Calculate the path to the modules directory relative to this file
modules_dir = os.path.dirname(os.path.abspath(__file__))
# Current file name so we skip it
current_file = os.path.basename(__file__)
# Ensure 'modules' is in sys.path for importlib to work
if modules_dir not in sys.path:
sys.path.insert(0, modules_dir)
# List all python files except dunder files and this file
for filename in os.listdir(modules_dir):
if filename.endswith(".py") and not filename.startswith("__") and filename != current_file:
module_name = filename[:-3] # strip .py extension
try:
module = importlib.import_module(module_name)
register_all_functions_as_hooks(module)
except Exception as e:
print(f"[hooks] Failed to import {module_name}: {e}")