wait_for reaction_add 总是超时

时间:2021-04-01 12:31:19

标签: python-3.x discord discord.py

我正在开发一个 Discord 机器人,它需要等待将反应添加到消息中,但它似乎总是超时,只是无法识别添加的反应。我的代码看起来类似于 StackOverflow 上关于同一事物的其他问题的答案,但它仍然以某种方式不起作用。

发送消息 10 秒后,将打印 timed out :( 字符串。与此同时,我对我发送的消息添加了一个反应,但没有任何反应。它也不会调用 check,因为表情符号从不打印。

有谁知道我做错了什么?我还查看了 Discord.py 文档,看起来我做得对。

编辑:我创建了一个最小的可重现示例,其中包含一个主文件和 1 个齿轮:https://github.com/put/discord-testing-bot。这就是我所做的:

  1. python main.py
  2. 等待打印“测试齿轮加载”
  3. 确保机器人在线
  4. 在机器人所在的服务器中发送消息
  5. 在 10 秒内添加一个竖起大拇指的表情符号
  6. 等一下
  7. 请参阅控制台中打印的“超时 :(”。

机器人拥有我服务器中的所有权限: GIF of permissions

ma​​in.py

import discord
from discord.ext import commands

intents = discord.Intents.none()
intents.guilds = True
intents.members = True
intents.emojis = True
intents.guild_messages = True
intents.guild_reactions = True

class TestBot(commands.Bot):
    def __init__(self):
        super().__init__(command_prefix="^", help_command=None, max_messages=None, intents=intents)
        self.load_extension('test_cog')

if __name__ == "__main__":
    bot = TestBot()
    bot.run("[TOKEN HERE]", bot=True)

test_cog.py

import discord
from discord.ext import commands
import asyncio

class TestCog(commands.Cog):
    def __init__(self, bot):
        self.bot = bot
        self._last_member = None

    @commands.Cog.listener()
    async def on_message(self, message):
        if message.author.bot or message.channel.type.name != 'text':
            return

        def check(reaction, user):
            print('a')
            return user == message.author and str(reaction.emoji) == "?"

        try:        
            reaction, user = await self.bot.wait_for('reaction_add', check=check, timeout=10)
            print('success!')

        except asyncio.exceptions.TimeoutError:
            print('timed out :(')

        except Exception as e:
            print(f'other error: {repr(e)}')

def setup(bot):
    bot.add_cog(TestCog(bot))
    print("Test Cog loaded")

1 个答案:

答案 0 :(得分:0)

来自documentation

<块引用>

ma​​x_messages(可选[int]) – 要存储在内部消息缓存中的最大消息数。这默认为 1000。传入 None 会禁用消息缓存。

您正在使用 max_messages=None 禁用内部消息缓存。由于机器人不存储消息,因此它看不到添加到其中的任何反应。

None 更改为某个整数值(默认为 1000),或者只是简单地从代码中删除 max_messages=None