如何在discord.js中记录删除消息的用户?

4

我刚开始学习如何创建Discord机器人,但我很难弄清楚如何记录删除消息的人。

我尝试了message.author,但当然,那会记录发送消息的人,而我不知道许多语法,所以我没有尝试其他任何东西。

1个回答

2

您可以使用messageDelete事件,该事件在删除消息时触发。如果用户删除了另一个用户的消息,您可以检查审核日志。

首先,请确保您具有所需的意图:GuildsGuildMembersGuildMessages。您还需要partialsChannelMessageGuildMember以处理在您的机器人上线之前发送的消息。

一旦消息被删除,您可以使用fetchAuditLogs方法来获取已删除消息所在公会的审核日志。

const client = new Client({
  intents: [
    GatewayIntentBits.Guilds,
    GatewayIntentBits.GuildMembers,
    GatewayIntentBits.GuildMessages,
  ],
  partials: [
    Partials.Channel,
    Partials.GuildMember,
    Partials.Message,
  ],
});

client.on('messageDelete', async (message) => {
  const logs = await message.guild.fetchAuditLogs({
    type: AuditLogEvent.MessageDelete,
    limit: 1,
  });
  // logs.entries is a collection, so grab the first one
  const firstEntry = logs.entries.first();
  const { executorId, target, targetId } = firstEntry;
  // Ensure the executor is cached
  const user = await client.users.fetch(executorId);

  if (target) {
    // The message object is in the cache and you can provide a detailed log here
    console.log(`A message by ${target.tag} was deleted by ${user.tag}.`);
  } else {
    // The message object was not cached, but you can still retrieve some information
    console.log(`A message with id ${targetId} was deleted by ${user.tag}.`);
  }
});

在 discord.js v14.8+ 中,有一个新的事件叫做 GuildAuditLogEntryCreate。当你收到相应的审计日志事件 (GuildAuditLogEntryCreate) 时,你可以立即找出谁删除了一条消息。这需要启用 GuildModeration 意图。
const { AuditLogEvent, Events } = require('discord.js');

client.on(Events.GuildAuditLogEntryCreate, async (auditLog) => {
  // Define your variables
  const { action, executorId, target, targetId } = auditLog;

  // Check only for deleted messages
  if (action !== AuditLogEvent.MessageDelete) return;

  // Ensure the executor is cached
  const user = await client.users.fetch(executorId);

  if (target) {
    // The message object is in the cache and you can provide a detailed log here
    console.log(`A message by ${target.tag} was deleted by ${user.tag}.`);
  } else {
    // The message object was not cached, but you can still retrieve some information
    console.log(`A message with id ${targetId} was deleted by ${user.tag}.`);
  }
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接