discord.py经济机器人报错:已定义balance命令却提示CommandNotFound
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 userin yourbalancefunction is undefined and unnecessary—you should usectx.authordirectly to reference the user running the command. - Your
openfunction tries to setusers[str(user.id)]["wallet"]before creating the user's entry in the JSON, which will throw aKeyError(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.Botwith proper intents and a clear command prefix. - Removed the broken
global uservariable and usedctx.authordirectly. - 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:
- Make sure your bot token is correct (you can get this from the Discord Developer Portal).
- When testing, use the prefix you set (e.g.,
!balanceinstead of justbalance). - Ensure your bot has read/write permissions for the
C:\discbotdirectory so it can access the JSON file.
内容的提问来源于stack exchange,提问作者Jonathan

