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

如何使用wait_for方法实现机器人等待用户响应并校验是否为链接

Discord机器人wait_for指令实现等待用户输入并校验链接方案

完整实现代码如下:

from urllib.parse import urlparse
import discord
from discord.ext import commands

# 机器人初始化,注意按需开启对应意图,必须开启消息相关权限
client = commands.Bot(command_prefix='!', intents=discord.Intents.all())

@client.command()
async def begin(ctx):
    await ctx.send("请发送你服务器托管站点的首页链接。")
    
    # 消息校验规则:仅接收当前命令触发用户、当前频道的消息
    def check(msg):
        return msg.author == ctx.author and msg.channel == ctx.channel
    
    try:
        # 等待用户响应,超时时间30秒可自行调整
        user_response = await client.wait_for('message', timeout=30, check=check)
        # 校验内容是否为合法http/https链接
        parsed_result = urlparse(user_response.content)
        if parsed_result.scheme in ('http', 'https') and parsed_result.netloc:
            await ctx.send(f"链接校验通过,你提交的地址为:{user_response.content}")
            # 此处可添加校验通过后的后续业务逻辑
        else:
            await ctx.send("提交内容不是合法的公网链接,请重新调用命令提交。")
    except TimeoutError:
        await ctx.send("等待响应超时,请重新调用命令提交。")

关键逻辑说明:

  • wait_for方法第一个参数为监听的事件名,此处监听message事件即可捕获用户发送的新消息;timeout参数设置最长等待时长,单位为秒,超时后会抛出TimeoutError异常需捕获处理;check参数传入校验回调,只有满足回调返回True的消息才会被返回,避免其他用户或其他频道的消息干扰当前交互流程。
  • 链接校验使用Python标准库urllib.parse.urlparse实现,无需引入第三方依赖,判断解析结果的协议头为http/https、且存在域名部分即可判定为合法公网链接。
  • 使用前需在Discord开发者后台的机器人配置页开启Message Content Intent权限,否则机器人无法读取用户发送的消息内容,wait_for无法正常捕获响应。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 06:57:00