Cogs loads but won't work in discord.py 2.0

Question:

I’ve provided code of two files. bot.py – runs bot, ping.py – cog file.
The problem is that Cog doesn’t work, bot doesn’t respond to commands, in my ping.py file i have ping command

bot.py

import discord as ds
import asyncio
import os
from dotenv import load_dotenv
from discord.ext import commands

load_dotenv()

intents = ds.Intents.all()
intents.message_content = True
    
bot = commands.Bot(command_prefix='!', intents=intents)

@bot.event
async def on_message(message):
    if message.author == bot.user:
        return
    username = str(message.author)
    user_message = str(message.content)
    channel = str(message.channel)

    print(f"{username} said: '{user_message}' ({channel})")

async def load_cogs():
    for filename in os.listdir('./cogs'):
        if filename.endswith('.py'):
            await bot.load_extension(f'cogs.{filename[:-3]}')

@bot.event
async def on_ready():
    print(f'{bot.user} is now running.')

async def main():
    await load_cogs()
    async with bot:
        TOKEN = os.getenv('TOKEN')
        await bot.start(TOKEN)

asyncio.run(main())

ping.py

import discord
from discord.ext import commands
import asyncio

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

    @commands.command(name="ping", description="Returns Pong!")
    async def ping(self, ctx):
        await ctx.send("Pong!")        

async def setup(bot: commands.Bot):
    await bot.add_cog(ping(bot))

After running bot display 0 errors. I tried to changing intents from default() to all() but it didn’t help.

Asked By: curious man

||

Answers:

You override the on_message event, and you don’t have a process_commands in it, so the bot won’t be processing any commands.

You can fix this by adding bot.process_commands inside the event.

@bot.event
async def on_message(message):
    ...
    await bot.process_commands(message)

Or register it as a listener so it doesn’t override the default event.

@bot.listen()
async def on_message(message):
    ...
Answered By: Catgal
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.