如何在用户执行Discord命令后接收输入文本以触发差异化响应?
Hey there! I’ve dealt with this exact scenario before when building Discord bots, so let me walk you through how to make this work smoothly using discord.py.
The key tool here is the wait_for() method, which lets your bot pause and listen for a specific event (in this case, a user’s message) after sending your initial command response. Here’s how to modify your hello command to handle the user’s choice between 1 and 2:
import asyncio from discord.ext import commands @client.command() async def hello(ctx): await ctx.send(f'Hey there {ctx.author.name}! Say 1 to access the moderation module and 2 to access the fun module') # Define a "check" function to filter valid incoming messages def check(message): # Ensure the message comes from the same user who ran the command # ...and is sent in the same channel # ...and matches one of our expected inputs return message.author == ctx.author and message.channel == ctx.channel and message.content in ['1', '2'] try: # Wait for the user's response, with a 30-second timeout response = await client.wait_for('message', check=check, timeout=30.0) # Handle the user's choice with targeted responses if response.content == '1': await ctx.send("Perfect! Welcome to the moderation module. Here are your available commands:\n- `!kick` (temporarily remove a user)\n- `!ban` (permanently remove a user)\n- `!mute` (silence a user)") # You can add follow-up logic here (like waiting for a specific moderation command) elif response.content == '2': await ctx.send("Woohoo! Let's have some fun. Try these commands:\n- `!joke` (get a random dad joke)\n- `!meme` (post a random meme)\n- `!8ball` (ask the magic 8-ball a question)") # Add fun module interactions here except asyncio.TimeoutError: # If the user doesn't respond in time, send a friendly reminder await ctx.send("Oops, you took too long to respond! Just run `!hello` again when you're ready to choose.")
Let’s break down what’s happening here:
- The
checkfunction: This filters out irrelevant messages, so your bot only reacts to the command’s original sender, in the same channel, and with valid input (1 or 2). This prevents other users’ messages from accidentally triggering the bot. wait_for('message'): This tells the bot to pause and listen for a new message that passes our check. Thetimeoutparameter ensures the bot doesn’t wait indefinitely if the user doesn’t reply.- Error handling: The
try/exceptblock catches theTimeoutError, letting you send a gentle reminder instead of leaving the bot stuck waiting.
Bonus: A more user-friendly alternative
If you want to avoid forcing users to type plain numbers, you can use discord.py Views (buttons or select menus) for a more interactive experience:
from discord import ui, ButtonStyle class ModuleSelect(ui.View): def __init__(self): super().__init__(timeout=30.0) @ui.button(label="Moderation", style=ButtonStyle.danger) async def mod_button(self, interaction, button): await interaction.response.send_message("Moderation module selected! Use `!kick`, `!ban`, or `!mute`.") self.stop() @ui.button(label="Fun", style=ButtonStyle.success) async def fun_button(self, interaction, button): await interaction.response.send_message("Fun module selected! Try `!joke`, `!meme`, or `!8ball`.") self.stop() @client.command() async def hello(ctx): await ctx.send(f'Hey there {ctx.author.name}! Choose a module:', view=ModuleSelect())
This gives users clickable buttons instead of requiring them to type numbers, which is often more intuitive for casual users.
内容的提问来源于stack exchange,提问作者RickyTicky Bobbywobbin

