P粉7093078652023-08-30 15:32:16
您可以使用messageDelete
事件,該事件在訊息被刪除時觸發。您可以檢查審核日誌,以查看使用者是否刪除了其他使用者的消息。
首先,確保您具有所需的意圖:Guilds
,GuildMembers
和GuildMessages
。您還需要partials
:Channel
,Message
和GuildMember
,以處理在您的機器人上線之前發送的訊息。
一旦訊息被刪除,您可以使用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}.`); } });