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

Discord.py经济Cog报错排查:NameError: 'open_account'未定义

问题分析:迁移Discord Bot经济系统到Cog后出现NameError错误

你遇到的NameError问题根源很明确——在类的方法内部调用类的其他方法时,没有正确使用self前缀来引用。

在你的Economy类里,open_account是一个类的异步方法,但你在balance和work命令里直接写了await open_account(ctx.author),Python会把它当成全局函数去查找,自然找不到,就抛出了name 'open_account' is not defined的错误。

修复方法

只需要在调用open_account时加上self.前缀,明确告诉Python这是当前类实例的方法:

修改balance方法:

@commands.command()
async def balance(self, ctx):
    await self.open_account(ctx.author)  # 这里加上self.
    discorduserid = ctx.author.id
    document = collection.find_one({"userid":discorduserid})
    print(document)
    wallet_amt = document["points"]
    em = discord.Embed(title = f"{ctx.author.name}'s balance", colour = discord.Colour.red())
    em.add_field(name = "Wallet", value = wallet_amt)
    await ctx.send(embed = em)

修改work方法:

@commands.command()
@commands.cooldown(1, 14400, commands.BucketType.user)
async def work(self, ctx):
    await self.open_account(ctx.author)  # 这里加上self.
    discorduserid = ctx.author.id
    earnings = random.randrange(1000)
    await ctx.send(f"You went to work and earned {earnings} coins!")
    doc = collection.find_one({"userid":discorduserid})
    total_earnings = doc["points"] + earnings
    results = collection.update_one({"userid":discorduserid}, {"$set":{"points":total_earnings}})

额外提示

在Python的类中,所有实例方法的第一个参数都是self(代表当前类的实例),调用类内部的其他方法、属性时,都必须通过self.xxx的方式来访问,这样才能确保作用域正确,避免类似的命名错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 08:27:21