Discord.py踢人命令无法识别带空格/下划线昵称的问题排查
Great question—this is a common pitfall with Discord.py command parameters when dealing with usernames that have spaces or special characters! Let’s break down what’s going wrong and how to fix it.
What’s the Issue?
Your current command defines user_name: discord.User as a positional parameter followed by reason. When a user runs something like !kick John_Doe breaking rules, it works because John_Doe is a single "token" with no spaces. But if they try !kick John Doe breaking rules, Discord.py will treat John as the user_name and Doe as the start of the reason—it doesn’t know to group the full spaced username as one parameter.
Additionally, using discord.User instead of discord.Member is slightly off here: kicking requires interacting with a server member, not just a generic Discord user, so Member is more appropriate (and it supports better user resolution for mentions, IDs, and spaced names).
The Fix
Here are the key changes you need to make:
- Switch to
discord.Memberfor the user parameter—this ensures you’re targeting a server member and handles all valid user identifiers correctly. - Make
reasona variable-length argument using*reason—this captures all remaining text after the user as the reason, even if it has spaces. - Add a default for empty reason so the command doesn’t break if no reason is provided.
Modified Code
@client.command() async def kick(ctx, member: discord.Member, *reason): # Join the reason tuple into a single string (handle empty case) reason_str = " ".join(reason) if reason else "no reason provided" await ctx.guild.kick(member) await ctx.send(f"{member.mention} has been kicked for: {reason_str}")
How to Use It
Now you can use the command in multiple ways, all of which work with spaced/underscored usernames:
- Mention the user directly:
!kick @JohnDoe spamming in general chat - Use the full spaced username (wrap in quotes):
!kick "John Doe" violating server guidelines - Use the user’s numeric ID:
!kick 123456789012345678 repeated harassment
Bonus: Add Robust Error Handling
To make the command more user-friendly, add error handling for common issues like missing permissions or invalid users:
@kick.error async def kick_error(ctx, error): if isinstance(error, commands.MissingRequiredArgument): await ctx.send("Please specify a user to kick (and a reason if you want).") elif isinstance(error, commands.MemberNotFound): await ctx.send("That user couldn't be found in this server.") elif isinstance(error, commands.MissingPermissions): await ctx.send("I don't have permission to kick members!") else: await ctx.send(f"An unexpected error occurred: {str(error)}")
内容的提问来源于stack exchange,提问作者Daniel Tam

