【问题标题】:Python discord bot message defined problemPython discord bot消息定义问题
【发布时间】:2021-08-12 16:12:39
【问题描述】:

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

【问题讨论】:

  • 错误告诉你问题出在哪里?您正在使用message.author.mention, message.contentmessage.channel.send,但message 没有以任何方式定义。

标签: python discord discord.py bots


【解决方案1】:

您的问题是 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("✔️")

【讨论】:

  • guild = Bot.get_guild() 你的意思是bot用户id还是我的?
  • 公会ID。如果您不希望它是静态的,请像这样使用payload.guild_idguild = Bot.get_guild(payload.guild_id)
  • 哦,谢谢。它已被修复。但是另一个问题就变成了。它发送消息相同的频道。如何选择频道?
  • 然后使用await guild.get_channel(&lt;channel-id&gt;).send("...") 将其发送到所需的频道,其中 必须替换为实际的频道 ID。如果它不能立即起作用,可能会就此提出另一个问题。
  • 哦,非常感谢您,先生。最后一个问题。我怎样才能得到“表情符号”的数量?例如,如果 n 次得到“表情符号”,那么就做 bla bla。我必须使用 len() 函数吗?
猜你喜欢
  • 1970-01-01
  • 2021-03-27
  • 2021-10-30
  • 2020-11-17
  • 2018-07-07
  • 2020-02-20
  • 2019-07-04
  • 2020-11-07
  • 2020-08-25
相关资源
最近更新 更多