You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python开发Discord Bot遇AttributeError:commands.cog无listener属性

Discord机器人开发AttributeError问题解决

问题现象

开发Discord机器人时触发以下错误:

AttributeError: module 'discord.ext.commands.cog' has no attribute 'listener'

原代码

Cog文件(ping.py)

import discord
from discord.ext import commands
from discord import Member

class ping(commands.cog):
    def __init__(self, client):
        self.client = client
        self._last_member = None

    @commands.cog.listener()
    async def on_ready(self):
        print("Ping.py is ready")

    @commands.command()
    async def ping(self, ctx, member:discord.Member):
        bot_latency = round(self.client.latency * 1000)
        member = member or ctx.author
        await ctx.send(f"Pong! {bot_latency}ms {member.mention}")

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

主文件(main.py)

import discord
from discord.ext import commands
import os
import asyncio

client = commands.Bot(description="Discord Bot", command_prefix="!", intents = discord.Intents.all())

@client.event
async def on_ready():
    print("The bot is ready for testing!")
    print("-----------------------------")

async def load():
    for filename in os.listdir("./cogs"):
        if filename.endswith(".py"):
            await client.load_extension(f"cogs.{filename[:-3]}")
            print(f"{filename[:-3]} is loaded!")

async def main():
    async with client:
        await load()
        await client.start('BOTTOKEN')

asyncio.run(main())

完整报错信息

Traceback (most recent call last):
  File "C:\Users\user\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\ext\commands\bot.py", line 935, in _load_from_module_spec
    spec.loader.exec_module(lib)  # type: ignore
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "<frozen importlib._bootstrap_external>", line 995, in exec_module
  File "<frozen importlib._bootstrap>", line 488, in _call_with_frames_removed
  File "c:\Users\user\vsPythonWorkspace\cogs\ping.py", line 5, in <module>
    class ping(commands.cog):
  File "c:\Users\user\vsPythonWorkspace\cogs\ping.py", line 10, in ping
    @commands.cog.listener()
     ^^^^^^^^^^^^^^^^^^^^^
AttributeError: module 'discord.ext.commands.cog' has no attribute 'listener'

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "c:\Users\user\vsPythonWorkspace\main.py", line 25, in <module>
    asyncio.run(main())
  File "C:\Users\user\AppData\Local\Programs\Python\Python312\Lib\asyncio\runners.py", line 194, in run
    return runner.run(main)
           ^^^^^^^^^^^^^^^^
  File "C:\Users\user\AppData\Local\Programs\Python\Python312\Lib\asyncio\runners.py", line 118, in run
    return self._loop.run_until_complete(task)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\user\AppData\Local\Programs\Python\Python312\Lib\asyncio\base_events.py", line 687, in run_until_complete
    return future.result()
           ^^^^^^^^^^^^^^^
  File "c:\Users\user\vsPythonWorkspace\main.py", line 22, in main
    await load()
  File "c:\Users\user\vsPythonWorkspace\main.py", line 17, in load
    await client.load_extension(f"cogs.{filename[:-3]}")
  File "C:\Users\user\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\ext\commands\bot.py", line 1013, in load_extension
    await self._load_from_module_spec(spec, name)
  File "C:\Users\user\AppData\Local\Programs\Python\Python312\Lib\site-packages\discord\ext\commands\bot.py", line 938, in _load_from_module_spec
    raise errors.ExtensionFailed(key, e) from e
 discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.ping' raised an error: AttributeError: module 'discord.ext.commands.cog' has no attribute 'listener'

解决方案

核心错误:大小写误用

discord.py中,Cog类和对应的listener装饰器均为大写C开头,代码里误用小写commands.cog导致无法找到正确属性,需修改两处:

  1. 类继承:将class ping(commands.cog):改为class ping(commands.Cog):
  2. 监听器装饰器:将@commands.cog.listener()改为@commands.Cog.listener()

额外修复:ping命令参数默认值

当前ping命令的member:discord.Member无默认值,直接调用!ping会触发参数缺失错误,需添加默认值并导入Optional类型提示:

修正后的Cog文件代码

import discord
from discord.ext import commands
from typing import Optional  # 新增导入

class ping(commands.Cog):  # 修正大写Cog
    def __init__(self, client):
        self.client = client
        self._last_member = None

    @commands.Cog.listener()  # 修正大写Cog
    async def on_ready(self):
        print("Ping.py is ready")

    @commands.command()
    async def ping(self, ctx, member: Optional[discord.Member] = None):  # 添加默认值
        bot_latency = round(self.client.latency * 1000)
        member = member or ctx.author
        await ctx.send(f"Pong! {bot_latency}ms {member.mention}")

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

验证步骤

  1. 替换原Cog文件代码
  2. 确保主文件中client.start('BOTTOKEN')填写正确的Discord机器人Token
  3. 重新运行主文件,错误即可消失

内容的提问来源于stack exchange,提问作者thatwillbeallfolks

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 09:47:10