discord.py带while循环的按钮命令多频道运行触发重复响应如何解决
问题根因
你当前代码中调用bot.wait_for('button_click')时未添加任何过滤规则,全局范围内任意按钮点击事件都会被所有处于等待状态的random_screenshot命令实例捕获,导致所有并行运行的命令实例同时跳出等待、执行下一轮循环,最终出现多频道同步响应的问题。
修复方案
你需要给wait_for方法添加自定义检查函数,仅放行当前命令对应的有效点击事件即可解决冲突,同时需要对按钮点击做出响应,避免discord前端显示交互超时。
修改后的参考代码如下:
import random import string import discord from discord_components import DiscordComponents, Button, ButtonStyle @bot.command() async def random_screenshot(ctx): # 自定义检查函数,可根据需求调整规则 def check(interaction): # 示例规则:仅当前频道内、触发命令的用户点击才会生效 return interaction.channel.id == ctx.channel.id and interaction.user.id == ctx.author.id while True: letters = string.ascii_lowercase + string.digits rand_string = ''.join(random.choice(letters) for i in range(6)) link = "https://prnt.sc/" + str(rand_string) await ctx.send(link, components=[ Button(style=ButtonStyle.blue, label="Next", emoji="➡") ]) # 添加check过滤,同时设置超时时间避免命令无限制挂起 interaction = await bot.wait_for('button_click', check=check, timeout=300) # 响应按钮点击,避免前端显示加载失败 await interaction.respond(type=6)
额外优化建议
- 可以按需调整check函数的规则,比如不需要限制点击用户的话,删掉用户id匹配的判断即可
- 上述代码添加了5分钟的超时时间,超时后命令会自动抛出异常结束,你可以添加try-except捕获超时异常做优雅退出,避免后台报错。
内容的提问来源于stack exchange,提问作者Murlik
相关产品推荐
相关产品推荐

