首页 > 解决方案 > Python discord bot消息定义问题

问题描述

我正在尝试构建一个检测特定表情符号的机器人。当机器人得到这个时,它会将消息移动到特定的频道。例如,如果消息反应有“like_emoji”,则必须将此消息内容移动到“xxx”频道。我在 stackoverflow 上找不到任何解决方案(或者我可能没有更深入地搜索)。

这是我的代码:

import os
import sys
import discord
from discord.ext import commands

my_secret = os.environ['locksecret']

intents = discord.Intents.default()
intents = discord.Intents(messages=True,guilds=True,reactions=True,members=True,presences=True)

Bot = commands.Bot(command_prefix = "!",intents=intents)
@Bot.event
async def on_reaction_add(reaction,user):
  channel = reaction.message.channel
  await channel.send("emoji added")
  if reaction.emoji == '':
    channel = Bot.get_channel("channel_id")
    await channel.send("{} written by:\n {}".format(message.author.mention,message.content))
    await message.channel.send("{} your message move to this channel --> {}".format(message.author.mention,channel.mention))
    await message.add_reaction("✔️")
Bot.run(my_secret)

当我这样做时,我得到这个错误:

***Ignoring exception in on_reaction_add
Traceback (most recent call last):
  File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event
    await coro(*args, **kwargs)
  File "main.py", line 57, in on_reaction_add
    await channel.send("{} written by:\n {}".format(message.author.mention,message.content))
NameError: name 'message' is not defined***

我怎么解决这个问题?顺便说一句,在代码空间中,有一些代码我尝试使用 bot 命令,因此,控制台显示“第 57 行”

标签: pythondiscorddiscord.pybots

解决方案


您的问题是message没有定义,就像您的错误状态一样。该on_reaction_add事件不提供添加反应的消息。您应该改用该on_raw_reaction_add事件


@Bot.event
async def on_raw_reaction_add(payload):
    guild = Bot.get_guild(<your-guild-id>)
    channel = guild.get_channel(payload.channel_id)
    message = await channel.fetch_message(payload.message_id)
    await channel.send("emoji added")
    if payload.emoji.name == '':
      await channel.send("{} written by:\n {}".format(message.author.mention,message.content))
      await message.channel.send("{} your message move to this channel --> {}".format(message.author.mention,channel.mention))
      await message.add_reaction("✔️")

推荐阅读