I've only just started to learn how to create discord bots and I'm struggling to figure out how to log who deleted a message.
I tried message.author but of course, that would log who sent the message and I didn't know many syntaxes so I didn't try anything else.
You can use the messageDelete event that fires whenever a message is deleted. You can check the audit logs if a user deleted another user's message.
First, make sure you have the required intents: Guilds, GuildMembers, and GuildMessages. You will also need partials: Channel, Message and GuildMember to work with messages sent before your bot got online.
Once a message is deleted, you can use the fetchAuditLogs method to fetch the audit logs for the guild the deleted message was sent in.
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}.`);
  }
});
In discord.js v14.8+ there is a new event, GuildAuditLogEntryCreate. You can find out who deleted a message as soon as you receive the corresponding audit log event (GuildAuditLogEntryCreate). It requires the GuildModeration intent to be enabled.
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}.`);
  }
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With