首页 > 解决方案 > discord.py 编辑了消息记录问题

问题描述

因此,我编写了一些代码,允许我将编辑的消息记录到某个频道。这是代码:

async def on_message_edit(message_before, message_after):
    embed=discord.Embed(title="{} edited a message".format(message_before, message.author), description="", color=0xFFFF00)
    embed.add_field(name= message_before.content ,value="This is the message before the edit:", inline=True)
    embed.add_field(name= message_after.content ,value="This is the message after the edit", inline=True)
    channel=bot.get_channel(747057143630528563)
    await channel.send(embed=embed) 

但是,当我运行代码时,我收到错误消息:

忽略 on_message_edit Traceback 中的异常(最后一次调用):文件“C:\Users\jackt\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py”,第 333 行,_run_event 等待coro(*args, **kwargs) 文件“C:\Users\jackt\Desktop\bot.py”,第 92 行,on_message_edit embed=discord.Embed(title="{} 编辑了一条消息".format(message_before, message.author), description="", color=0xFFFF00) NameError: name 'message' is not defined

我需要更改代码的哪一部分,我需要对其进行哪些更改?谢谢。

标签: pythondiscord.py

解决方案


discord.Embed(title="{} edited a message".format(message_before, message.author), description="", color=0xFFFF00)

实际上应该是

discord.Embed(title="{} edited a message".format(message_before.author.name), description="", color=0xFFFF00)

您之前收到错误的原因message is not defined是因为您在此处添加了逗号:message_before, message.author. 这使python认为它们是两个不同的语句,使其尝试访问消息变量(不存在)。

相反,您应该访问 message_before 对象。我添加.name以检索名称,就像使用.author只会添加一个用户对象一样。如果您只想提及用户,则可以替换.name.mention.

编辑:还在@bot.event函数顶部添加,以便在消息编辑时调用它。代码应如下所示:

@bot.event
async def on_message_edit(message_before, message_after):
    discord.Embed(title="{} edited a message".format(message_before.author.name), description="", color=0xFFFF00)
    embed.add_field(name= message_before.content ,value="This is the message before the edit:", inline=True)
    embed.add_field(name= message_after.content ,value="This is the message after the edit", inline=True)
    channel=bot.get_channel(747057143630528563)
    await channel.send(embed=embed) 

推荐阅读