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

为什么我的Discord机器人代码定义了users却仍提示该变量未定义

问题修复说明

错误根因

  • 你在open_account函数中调用get_bank_data()时没有接收它的返回值,users变量仅在get_bank_data的函数作用域内生效,没有传递到open_account的作用域中,所以触发了未定义报错。
  • 你的代码还存在其他几处语法、逻辑错误,会导致后续运行继续报错,已同步修复。

具体修改点

  • open_account函数内调用get_bank_data()时添加变量接收返回值:users = await get_bank_data()
  • 修复open_account内新用户初始化逻辑,不存在的用户ID需要先创建一级字典,再赋值钱包、银行属性
  • 修复balance函数内未定义user变量的问题,将user.id替换为ctx.author.id
  • 修复discord颜色类调用错误,discord.Color首字母需要大写
  • 修复Embed添加字段的语法错误,方法名为add_field,不是add.field

修复后完整代码

import discord
from discord.ext import commands
import json
client = commands.Bot(command_prefix='`')

# 此处替换为你自己的机器人token
token = "你的机器人token"

@client.event
async def on_ready():
    print("We have logged into this server as {0.user}".format(client))


@client.command()
async def balance(ctx):
    await open_account(ctx.author)
    users = await get_bank_data()
    purse_amt = users[str(ctx.author.id)]["purse"]
    bank_amt = users[str(ctx.author.id)]["bank"]
    em = discord.Embed(title=f"{ctx.author.name}'s balance", color=discord.Color.purple())
    em.add_field(name="Purse", value=purse_amt)
    em.add_field(name="Bank", value=bank_amt)
    await ctx.send(embed=em)


async def open_account(user):
    users = await get_bank_data()
    if str(user.id) in users:
        return False
    else:
        users[str(user.id)] = {}
        users[str(user.id)]["purse"] = 0
        users[str(user.id)]["bank"] = 0
    with open("mainbank.json", "w") as f:
        json.dump(users, f)
    return True


async def get_bank_data():
    with open("mainbank.json", "r") as f:
        users = json.load(f)
    return users


client.run(token)

额外注意

运行前请先在代码同级目录创建mainbank.json文件,写入初始内容{},否则会触发文件不存在的报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 08:00:04