Using os.walk to create discord.py cog names

37 views Asked by At

I'm trying to automate my discord.py bot's scan and intake of cogs as extentions using os.walk and I'd like to understand why checking for cogs after the bot is live says none are loaded. I'm a little new to python and learning as I go so please forgive any times I need an answer expanding on.

This is the portion of the script that is responsible for the operation

### COGS ###
@bot.event
async def setup_hook():
    for dirs in next(os.walk('.'))[1]:
        for i in range(len(dirs)):
            if dirs[i].startswith("."):
                for file in os.listdir(''.join(dirs[i])):
                    if file.endswith(".py"):
                        await bot.load_extension(f"{dirs[i]}.{file[:-3]}")
    print('Cogs should be done now.')

As I understood it, taking the second part of os.walk would return the folder names in the same directory as the .py script running it, so next(os.walk('.'))[1] was meant to populate a list dirs with the folders present in the root folder. I hoped that I could basically do a for loop on those folders and get the names of the python files and append the folder and python script names to each other with (f"{dirs[i]}.{file[:-3]}") to create the dot qualified names of them.

edit: I was trying to get every extension in a given folder, but they're organised further into folders. So while I want it to be a case of /src/cogs/allthecogs.py I actually have src/coggroup1/type1cogshere.py and src/coggroup2/type2cogshere.py

I've since relegated them to camelCased names in one folder and I'm just running this:

for file in os.listdir("cogs"):
    if file.endswith(".py"):
        await bot.load_extension(f"cogs.{file[:-3]}")

Admittedly, there are now new problems, but I think I was overdoing it to make it human readable at the cost of more work.

0

There are 0 answers