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

如何实现Discord机器人等待用户响应并获取链接后删除消息

解决Discord机器人等待用户回复并清理消息的问题

你当前的代码里client.wait_for("message")会监听所有频道的所有消息,没法确保只收到命令发起者的回复,而且也没处理后续删除消息的逻辑。下面是修改后的完整代码,解决这些问题:

import asyncio
import discord

@client.command()
async def messageembed(ctx):
    # 删除触发命令的原始消息
    await ctx.message.delete()
    
    # 创建并发送Embed,同时保存这条消息的对象
    embed = discord.Embed(colour=discord.Colour.blue())
    embed.set_author(name='Enter your profile link')
    bot_msg = await ctx.send(embed=embed)
    
    # 定义消息检查规则:必须是发起命令的用户在当前频道发的消息
    def msg_check(msg):
        return msg.author == ctx.author and msg.channel == ctx.channel
    
    try:
        # 等待用户回复,超时时间设为60秒
        user_reply = await client.wait_for("message", check=msg_check, timeout=60)
        profile_link = user_reply.content
        
        # 删除机器人的Embed消息和用户的回复
        await bot_msg.delete()
        await user_reply.delete()
        
        # 这里可以添加后续处理逻辑,比如用拿到的链接做操作
        await ctx.send(f"已获取到你的个人资料链接", delete_after=5)
    except asyncio.TimeoutError:
        # 超时后清理机器人的消息并提示用户
        await bot_msg.delete()
        await ctx.send("超时没回复,操作取消了", delete_after=5)

关键说明

  • 消息过滤:通过msg_check函数,只接收发起命令的用户在当前频道的回复,避免误收其他无关消息
  • 超时处理:设置timeout=60,如果用户60秒内没回复,机器人会自动终止等待并清理消息
  • 消息对象保存:发送Embed时把消息存在bot_msg里,后续才能精准删除这条机器人发送的消息
  • 异常捕获:捕获TimeoutError,处理用户超时不回复的情况

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 13:30:40