如何追蹤discord.js中刪除訊息的使用者?
P粉760675452
P粉760675452 2023-08-29 17:00:40
0
1
639
<p>我剛開始學習如何創建discord機器人,我正在努力弄清楚如何記錄誰刪除了一條訊息。 </p> <p>我嘗試了<code>message.author</code>,但當然,那會記錄發送訊息的人,而我不知道很多語法,所以沒有嘗試其他任何東西。 </p>
P粉760675452
P粉760675452

全部回覆(1)
P粉709307865

您可以使用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}.`);
  }
});
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板