Discord.py bet命令修改economy.json的balance值时出现报错
解决Discord.py bet命令中
'dict' object has no attribute 'append'错误 错误原因
你的economy.json内容是一个字典({"balance":2}),但代码里错误地对这个字典对象调用了append()方法——append()是Python列表(list)的专属方法,字典类型根本没有这个属性,所以触发了该错误。
修复方案
直接基于字典结构操作balance字段即可,无需使用append()。以下是完整的实现思路和示例代码:
核心步骤
- 读取
economy.json文件,解析为字典对象 - 检查用户投注金额是否合法(不超过当前余额)
- 随机生成输赢结果,加入jackpot概率逻辑
- 根据结果调整字典中的
balance值 - 将修改后的字典重新写入
economy.json
示例代码
import discord import json import random from discord.ext import commands bot = commands.Bot(command_prefix="!", intents=discord.Intents.all()) @bot.command(aliases=["gamble"]) async def bet(ctx, amount: int): # 读取经济数据 with open("economy.json", "r") as f: data = json.load(f) # 验证投注金额 if amount <= 0: await ctx.send("投注金额必须大于0!") return if amount > data["balance"]: await ctx.send("余额不足,无法投注!") return # 随机生成结果:10%概率中jackpot,45%赢,45%输 result = random.choices(["jackpot", "win", "lose"], weights=[10, 45, 45])[0] if result == "jackpot": winnings = amount * 5 data["balance"] += winnings await ctx.send(f"恭喜中了Jackpot!获得{winnings}金币,当前余额:{data['balance']}") elif result == "win": data["balance"] += amount await ctx.send(f"赢了!获得{amount}金币,当前余额:{data['balance']}") else: data["balance"] -= amount await ctx.send(f"输了!扣除{amount}金币,当前余额:{data['balance']}") # 写入修改后的余额 with open("economy.json", "w") as f: json.dump(data, f, indent=4) bot.run("你的Bot令牌")
关键注意点
- 每次修改余额后,必须以字典格式重新写入文件,不能用列表的操作方法
- 如果后续要支持多用户,建议把
economy.json改成以用户ID为键的字典结构(比如{"123456789": {"balance": 100}}),避免单余额的局限
内容的提问来源于stack exchange,提问作者Phoenix
相关产品推荐
相关产品推荐

