pyhton discord bot 消息定义问题

时间:2021-05-24 10:41:31

标签: python discord discord.py bots

我正在尝试构建一个检测特定表情符号的机器人。当机器人收到此信息时,它会将消息移动到特定频道。例如,如果消息反应有“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 行”

1 个答案:

答案 0 :(得分:2)

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


@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("✔️")