discord.py 1.3.2:如何在用户按下表情符号时检测并执行代码

2024-10-03 09:21:22 发布

您现在位置:Python中文网/ 问答频道 /正文

在我制作的discord bot中,我在调用$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')

现在我想在用户按下其中一个按钮后执行一组函数。你能告诉我怎样才能做到这一点吗

看到this 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 documentation

那么,你能给我一个例子来说明如何实现这一点吗

提前谢谢


Tags: thenameaddfieldmessagevaluebottrack