You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

discord.py实现Discord机器人给自己发送的消息添加表情反应求助

问题原因

你当前代码中调用add_reaction的对象是用户发送的触发指令的消息,没有获取到机器人自身发送的消息对象,所以反应只会添加在用户消息上。

修改方案
  1. 调用channel.send()时将返回值存储为变量,这个返回值就是机器人刚发送的消息的实例对象
  2. 对该实例对象调用add_reaction()方法即可给机器人自己的消息加反应
完整修改后代码
from inspect import CO_NESTED
from typing import Literal
from discord.ext import commands
import discord
import random
import asyncio
import time

TOKEN = "xxx"

# discord.py 2.x 版本需要显式声明intents,旧版本可以去掉这部分直接用原来的client声明
intents = discord.Intents.default()
intents.message_content = True # 需同时在Discord开发者后台的Bot设置页开启Message Content Intent开关
client = discord.Client(intents=intents)

@client.event
async def on_ready():
    print('We have logged in as {0.user}'.format(client))

@client.event
async def on_message(message):
    username = str(message.author).split('#')[0]
    user_message = str(message.content)
    channel = str(message.channel.name)
    print(f'{username}: {user_message} ({channel})')

    if message.author == client.user:
        return
    
    if "p!react" in user_message.lower():
        # 存储机器人发送的消息对象
        bot_sent_msg = await message.channel.send("hello!")
        # 给机器人自身发送的消息添加表情反应
        await bot_sent_msg.add_reaction("📰")
        # 如果不需要给用户触发消息加反应,可以删掉下面这行
        await message.add_reaction("📰")


client.run(TOKEN)

内容的提问来源于stack exchange,提问作者EpicEfeathers

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 20:45:02