首页 > 解决方案 > 当对消息添加反应时,我如何 DM 用户?

问题描述

将用户的反应与向他们发送 DM 相结合让我很难过。

我的项目通过在底部添加一个反应的嵌入来工作,当用户单击表情符号时,它将向用户发送一组说明(现在我只是使用“测试”这个词)。

这是我到目前为止所拥有的:

@client.event
async def on_message(message):
    if message.content.startswith('.add'):
        embed = discord.Embed(title="Embed Title", color=0x6610f2)
        embed.add_field(name="__**Steps to get DM'd:**__", value=""" 
        • Step 1
        • Step 2
        • Step 3
        • Step 4
        • Step 5
        """)
        
        msg = await message.channel.send(embed=embed)
        await msg.add_reaction('\U0001F91D')

@client.event
async def on_raw_reaction_add(payload):
    if payload.user_id == client.user.id:
        return

    if str(payload.emoji) == '\U0001F91D':
        channel = await client.fetch_channel(payload.channel_id)
        message = await channel.fetch_message(payload.message_id)

        await message.author.send('Test')

我只是不确定如何在 on_message() 函数之外获取用户 ID,因为我知道如何使 on_reaction_add 工作的唯一方法是在它自己的客户端事件中。我什至不确定我是否正确处理了 DM 用户方面。

使用 Discord.py 的异步版本

标签: pythondiscord.py

解决方案


在您的payload中,您应该已经获得了discord.Member可以使用的对象。尝试类似的东西

@client.event
async def on_raw_reaction_add(payload):
    if str(payload.emoji) == "\U0001F91D":
        member = payload.member
        await member.send('This is a DM to you!')

因为您的代码不检查消息 ID,所以对任何消息(不仅仅是您发送的消息)的反应都会导致响应。为了防止这种情况,您可以检查是否payload.message_id与您的机器人消息的 id 匹配(您可以在发送消息时将其存储在某处)。

您还试图阻止对机器人的初始反应做出响应。payload.user_id我建议不要检查

if member.bot:
    return

这可以防止对任何对您的消息做出反应的机器人做出响应,包括您自己的。


推荐阅读