如何让Discord机器人的Rickroll命令条件逻辑正常运行?
Fixing Rickroll Command Conditional Logic for Discord Bot
Let's walk through why your current code isn't behaving as expected and get it working correctly.
Why Your Current Code Fails
- You're Not Targeting the Mentioned User: If your
uservariable isn't pulling the specific user you @-ed (e.g., it's instead pointing to the person running the command), the check will always evaluate against the wrong ID. - ID Type Mismatch: Discord user IDs are sometimes stored as strings, but you're comparing against an integer. If
user.idis a string,user.id != 878176818564317184will always beTrueregardless of the actual ID. - Disjointed Messages: Sending three separate
send()calls posts three separate messages, which is messy and not ideal for this command.
Corrected Implementation
Assuming you're using discord.py (the most common library for Discord bots), here's the fixed code that addresses all these issues:
# Check if any user was mentioned in the command if ctx.message.mentions: target_user = ctx.message.mentions[0] # Ensure we're comparing IDs as the same type (integer) target_user_id = int(target_user.id) if isinstance(target_user.id, str) else target_user.id if target_user_id != 878176818564317184: # Combine mention, GIF link, and text into one message await ctx.send(f"{target_user.mention}\nhttps://tenor.com/view/rick-astley-rick-roll-dancing-dance-moves-gif-14097983\nhas been rickrolled lol") else: await ctx.send("No u") else: # Handle case where no user was tagged await ctx.send("You need to mention a user to rickroll them!")
What Changed & Why
- Grab the Mentioned User:
ctx.message.mentions[0]gets the first user you tagged in the command, ensuring we're checking the right person's ID. - Type-Safe ID Check: We convert the user's ID to an integer to match your hardcoded ID, eliminating type mismatch bugs.
- Single Cohesive Message: Using an f-string to merge all content into one
send()call keeps the response clean and easy to read. - Fallback for No Mention: Added a check to handle when someone runs the command without tagging a user, so the bot doesn't misbehave.
内容的提问来源于stack exchange,提问作者Zook780
相关产品推荐
相关产品推荐

