#How would I go about adding a group of commands that do almost the same thing to a cog?
1 messages · Page 1 of 1 (latest)
I don't have a lot of time rn but I will post some examples of what i am talking about with my code
Because of the way extensions (cogs) are loaded from files, I believe you would have to actually create the my_cog.py file progamatically and then load it into your bot. Maybe someone else can correct me if I'm wrong here
I do have a separate cog file but it still won't put the commands under it
Oh, are you talking about writing code to write the code for the commands?
That might work but sounds a bit messy
ok so the code i currently have is:
import asyncio
from typing import Union
import discord
import random
from discord.ext import commands, bridge
import config
import utils
class Actions(config.RevnobotCog):
def __init__(self, client: bridge.Bot):
self.description = "do actions"
self.icon = "\U0001FA84"
self.hidden = False
self.client = client
self.actions_dir = "./media/images/actions/"
self.actions_data = {
"hug": ["hugged", 'Hug a user', ['cuddle']],
"kill": ["killed", "oof!", []],
"kiss": ["kissed", "😳", []],
"lick": ["licked", "ahh, gross", []],
"pat": ["patted", "pat pat", []],
"punch": ["punched", "ou-oof!", []],
"slap": ["slapped", "ouch!", []]
}
for key, value in self.actions_data.items():
cmd = commands.Command(name=key, func=self.base_command, description=value[1],
aliases=value[2])
self.client.add_command(cmd)
self.client.application_command(name=key, cls=discord.SlashCommand, description=value[1])(self.base_command)
@commands.bot_has_permissions(send_messages=True, attach_files=True)
@commands.cooldown(**config.default_cooldown_options)
async def base_command(self, ctx: Union[discord.ApplicationContext, commands.Context], member: discord.Member):
action_name = ctx.command.qualified_name
action_name_ext = self.actions_data[ctx.command.qualified_name][0]
loop = asyncio.get_event_loop()
number_of_10 = await loop.run_in_executor(None, lambda: random.randint(1, 10))
filename = f'{action_name}gif{number_of_10}.gif'
file = discord.File(f'{self.actions_dir}{action_name}/{filename}')
embed = utils.default_embed(ctx, f'{action_name_ext} {member}', f'**{ctx.author.mention}** {action_name_ext} '
f'**{member.mention}**')
embed.set_image(url=f'attachment://{filename}')
await utils.send_type(ctx)(file=file, embed=embed)
def setup(client):
client.add_cog(Actions(client))
my help command uses the mapping provided by the help class
the actions cog is empty and all commands added are associated withought a cog
how would I got about adding all of these similar commands to the cog?
bot.load_extension('cogs.generalutility')
to load a cog called generalutility.py from the folder cogs(use this in your main/bot file)
in your cog file put this outside any classes:
bot.add_cog(ClassName(bot))```
and then in then in the init of the class:
```class ClassName(commands.Cog):
def __init__(self, bot):
self.bot = bot```
not sure if this is what you are looking for but 🤷♂️
hope you get some sleep then
not before i get my shit done, gotta find the balance between reliability and stuff being aesthetically pleasing
when you can of corse
anyway, I went with @fossil yoke 's Idea of automatically generating the file. but I might open an issue about a proper way to do this
I guess the function should not be decorated (base_command) as it makes it being registered as another command and not as a base function to all commands.
Also, as Colin said, make sure you load cogs in your setup_hook or in a command.
setup hook?
and do what excactly?
# using on_ready
import os
@client.event
async def on_ready():
for f in os.listdir("the/path/to/your/cogs"): # this line returns a list of all files in the directory
if f.endswith(".py:): # checks if file is a python file
await client.load_extension('cogs.' + f[:-3]) # loads it as extensions
oh, load the cogs in the on_ready event instead of in main
Well, yes ig
is there any advantage to waiting until the bot is ready?
Well, you ensure the bot is woken when loading cogs
I probably should of posted this erlier but this is how my cogs are loaded:
# load in every cog in ./cogs directory
if __name__ == "__main__":
autogen_actions.build_actions() # this is my current solution
cogs_folder = list(os.listdir('./cogs'))
for filename in cogs_folder:
if filename.endswith('.py'):
# disable the debug cog if the bot is not executed with the "debug mode" parameter set to true in the
# config json file
if filename == "debug.py" and not config.debug_mode:
continue
# 2 methods are used to handle cog errors because the pycord devs keep changing how they work
try:
cog_status = client.load_extension(f'cogs.{filename[:-3]}')
except discord.ExtensionFailed as cog_err:
cog_error = cog_err
else:
if isinstance(cog_status, dict):
cog_error = cog_status.get(f'cogs.{filename[:-3]}')
else:
cog_error = None
if isinstance(cog_error, Exception):
if isinstance(cog_error, discord.ExtensionFailed):
if isinstance(cog_error.original, SyntaxError):
print(f"\aSyntax Error! Please check line {cog_error.original.lineno} from column "
f"{cog_error.original.offset} in "
f"{cog_error.original.filename}", file=sys.stderr)
with open(cog_error.original.filename) as error_file:
error_line = error_file.readlines()[cog_error.original.lineno-1]
print(f'{error_line}{" "*(cog_error.original.offset-1)}'
f'{"^"*(cog_error.original.end_offset-1-cog_error.original.offset-1)}',
file=sys.stderr)
exit(1)
else:
traceback_string = "\n".join(traceback.format_tb(cog_error.__traceback__))
if isinstance(cog_error, discord.ExtensionFailed):
traceback_string = "\n".join(traceback.format_tb(cog_error.original.__traceback__))
print(f'Oops, a cog raised an error:\n{type(cog_error.original).__name__}: '
f'{cog_error.original}\nTraceback:\n'
f'{traceback_string}', file=sys.stderr)
else:
traceback_string = "\n".join(traceback.format_tb(cog_error.__traceback__))
if isinstance(cog_error, discord.ExtensionFailed):
traceback_string = "\n".join(traceback.format_tb(cog_error.original.__traceback__))
print(f'Oops, a cog raised an error:\n{type(cog_error).__name__}: {cog_error}\nTraceback:\n'
f'{traceback_string}', file=sys.stderr)
eh no
load the cogs outside of any of the events
client = discord.Bot()
client.load_extension()
client.run()
load_load...
Dw, it was just a typo lol
ye
that is how I load my cogs ```py
client.load_extension("Cogs", recursive=True)
A simple oneliner x3
I also do it like that, it is the simplest way ik
solved?
I think so...
.close
Done with your help thread?
Please close your own help thread by using </close:1009144375709814897> with @daring mantle.
Backup bot: </solved:1109625445990793246> (or
.solved) with @random orbit.
@ripe grove
This thread was archived by a staff member.
Its a sketchy workaround. I've done further testing and still don't know why add_command wont register under the cog properly. I will have to open an issue if the library is still acepting issues?
Yes we still are!