Home > OS >  How can I fix not working cogs in discord.py
How can I fix not working cogs in discord.py

Time:01-02

I wanted to create cogs but they don't work as they should. I don't really know what to do. And when turning on the bot, there is no log message about loading the ping cog.

When typing the command:

ERROR    discord.ext.commands.bot Ignoring exception in command None
discord.ext.commands.errors.CommandNotFound: Command "ping" is not found

main.py:

import discord
from discord.ext import commands
from discord import app_commands
from webserver import keep_alive
import os

intents = discord.Intents.all()

client = commands.Bot(command_prefix = ".",intents=intents)

@client.event
async def on_ready():
    await client.change_presence(activity=discord.Game('bot online'))
    print ("Bot is currently online!")

async def load():
  for filename in os.listdir('./cogs'):
    if filename.endswith('.py'):
        await client.load_extension(f'cogs.{filename[:-3]}')
        print(f"Loaded Cog: {filename[:-3]}")
    else:
        print("Unable to load pycache folder.")

keep_alive()
token = os.environ.get("discord_bot_secret")
client.run(token)

cogs/ping.py:

import discord
from discord.ext import commands

class ping(commands.Cog):
    def __init__(self, client):
        self.client = client

    @commands.command()
    async def ping(self, ctx):
        await ctx.send('Pong!')

def setup(client):
    client.add_cog(ping(client))

I tried delete async def load(): and await before client.load_extension(f'cogs.{filename[:-3]}') but it didn't work and I got an error:

main.py:18: RuntimeWarning: coroutine 'BotBase.load_extension' was never awaited
  client.load_extension(f'cogs.{filename[:-3]}')
RuntimeWarning: Enable tracemalloc to get the object allocation traceback

And I don't know why but, after deleting it, there was a message log about loading the ping cog.

CodePudding user response:

After the discord.py 2.0 update, loading extensions and adding cogs are now asynchronous, meaning that the load_extension and add_cog methods are now returning a coroutine that you need to call them using the await statement (async function), and the setup function in your extension file also needs to be an async function. I highly recommend you load the cogs in the new method setup_hook, example:

Somewhere in main.py

@client.event
async def setup_hook():
  for filename in os.listdir('./cogs'):
    if filename.endswith('.py'):
        await client.load_extension(f'cogs.{filename[:-3]}')
        print(f"Loaded Cog: {filename[:-3]}")
    else:
        print("Unable to load pycache folder.")

Setup function in cogs/ping.py

async def setup(client):
    await client.add_cog(ping(client))

See discord.py Extension and Cog Loading / Unloading is Now Asynchronous

  • Related