Discord经济机器人无法运行求助:命令未找到及JSON文件疑似异常问题
Discord经济机器人启动故障排查与修复方案
嘿,我看了你的代码和问题描述,发现好几个关键问题导致机器人启动后命令无法识别,还有数据读写的bug,咱们一步步来修复:
1. 命令装饰器缺失括号——「命令未找到」的核心原因
你用了@client.command但没加括号(),Discord.py的命令装饰器必须带括号才能正确注册命令,这就是系统提示“命令未找到”的直接原因。修复方式很简单:
@client.command() # 加上括号! async def balance(ctx): # ... 原有代码
同理,beg命令的装饰器也要加上括号。
2. 函数调用不匹配&变量未赋值
balance函数里你调用了await users(ctx.author),但你定义的初始化函数是async def account(user),这里函数名写错了,应该改成await account(ctx.author)。account函数里调用data()但没把返回值赋值给users,直接用会报NameError,要改成users = await data()。
3. 文件读写模式错误
所有写入bank.json的地方,你用的是默认只读模式(r),根本没法写入数据。要改成写入模式w,还可以加indent=4让JSON格式更美观:
with open("bank.json", "w") as file: json.dump(users, file, indent=4)
4. 金额累加逻辑错误
beg函数里的users[str(user.id)]["Wallet"] = + earning是错的,这相当于把钱包金额直接设置为earning,而不是累加。应该改成:
users[str(user.id)]["Wallet"] += earning
5. 用户数据初始化冗余
account函数里初始化用户数据的代码太啰嗦,直接赋值一个字典就行:
users[str(user.id)] = {"Wallet": 0, "Bank": 0}
不用先给Wallet赋值为空字典再覆盖。
6. 数据加载的健壮性优化
data函数可以加上异常处理,防止文件不存在时崩溃:
async def data(): try: with open("bank.json", "r") as file: accounts = json.load(file) except FileNotFoundError: # 如果文件不存在,自动创建空文件 accounts = {} with open("bank.json", "w") as file: json.dump(accounts, file) return accounts
完整修复后的代码
import discord from discord.ext import commands import random import json import os client = commands.Bot(command_prefix="!") os.chdir("FOLDER PATH PROVIDED") # 替换成你的实际文件夹路径 @client.event async def on_ready(): await client.change_presence(activity=discord.Game("In Development")) print("Bot is ready!") @client.command() async def balance(ctx): await account(ctx.author) users = await data() user = ctx.author wallet_amount = users[str(user.id)]["Wallet"] bank_amount = users[str(user.id)]["Bank"] em = discord.Embed(title=f"{user.name}'s Account", color=discord.Color.green()) em.add_field(name="Wallet", value=f"${wallet_amount}", inline=True) em.add_field(name="Bank", value=f"${bank_amount}", inline=True) await ctx.send(embed=em) @client.command() async def beg(ctx): await account(ctx.author) users = await data() user = ctx.author earning = random.randrange(1, 101) # 改成1-100,避免赚0的情况 await ctx.send(f"Someone gave you ${earning}!") users[str(user.id)]["Wallet"] += earning with open("bank.json", "w") as file: json.dump(users, file, indent=4) async def account(user): users = await data() if str(user.id) in users: return False else: users[str(user.id)] = {"Wallet": 0, "Bank": 0} with open("bank.json", "w") as file: json.dump(users, file, indent=4) return True async def data(): try: with open("bank.json", "r") as file: accounts = json.load(file) except FileNotFoundError: accounts = {} with open("bank.json", "w") as file: json.dump(accounts, file) return accounts client.run("TOKEN PROVIDED") # 替换成你的机器人Token
最后提醒
- 务必替换代码里的
FOLDER PATH PROVIDED为你的实际文件夹路径(比如C:/Users/YourName/DiscordBot) - 替换
TOKEN PROVIDED为你的Discord机器人Token - 运行前确保安装了依赖:
pip install discord.py
内容的提问来源于stack exchange,提问作者LeonSoul
相关产品推荐
相关产品推荐

