在Discord Python中后台等待反应

0 投票
2 回答
1551 浏览
提问于 2025-06-18 03:58

我有一个机器人,每当提到某个特定用户的名字时,它就会向频道发送一条特定的消息(使用 on_message())。如果我觉得烦了,想让它停止发送消息,我只需要在它发的消息上点个差评,时间在两分钟内,这样它就会停止。

现在,我还有一个命令,可以接受那个人的名字作为参数,比如 .command @person_name。我的问题是,当我用那个特定人的名字调用命令时,机器人会先发送反应消息(这没问题),然后它会等整整两分钟来看看有没有反应,等到超时后才会继续执行 command 的内容。我该如何让 waitfor() 函数在后台运行呢?

以下是我代码的大致内容:

async def on_message(message):
    if "person_name" in message.content:
        await message.channel.send("sample reaction message")
        await fun()                                    #check for reaction

    ...                                                #other things
    await bot.process_commands(message)

async def fun(message):
    content = message.content
    channel = message.channel

    global VARIABLE                                   #this variable decides whether the bot should react to the person's name

    def check(reaction,user):
        return user.id == bot.owner_id and str(reaction.emoji) == ''

    try: reaction,user = await bot.wait_for('reaction_add',timeout = (60 * 2),check=check)
    except asyncio.TimeoutError: pass
    else:
        if str(reaction.emoji) == '':
            VARIABLE = False                           #disable the reaction message
            await channel.send(" Okay, I'll stop.")

相关问题:

  • 暂无相关问题
暂无标签

2 个回答

1

因为你正在使用检查函数

 def check(reaction,user):
        return user.id == bot.owner_id and str(reaction.emoji) == ''

并且确认这个反应 '' 是否被添加了,所以你不需要后面这个if语句

if str(reaction.emoji) == '':

--------------------------------更新------------------------------------

如果你仍然需要验证一个表情符号

try:
    reaction_check = await bot.wait_for('reaction_add',check=check,timeout=15)
    emoji = f"{reaction_check}"
    emoji = emoji[emoji.find("(<Reaction emoji=")+len("(<Reaction emoji="):emoji.find("me")]
except:
    emoji = '✅'
if emoji.find('') != -1:
    print("code")

**

  • 更新 2

**

try:
        reaction_check = await bot.wait_for('reaction_add',check=check,timeout=15)
# since **`reaction_check`** yeilds a tuple
        emoji = reaction_check[0] #yeilds the emoji that was used in reaction
    except:
        emoji = '✅'
    if str(emoji) == '':
        print("code")
1

使用 on_reaction_add 这个事件可以让你实现这个功能。不过,我建议不要使用全局变量。这个事件会在有人对一个缓存的消息做出反应时触发。如果你希望在机器人重启后这个功能仍然有效,你应该使用on_raw_reaction_add

把这个函数添加到你的机器人代码里:

async def on_reaction_add(reaction, user):
    if bot.is_owner(user) and str(reaction.emoji) == "":
        VARIABLE = False

撰写回答