【问题标题】:Discord.py wait for message or reactionDiscord.py 等待消息或反应
【发布时间】:2022-01-11 11:05:39
【问题描述】:

我对 Python 和 Discord.py 都很陌生,我正在尝试寻找如何让机器人同时等待用户的消息或反应。

我尝试将它们分开,但只是导致机器人在反应之前需要消息响应。

这是我正在尝试做的类似代码:

@bot.event
async def on_message(ctx):
    if ctx.author == bot.user:
        return

    if ctx.content == "$respond":
        message = await ctx.send("Waiting for response...")

        while True:
            try:
                response = #Will wait for a message(Yes or No) or reaction(Check or Cross) from ctx.author for 30 secs
            except asyncio.TimeoutError:
                await message.edit(content=f"{ctx.author} did not respond anymore!")
                break

            if response.content == "yes":
                await message.edit(content=f"{ctx.author} said yes!")
                continue
            
            elif response.content == "no":
                await message.edit(content=f"{ctx.author} said nyo!")
                continue
            
            #These are reactions
            elif str(response.emoji) == "✅":
                await message.edit(content=f"ctx.author reacted ✅!")
                continue
            
            elif str(response.emoji) == "❌":
                await messave.edit(content=f"Stopped listening to responses.")
                break

【问题讨论】:

    标签: python discord.py


    【解决方案1】:

    bot.wait_for 是您在此处寻找的内容。

    我建议使用bot.command() 来处理命令,但这也很好。

    这是您在特定条件下等待特定事件(作为第一个参数提供)的方式(如 check 参数中提供的那样)

    @bot.event
    async def on_message(msg):
        if msg.author == bot.user:
            # if the author is the bot itself we just return to prevent recursive behaviour
            return
        if msg.content == "$response":
    
            sent_message = await msg.channel.send("Waiting for response...")
            res = await bot.wait_for(
                "message",
                check=lambda x: x.channel.id == msg.channel.id
                and msg.author.id == x.author.id
                and x.content.lower() == "yes"
                or x.content.lower() == "no",
                timeout=None,
            )
    
            if res.content.lower() == "yes":
                await sent_message.edit(content=f"{msg.author} said yes!")
            else:
                await sent_message.edit(content=f"{msg.author} said no!")
    

    这将导致:

    监听多个事件有点意思, 用这个 sn-p 替换现有的wait_for

    done, pending = await asyncio.wait([
                        bot.loop.create_task(bot.wait_for('message')),
                        bot.loop.create_task(bot.wait_for('reaction_add'))
                    ], return_when=asyncio.FIRST_COMPLETED)
    

    你可以同时监听两个事件

    以下是使用 @bot.command() 处理此问题的方法

    import discord
    import os
    from discord.ext import commands
    
    bot = commands.Bot(command_prefix="$", case_insensitive=True)
    
    
    @bot.event
    async def on_ready():
        print(f"Logged in as {bot.user}")
    
    
    @bot.command()
    async def response(ctx):
        sent_message = await ctx.channel.send("Waiting for response...")
        res = await bot.wait_for(
            "message",
            check=lambda x: x.channel.id == ctx.channel.id
            and ctx.author.id == x.author.id
            and x.content.lower() == "yes"
            or x.content.lower() == "no",
            timeout=None,
        )
    
        if res.content.lower() == "yes":
            await sent_message.edit(content=f"{ctx.author} said yes!")
        else:
            await sent_message.edit(content=f"{ctx.author} said no!")
    
    
    bot.run(os.getenv("DISCORD_TOKEN"))
    

    这会得到相同的结果。

    【讨论】:

    • 我已经知道 wait_for 命令,但我不知道如何同时监听多个事件,所以这正是我要找的。谢谢!
    猜你喜欢
    • 2021-06-22
    • 2023-03-14
    • 2021-10-13
    • 2021-06-27
    • 2019-08-22
    • 2020-09-01
    • 1970-01-01
    • 2021-08-13
    • 2020-02-23
    相关资源
    最近更新 更多