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

discord.py经济机器人报错:已定义balance命令却提示CommandNotFound

Fixing "CommandNotFound" for Your discord.py Economy Bot's balance Command

Got it, let's break down why your balance command isn't being recognized and fix the other sneaky bugs in your script along the way.

1. The Root Cause: Wrong Client Instance

The most common reason you're seeing CommandNotFound is that you're probably using a basic discord.Client instead of commands.Bot. The @client.command() decorator only works with a commands.Bot object—it's part of discord.py's commands extension, which the plain Client doesn't support.

First, fix your bot initialization:

from discord.ext import commands
import discord
import json

# Pick your command prefix (like '!' or '$') and enable intents (required for message access)
client = commands.Bot(command_prefix='!', intents=discord.Intents.all())

(Intents are mandatory in newer discord.py versions to read message content, so enabling all intents here makes sure your bot can see the commands users type.)

2. Fixing Other Critical Bugs

Even once the command is recognized, your script has a few issues that will crash it:

  • The global user in your balance function is undefined and unnecessary—you should use ctx.author directly to reference the user running the command.
  • Your open function tries to set users[str(user.id)]["wallet"] before creating the user's entry in the JSON, which will throw a KeyError (since that key doesn't exist yet).
  • You're reading the JSON file multiple times unnecessarily, and there's no fallback if the file doesn't exist initially.

Corrected Full Script

Here's the fixed, working version of your code with all these issues addressed:

from discord.ext import commands
import discord
import json

# Initialize bot with prefix and required intents
client = commands.Bot(command_prefix='!', intents=discord.Intents.all())

# Use a constant for your file path to avoid repetition
BANK_FILE_PATH = r"C:\discbot\bank.json"

@client.command()
async def balance(ctx):
    # Create the user's account if it doesn't exist
    await open_user_account(ctx.author)
    # Fetch the latest user data
    users = await get_all_users()
    
    user_id = str(ctx.author.id)
    wallet_balance = users[user_id]["wallet"]
    bank_balance = users[user_id]["bank"]
    
    # Build and send the balance embed
    balance_embed = discord.Embed(title=f"{ctx.author.name}'s Balance", color=discord.Color.red())
    balance_embed.add_field(name="WALLET", value=f"${wallet_balance}", inline=True)
    balance_embed.add_field(name="BANK", value=f"${bank_balance}", inline=True)
    await ctx.send(embed=balance_embed)

async def open_user_account(user):
    users = await get_all_users()
    user_id = str(user.id)
    
    if user_id not in users:
        # Create a full entry for the new user
        users[user_id] = {"wallet": 0, "bank": 0}
        # Save the updated data back to the JSON file
        with open(BANK_FILE_PATH, "w") as file:
            json.dump(users, file, indent=4)  # Indent makes the JSON human-readable
        return True
    return False

async def get_all_users():
    try:
        # Try to read existing user data
        with open(BANK_FILE_PATH, "r") as file:
            return json.load(file)
    except FileNotFoundError:
        # If the file doesn't exist, create an empty one and return an empty dict
        with open(BANK_FILE_PATH, "w") as file:
            json.dump({}, file)
        return {}

# Replace this with your actual bot token from the Discord Developer Portal
client.run("YOUR_BOT_TOKEN_HERE")

Key Improvements & Fixes:

  • Switched to commands.Bot with proper intents and a clear command prefix.
  • Removed the broken global user variable and used ctx.author directly.
  • Fixed the account creation logic to create a full user entry before setting wallet/bank values (no more KeyError).
  • Added error handling for when the JSON file doesn't exist yet (it will be created automatically).
  • Cleaned up the embed formatting with inline fields and dollar signs for better readability.
  • Used a constant for the file path to avoid typos and repetition.

Final Quick Checks:

  1. Make sure your bot token is correct (you can get this from the Discord Developer Portal).
  2. When testing, use the prefix you set (e.g., !balance instead of just balance).
  3. Ensure your bot has read/write permissions for the C:\discbot directory so it can access the JSON file.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 08:04:19