Add: BaseCog, PostCommand and ReloadCommand
Reused BaseCog and PostCommand from old codebase Used ReloadCommand by Apollo: https://github.com/official-Cromatin/Apollo/blob/3fe5972653da3d858e2601c126bacd244c803ccc/src/cogs/reload.py
This commit is contained in:
@@ -0,0 +1,15 @@
|
||||
"""Contains the BaseCog"""
|
||||
|
||||
from discord.ext import commands
|
||||
import logging
|
||||
|
||||
class BaseCog(commands.Cog):
|
||||
def __init__(self, bot:commands.Bot, logger:logging.Logger):
|
||||
self._bot = bot
|
||||
self._logger = logger
|
||||
|
||||
async def cog_load(self):
|
||||
self._logger.debug(f"Cog for the '{self.__class__.__name__}' command got loaded")
|
||||
|
||||
async def cog_unload(self):
|
||||
self._logger.debug(f"Cog for the '{self.__class__.__name__}' command got unloaded")
|
||||
@@ -0,0 +1,28 @@
|
||||
"""Contains the implementation for the /post command"""
|
||||
|
||||
from .base import BaseCog
|
||||
import logging
|
||||
from discord import app_commands, Interaction
|
||||
from discord.ext import commands
|
||||
|
||||
class PostCommand(BaseCog):
|
||||
def __init__(self, bot):
|
||||
logger = logging.getLogger("cmds.post")
|
||||
super().__init__(bot, logger)
|
||||
|
||||
@app_commands.command(name = "post", description = "Post an embed in the Current Channel with a link to the content")
|
||||
@app_commands.describe(url = "URL to the post", custom_note = "Describe the post with your own note", use_title = "Display the title of the post", quality = "Specifies the quality of the converted image, closer to 100 is better")
|
||||
@app_commands.choices(quality = [
|
||||
app_commands.Choice(name = "Poor (60)", value = 60),
|
||||
app_commands.Choice(name = "Fair (70)", value = 70),
|
||||
app_commands.Choice(name = "Good (80)", value = 80),
|
||||
app_commands.Choice(name = "Very Good (85)", value = 85),
|
||||
app_commands.Choice(name = "Excellent (90)", value = 90),
|
||||
app_commands.Choice(name = "Superior (95)", value = 95),
|
||||
app_commands.Choice(name = "Perfect (100)", value = 100)
|
||||
])
|
||||
async def post(self, ctx:Interaction, url:str, custom_note:str = None, use_title:bool = True, quality:app_commands.Choice[int] = 95):
|
||||
print("Hallo")
|
||||
|
||||
async def setup(bot:commands.Bot):
|
||||
await bot.add_cog(PostCommand(bot))
|
||||
@@ -0,0 +1,113 @@
|
||||
import discord
|
||||
from discord import app_commands
|
||||
from discord.ext import commands
|
||||
from .base import BaseCog
|
||||
|
||||
import logging
|
||||
from datetime import datetime
|
||||
from utils.datetime_tools import get_elapsed_time_milliseconds
|
||||
|
||||
class ReloadCommand(BaseCog):
|
||||
def __init__(self, bot:commands.Bot):
|
||||
self.__bot = bot
|
||||
self.__cached_cog_names:list[str] = None
|
||||
self.__reload_running = False
|
||||
super().__init__(bot, logging.getLogger("cmds.reload"))
|
||||
|
||||
async def autocomplete_cog(self, ctx: discord.Interaction, cog_name_stw:str):
|
||||
"""Helpermethod to recommend the right cog name to the user"""
|
||||
# Cache the cog names if not cached yet
|
||||
if not self.__cached_cog_names:
|
||||
self.__cached_cog_names = list(self.__bot.extensions.keys())
|
||||
|
||||
if cog_name_stw == "":
|
||||
# Return first 25 cog names, if provided name is empty
|
||||
matching_cogs = sorted(self.__cached_cog_names)
|
||||
else:
|
||||
matching_cogs = []
|
||||
for cog_name in self.__cached_cog_names:
|
||||
if cog_name.startswith(cog_name_stw.lower()):
|
||||
matching_cogs.append(cog_name)
|
||||
|
||||
choices = []
|
||||
for matching_cog in matching_cogs[:25]:
|
||||
choices.append(app_commands.Choice(name = matching_cog.removeprefix("cogs.").capitalize(), value = matching_cog))
|
||||
|
||||
return choices
|
||||
|
||||
@app_commands.command(name = "reload_all", description = "Reloads all cogs")
|
||||
async def reload_all(self, ctx: discord.Interaction):
|
||||
if self.__reload_running:
|
||||
await ctx.response.send_message("Reload is allready being executed", ephemeral = True)
|
||||
else:
|
||||
self.__reload_running = True
|
||||
task_start = datetime.now().timestamp()
|
||||
cog_names = list(self.__bot.extensions.keys())
|
||||
stepped_over = 0
|
||||
self._logger.debug(f"Reloading all {len(cog_names)} cogs / extensions ...")
|
||||
try:
|
||||
embed_cog_stats = "Reloaded the following cogs:\n"
|
||||
for extension_name in cog_names:
|
||||
if "impls" in extension_name:
|
||||
stepped_over += 1
|
||||
else:
|
||||
start_reload = datetime.now().timestamp()
|
||||
await self.__bot.reload_extension(extension_name)
|
||||
embed_cog_stats += f"- {extension_name.removeprefix('cogs.').capitalize()} (`{get_elapsed_time_milliseconds(datetime.now().timestamp() - start_reload)}`)\n"
|
||||
|
||||
except Exception as error:
|
||||
embed_cog_stats += f"- {extension_name.removeprefix('cogs.').capitalize()} <--"
|
||||
|
||||
embed = discord.Embed(
|
||||
title = "Reloading All Cogs",
|
||||
description = f"{embed_cog_stats} \n\nDuring the reload an exception occured",
|
||||
color = 0xED4337)
|
||||
|
||||
raise error
|
||||
else:
|
||||
elapsed_time = get_elapsed_time_milliseconds(datetime.now().timestamp() - task_start)
|
||||
embed = discord.Embed(
|
||||
title = "Reloading All Cogs",
|
||||
description = f"{embed_cog_stats}Total time spend: `{elapsed_time}`",
|
||||
color = 0x4BB543)
|
||||
|
||||
self._logger.info(f"Cogs successfully reloaded after {elapsed_time} (Ignored )")
|
||||
finally:
|
||||
await ctx.response.send_message(embed = embed, ephemeral = True)
|
||||
self.__reload_running = False
|
||||
|
||||
|
||||
@app_commands.command(name = "reload", description = "Reload specific cog")
|
||||
@app_commands.autocomplete(cog_name = autocomplete_cog)
|
||||
async def reload(self, ctx: discord.Interaction, cog_name:str):
|
||||
if self.__reload_running:
|
||||
await ctx.response.send_message("Reload is allready being executed", ephemeral = True)
|
||||
else:
|
||||
self.__reload_running = True
|
||||
task_start = datetime.now().timestamp()
|
||||
self._logger.debug(f"Reloading {cog_name} cog ...")
|
||||
try:
|
||||
await self.__bot.reload_extension(cog_name)
|
||||
except Exception as error:
|
||||
embed = discord.Embed(
|
||||
title = f"Reloading `{cog_name.removeprefix('cogs.').capitalize()}` cog",
|
||||
description = "Reload failed with an exception",
|
||||
color = 0xED4337)
|
||||
|
||||
raise error
|
||||
else:
|
||||
embed = discord.Embed(
|
||||
title = f"Reloading `{cog_name.removeprefix('cogs.').capitalize()}` cog",
|
||||
description = f"Total time spend: `{get_elapsed_time_milliseconds(datetime.now().timestamp() - task_start)}`",
|
||||
color = 0x4BB543)
|
||||
|
||||
self._logger.info(f"Cog {cog_name} successfully reloaded after {get_elapsed_time_milliseconds(datetime.now().timestamp() - task_start)}")
|
||||
finally:
|
||||
await ctx.response.send_message(embed = embed, ephemeral = True)
|
||||
self.__reload_running = False
|
||||
|
||||
# Clear the cache
|
||||
self.__cached_cog_names = None
|
||||
|
||||
async def setup(bot:commands.Bot):
|
||||
await bot.add_cog(ReloadCommand(bot))
|
||||
Reference in New Issue
Block a user