Discord.py开发经济Cog时出现Economy对象无ctx属性报错如何解决
问题排查与解决方法
错误根因
「Economy object doesn't have an attribute ctx」报错的直接原因是代码错误使用了
self.ctx.author.id,self指向的是Economy Cog类的实例,该实例本身没有预存ctx属性,ctx是当前_bet命令函数的入参,直接调用即可,不需要加self.前缀。
额外问题修复
代码中还有多个影响功能运行的问题需要同步处理:
- 重复嵌套打开了两次
data/eco.json只读流,属于无用冗余代码 - 没有校验调用命令的用户是否已经在
eco.json中初始化经济数据,直接修改会抛出KeyError - 没有校验下注金额合法性(负数、用户余额不足的情况)
- 写入json无缩进,后续排查数据可读性差
修正后的完整代码
@commands.command(name="bet", aliases=["be", "b"], brief="You bet for honeycomb", description="If you lose you give honeycomb, if you win you get honeycomb") async def _bet(self, ctx, amount : int = 5): # 下注金额合法性校验 if amount < 1: embed = discord.Embed(title="下注错误", description="下注金额不能小于1", color=0xff0000) await ctx.send(embed=embed) return user_id = str(ctx.author.id) # 读取经济数据 with open("data/eco.json", "r") as dataRead: dataReadJSON = json.load(dataRead) # 初始化未注册用户的经济数据 if user_id not in dataReadJSON: dataReadJSON[user_id] = 0 # 可替换为你设定的初始余额 # 余额充足性校验 if dataReadJSON[user_id] < amount: embed = discord.Embed(title="下注错误", description="你的蜂巢余额不足", color=0xff0000) await ctx.send(embed=embed) return # 胜负随机判定 cance = [True, False] random_chance = random.choice(cance) if random_chance: dataReadJSON[user_id] += int(amount*2) embed = discord.Embed(title="Bet", description=f"You bet and won <:honeycomb0:879275123486633984>{amount*2}", color=0xffff00) else: dataReadJSON[user_id] -= int(amount) embed = discord.Embed(title="Bet", description=f"You bet and lost <:honeycomb0:879275123486633984>{amount}", color=0xff0000) # 写入更新后的数据 with open("data/eco.json", "w") as dataWrite: json.dump(dataReadJSON, dataWrite, indent=4) await ctx.send(embed=embed)
内容的提问来源于stack exchange,提问作者AidanGamin
相关产品推荐
相关产品推荐

