如何实现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 bectx(context), followed byerror. Your code has them reversed, so the event never triggers correctly. - Missing
awaitforctx.send(): Sincesend()is an async coroutine, you have to useawaitto 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
ifstatements could lead to multiple messages if (unlikely here) multiple error types match. Switching toelifmakes 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_contentintent 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_errorevent. 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
相关产品推荐
相关产品推荐

