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

Discord.py嵌入反应系统问题:单Embed正常 多Embed反应互相干扰

问题根源

  • 当前wait_for事件监听的校验规则缺少反应归属的消息ID校验:所有同命令生成的Embed消息的反应事件,都会命中所有正在运行的监听逻辑,导致多份Embed的计数器被同步修改
  • 其他潜在问题:
    • 每次修改数值都调用add_field,会导致Embed的字段持续累加,不会覆盖原有内容
    • while True循环没有退出逻辑,超时后依然会持续监听,占用资源
    • 触发垃圾桶表情后没有终止循环,逻辑会继续运行

修复后代码

import discord
import asyncio
from discord.ext import commands

@client.command()
async def embed(ctx):
    current = 1
    embed = discord.Embed(title=f"{current}")
    buttons = [u"\u25C0", u"\u25FC", u"\u25B6", u"\U0001F5D1"]
    msg = await ctx.send(embed=embed)

    for button in buttons:
        await msg.add_reaction(button)
    
    while True:
        try:
            # 新增校验:反应的消息必须是当前命令生成的这条消息
            reaction, user = await client.wait_for(
                "reaction_add",
                check=lambda reaction, user: user == ctx.author and reaction.emoji in buttons and reaction.message.id == msg.id,
                timeout=180.0
            )
        except asyncio.TimeoutError:
            embed.set_footer(text="Timeout.")
            await msg.edit(embed=embed)
            await msg.clear_reactions()
            # 超时后退出循环,释放资源
            break

        else:
            previous_page = current
            # 每次修改前清空原有字段,避免重复累加
            embed.clear_fields()
            if reaction.emoji == u"\u25C0":
                current -= 1
            elif reaction.emoji == u"\u25FC":
                if current > 0:
                    current = 0
            elif reaction.emoji == u"\u25B6":
                current += 1
            elif reaction.emoji == u"\U0001F5D1":
                await msg.clear_reactions()
                # 触发删除后直接退出循环
                break

            await msg.remove_reaction(reaction.emoji, ctx.author)

            if current != previous_page:
                embed.title = f"{current}"
                embed.add_field(name=None, value=f"{current}")
                await msg.edit(embed=embed)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 14:15:04