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

如何在用户执行Discord命令后接收输入文本以触发差异化响应?

How to Handle User Input After a Discord Command in discord.py

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 check function: 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. The timeout parameter ensures the bot doesn’t wait indefinitely if the user doesn’t reply.
  • Error handling: The try/except block catches the TimeoutError, 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 14:37:29