Section titled Audit logsAudit logs
Section titled A Quick BackgroundA Quick Background
Audit logs are an excellent moderation tool offered by Discord to know what happened in a server and usually by whom. Making use of audit logs requires the ViewAuditLog
permission. Audit logs may be fetched on a server, or they may be received via the gateway event Client#guildAuditLogEntryCreate which requires the GuildModeration
intent.
There are quite a few cases where you may use audit logs. This guide will limit itself to the most common use cases. Feel free to consult the relevant Discord API page for more information.
Keep in mind that these examples explore a straightforward case and are by no means exhaustive. Their purpose is to teach you how audit logs work, and expansion of these examples is likely needed to suit your specific use case.
Section titled Fetching Audit LogsFetching Audit Logs
Let's start by glancing at the Guild#fetchAuditLogs() method and how to work with it. Like many discord.js methods, it returns a Promise containing the GuildAuditLogs object. This object has one property, entries
, which holds a Collection of GuildAuditLogsEntry objects, and consequently, the information you want to retrieve.
Here is the most basic fetch to look at some entries.
_10const fetchedLogs = await guild.fetchAuditLogs();_10const firstEntry = fetchedLogs.entries.first();
Simple, right? Now, let's look at utilizing its options:
_10import { AuditLogEvent } from 'discord.js';_10_10const fetchedLogs = await guild.fetchAuditLogs({_10 type: AuditLogEvent.InviteCreate,_10 limit: 1,_10});_10_10const firstEntry = fetchedLogs.entries.first();
This will return the first entry where an invite was created. You used limit: 1
here to specify only one entry.
Section titled Receiving Audit LogsReceiving Audit Logs
Audit logs may be received via the gateway event Client#guildAuditLogEntryCreate. This is the best way to receive audit logs if you want to monitor them. As soon as an audit log entry is created, your application will receive an instance of this event. A common use case is to find out who did the action that caused the audit log event to happen.
Section titled Who deleted a message?Who deleted a message?
One of the most common use cases for audit logs is understanding who deleted a message in a Discord server. If a user deleted another user's message, you can find out who did that as soon as you receive the corresponding audit log event.
Messages deleted by their author or bots (excluding bulk deletes) do not generate audit log entries.
With this, you now have a very simple logger telling you who deleted a message authored by another person.
Section titled Who kicked a user?Who kicked a user?
This is very similar to the example above.
If you want to check who banned a user, it's the same example as above except the action
should be AuditLogEvent#MemberBanAdd. You can check the rest of the possible actions on this page.