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

如何实现discord.py命令参数错误时发送聊天提示?代码求助

Fixing Your Discord.py Command Error Handling

Let's break down why your error handler isn't working and fix it step by step:

Key Issues in Your Current Code

  • Wrong parameter order for on_command_error: Discord.py expects the first parameter to be ctx (context), followed by error. Your code has them reversed, so the event never triggers correctly.
  • Missing await for ctx.send(): Since send() is an async coroutine, you have to use await to actually execute it—without it, the message never gets sent, and no errors show up in the terminal because the coroutine is just created but never run.
  • Unstructured condition checks: Using separate if statements could lead to multiple messages if (unlikely here) multiple error types match. Switching to elif makes the logic cleaner and ensures only one error message is sent per issue.

Corrected Full Code

import discord
from discord.ext import commands
import random

# Initialize your bot (don't forget to enable message content intent!)
intents = discord.Intents.default()
intents.message_content = True
bot = commands.Bot(command_prefix="!", intents=intents)

@bot.command(name="randint")
async def random_num(ctx, min_num:int, max_num:int):
    result = random.randint(min_num, max_num)
    embed=discord.Embed(color=0x1e9f9c)
    embed.add_field(name="Random number", value=f"min:{min_num}, max:{max_num}", inline=False)
    embed.add_field(name="Result", value=result, inline=False)
    await ctx.send(embed=embed)

@bot.event
async def on_command_error(ctx, error):
    # Handle missing required arguments first
    if isinstance(error, commands.MissingRequiredArgument):
        await ctx.send("bruh you do know you have to input 2 numbers lol")
    # Handle non-number input errors
    elif isinstance(error, commands.BadArgument):
        await ctx.send("bruh input numbers")
    # Optional: Catch-all for unhandled errors (helps with debugging)
    else:
        print(f"Unhandled error occurred: {error}")
        await ctx.send("Oops, something unexpected went wrong!")

# Replace with your actual bot token
bot.run("YOUR_BOT_TOKEN_HERE")

Extra Tips

  • Ensure you've enabled the message_content intent in your Discord Developer Portal—without it, your bot can't read command inputs at all.
  • If you only need error handling for this specific command, you can use a per-command error handler instead of the global on_command_error event. This is often cleaner:
@random_num.error
async def random_num_error(ctx, error):
    if isinstance(error, commands.MissingRequiredArgument):
        await ctx.send("bruh you do know you have to input 2 numbers lol")
    elif isinstance(error, commands.BadArgument):
        await ctx.send("bruh input numbers")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 20:47:50