You need to enable JavaScript to run this app. discord.py 如何实现等待指令发起者响应并返回对应匹配消息
优惠活动
大模型
产品
解决方案
定价
更多

discord.py 如何实现等待指令发起者响应并返回对应匹配消息

基于discord.py实现指令发起者的定向等待响应逻辑

核心实现依赖

使用discord.py内置的wait_for协程完成临时事件监听,无需维护全局用户状态表,天然支持多用户同时触发指令的并发场景。

关键逻辑规则

  • 响应过滤:仅接收发送原指令的用户在原指令所在频道发送的消息,避免其他用户误触干扰流程
  • 超时保护:默认设置30秒等待窗口,超时自动终止流程释放资源
  • 输入校验:严格校验用户输入是否为1-12范围内的有效数字,无效输入给出明确提示

完整可运行代码

import asyncio
import discord

client = discord.Client()

# 学科数字和名称的映射表,可自行扩展对应返回内容
SUBJECT_MAP = {
    1: "Histoire",
    2: "Géographie",
    3: "EMC",
    4: "Français",
    6: "Mathématiques",
    7: "Physique-Chimie",
    8: "Enseignement Scientifique",
    9: "NSI",
    10: "Anglais",
    11: "Espagnol",
    12: "Allemand"
}

@client.event
async def on_ready():
    print('We have logged in as {0.user}'.format(client))

@client.event
async def on_message(message):
    if message.author == client.user:
        return

    if message.content.startswith('.pdfcheckup'):
        # 发送可选学科提示
        await message.channel.send("Quelle matière scolaire cherchez-vous ?\nListe des matières disponibles:\n**```\n1- Histoire\n2- Géographie\n3- EMC\n4- Français\n6- Mathématiques\n7- Physique-Chimie\n8- Enseignement Scientifique\n9- NSI\n10- Anglais\n11- Espagnol\n12- Allemand\n```**")

        # 定义响应过滤规则
        def check(response_msg):
            return (
                response_msg.author == message.author 
                and response_msg.channel == message.channel
            )

        # 等待用户响应,最长等待30秒
        try:
            user_response = await client.wait_for(
                'message', 
                check=check, 
                timeout=30.0
            )
        except asyncio.TimeoutError:
            await message.channel.send('⏰ 等待响应超时,请重新发送 `.pdfcheckup` 发起查询。')
            return

        # 校验用户输入内容
        if not user_response.content.strip().isdigit():
            await message.channel.send('❌ 输入格式无效,请发送1-12范围内的数字对应学科。')
            return
        
        selected_num = int(user_response.content.strip())
        if selected_num not in SUBJECT_MAP:
            await message.channel.send('❌ 输入数字不在可选学科范围内,请重新发起查询。')
            return
        
        # 匹配到有效学科后发送对应专属消息,可替换为实际的PDF链接、文件等内容
        await message.channel.send(f'✅ 已为你匹配{SUBJECT_MAP[selected_num]}相关资源:此处替换为对应专属返回内容')

client.run('[my token]')

扩展提示

如果需要支持用户输错后多次重试、不直接终止流程,可以把输入校验部分套入循环,只有收到有效学科数字或者超时才退出等待逻辑。


内容的提问来源于stack exchange,提问作者Mirai

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.18 11:15:02