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

discord.py Cog中普通函数调用报错:NameError(名称未定义)

解决Discord.py Cog中调用类方法出现NameError的问题

嘿,我看你遇到的问题很明确——在Cog的on_message监听器里调用print_message函数时触发了NameError,这是因为没搞清楚Python类中实例方法的调用规则。

错误原因

在Python的类中,实例方法必须通过self来调用。print_message是Misc类的一个实例方法,不是全局函数。你直接写print_message(message)的话,Python会在全局作用域里找这个函数,自然找不到,就抛出了名称未定义的错误。

修复步骤

只需要在调用print_message的时候加上self.前缀,让Python知道这是当前类实例的方法:

修改后的cog.py代码:

import discord
from discord.ext import commands

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

    def print_message(self,message):
        print(f"New message received!\nAuthor: {message.author}\nContent: {message.content}\n----------")

    @commands.Cog.listener()
    async def on_message(self,message):
        # 加上self.调用类内的实例方法
        self.print_message(message)
        # 额外提醒:如果你的bot还要处理命令,必须加上这一行,否则命令会被on_message拦截
        await self.client.process_commands(message)

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

额外注意点

你错误信息里还出现了CommandNotFound: Command "hi" is not found,这是因为当你自定义on_message监听器时,默认会阻止discord.py处理命令。所以一定要在on_message方法末尾加上await self.client.process_commands(message),这样bot才能正常响应你的前缀命令。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 14:07:40