如何实现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
相关产品推荐
相关产品推荐

