首页 > 解决方案 > discord.py 1.3.2:如何在用户按下表情符号反应时检测和执行代码

问题描述

在我制作的不和谐机器人中,我在调用函数时将此字段编码为输出,$track_win并在该字段下方添加了许多反应。

@bot.command()
async def track_win(ctx):
    embed = discord.Embed(title = "Individual Win Tracker", description = "Click on any of the following emojis corresponding to the winner", color =0xeee657)
    embed.add_field(name = "Afif:", value = ":joy:")
    embed.add_field(name = "Faisal:", value = ":rage:")
    embed.add_field(name = "Irfan:", value = ":open_mouth:")
    embed.add_field(name = "Mahdi:", value = ":pensive:")
    embed.add_field(name = "Maruf:", value = ":unamused:")
    embed.add_field(name = "Nasseef:", value = ":sob:")
    message = await ctx.send(embed = embed)
    await message.add_reaction('\U0001F602')
    await message.add_reaction('\U0001F621')
    await message.add_reaction('\U0001F62E')
    await message.add_reaction('\U0001F614')
    await message.add_reaction('\U0001F612')
    await message.add_reaction('\U0001F62D')

现在,一旦用户按下其中一个反应,我想执行一组功能。你能告诉我我能做到这一点的方法吗?

看到这个 Stack Overflow question中的答案,我这样做了:

@client.event
async def on_reaction_add(reaction,user):
    if reaction.emoji == '\U0001F602': #all of the functions that I wanted to execute are given below
            fo = open("/storage/emulated/0/afif.txt", "r") 
            wins = fo.read()
            afif = int(str(wins)) + 1
            fo.close()
            fo = open("/storage/emulated/0/afif.txt", "w+")
            fo.write(str(afif))
            fo.close()
            print(afif)

然而,虽然这种方法似乎不起作用,但也没有抛出异常。我无法完全理解discord.py 文档

那么你能给我一个例子来说明我如何做到这一点吗?

提前致谢!

标签: pythonevent-handlingdiscorddiscord.pydiscord.py-rewrite

解决方案


推荐阅读