How to Use Discord Bot Audit Log Read for Custom Mod Tools
🔍 WiseChecker

How to Use Discord Bot Audit Log Read for Custom Mod Tools

Discord’s audit log records every moderation action, permission change, and server setting update. By default, only server administrators and members with the View Audit Log permission can see these logs in the server settings. If you want to build a custom moderation tool that monitors, filters, or alerts on specific audit log events without granting full access to the server settings, you need your bot to use the Audit Log Read intent. This article explains how to enable the intent, write code to fetch audit log entries, and build a simple custom moderation dashboard using Discord.js.

Key Takeaways: Using Discord Bot Audit Log Read for Custom Mod Tools

  • Discord Developer Portal > Bot > Privileged Gateway Intents > Server Members Intent: Enable this intent to allow your bot to read audit log entries.
  • Discord.js Guild.fetchAuditLogs() method: Use this method to fetch audit log entries programmatically in your bot code.
  • Audit log event types like MEMBER_KICK, MEMBER_BAN, CHANNEL_OVERWRITE_CREATE: Filter these specific events to build custom moderation alerts and dashboards.

ADVERTISEMENT

What the Audit Log Read Intent Does and Why You Need It

Discord’s audit log is a built-in feature that records actions like member kicks, bans, role changes, channel edits, and permission updates. By default, users with the View Audit Log permission can see these entries in Server Settings > Audit Log. When you build a custom moderation bot, you often need to read these logs automatically — for example, to send a real-time alert when a member is banned or to generate a weekly report of moderation actions.

To access audit log entries from your bot, you must enable the Server Members Intent in the Discord Developer Portal. This privileged intent tells Discord that your bot will request audit log data. Without it, the fetchAuditLogs() method will return an empty array or throw an error. Once enabled, your bot can read any audit log entry that the bot user has permission to see — typically, the bot needs the View Audit Log permission itself.

The audit log provides detailed information for each entry: the action type (like MEMBER_KICK), the user who performed the action, the target user or object, the time of the action, and optional reason text. By filtering on action types, you can create targeted alerts — for instance, only log bans and kicks, or only permission changes.

Steps to Enable Audit Log Read for Your Discord Bot

Follow these steps to set up your bot to read audit log entries. You need a bot already created in the Discord Developer Portal and a basic Discord.js bot project running on Node.js.

  1. Enable the Server Members Intent in the Developer Portal
    Go to the Discord Developer Portal and select your bot application. In the left menu, click Bot. Scroll down to Privileged Gateway Intents. Toggle on Server Members Intent. Click Save Changes at the bottom of the page. This intent is required to fetch audit log entries.
  2. Invite the Bot with the View Audit Log Permission
    Use the OAuth2 URL Generator in the Developer Portal. Under Scopes, select bot. Under Bot Permissions, select View Audit Log. Copy the generated URL and open it in a browser to invite the bot to your server. Without this permission, the bot cannot read audit log entries even with the intent enabled.
  3. Install Discord.js v14 or Later
    In your bot project folder, run npm install discord.js@14. Discord.js v14 includes full support for audit log fetching with the GuildAuditLogs class. If you use an older version, update your package.json and reinstall.
  4. Write Code to Fetch Audit Log Entries
    In your bot’s main file, add a command or event handler that calls guild.fetchAuditLogs(). For example, to fetch the last 10 entries and log their action types:
    const auditLogs = await guild.fetchAuditLogs({ limit: 10 });
    auditLogs.entries.forEach(entry => console.log(entry.action));

    This code retrieves the most recent 10 audit log entries and prints their action type constants like MEMBER_KICK or CHANNEL_CREATE.
  5. Filter by Specific Action Types for Custom Mod Tools
    To build a custom moderation dashboard, filter entries by action type. For example, to only process kicks and bans:
    const filteredEntries = auditLogs.entries.filter(entry =>
    entry.action === 'MEMBER_KICK' || entry.action === 'MEMBER_BAN'
    );

    You can then send these entries to a specific channel, store them in a database, or trigger a webhook.
  6. Handle Errors and Rate Limits
    Wrap your fetch call in a try-catch block. If the bot lacks the View Audit Log permission, the fetch will throw a DiscordAPIError with code 50013 (Missing Permissions). Also, audit log fetching is rate-limited to 5 requests per 5 seconds per guild. Use a queue or delay if you need to fetch logs frequently.

ADVERTISEMENT

Common Issues When Building Custom Mod Tools with Audit Logs

Bot Returns Empty Array or No Entries

If your bot fetches audit logs but receives an empty array, check two things. First, confirm the bot has the View Audit Log permission on the server. Second, verify that the Server Members Intent is enabled in the Developer Portal. Also, note that audit logs older than 90 days are automatically deleted by Discord, so if the server has no recent actions, the array will be empty.

Missing Permissions Error (50013)

This error occurs when the bot attempts to fetch audit logs without the View Audit Log permission. Re-invite the bot with the correct permission using the OAuth2 URL generator. You can also verify the bot’s role in Server Settings > Roles — ensure the role has the View Audit Log permission checked.

Rate Limiting When Fetching Logs Frequently

Discord enforces a rate limit of 5 audit log fetch requests per 5 seconds per guild. If your bot needs to poll logs continuously, implement a delay between requests or use a queue system. For real-time alerts, consider using Discord’s Gateway events like GUILD_AUDIT_LOG_ENTRY_CREATE (available with the Audit Log Event intent) instead of polling.

Audit Log Action Types: Common Events for Custom Mod Tools

Action Type What It Records Use Case for Mod Tools
MEMBER_KICK When a member is kicked from the server Alert mods in a private channel with member name and reason
MEMBER_BAN When a member is banned Log ban details including moderator and duration
MEMBER_UNBAN When a member is unbanned Track unban actions for appeal review
MEMBER_ROLE_UPDATE When a member’s roles are changed Monitor role assignments and removals
CHANNEL_CREATE When a channel or category is created Alert on new channel creation for review
CHANNEL_DELETE When a channel is deleted Log deletions for audit trail
CHANNEL_OVERWRITE_CREATE When permission overwrites are added to a channel Track permission changes that affect mod access
GUILD_UPDATE When server settings like name or verification level change Monitor critical server configuration changes

You can use the AuditLogEvent enum from Discord.js to reference these action types in your code. For a full list, see the Discord.js documentation.

Building a Simple Mod Alert Command

Here is a complete example of a Discord.js slash command that fetches the latest 5 audit log entries and sends them to a specific channel. This command filters for member kicks and bans only.

const { SlashCommandBuilder, EmbedBuilder } = require('discord.js');

module.exports = {
  data: new SlashCommandBuilder()
    .setName('modlog')
    .setDescription('Show recent moderation actions'),
  async execute(interaction) {
    try {
      const auditLogs = await interaction.guild.fetchAuditLogs({
        limit: 5,
        type: ['MEMBER_KICK', 'MEMBER_BAN']
      });
      if (auditLogs.entries.size === 0) {
        return interaction.reply('No recent moderation actions found.');
      }
      const embed = new EmbedBuilder()
        .setTitle('Recent Moderation Actions')
        .setColor(0xFF0000)
        .setTimestamp();
      auditLogs.entries.forEach(entry => {
        const moderator = entry.executor.username;
        const target = entry.target?.username || 'Unknown';
        const reason = entry.reason || 'No reason provided';
        embed.addFields({
          name: `${entry.action} - ${target}`,
          value: `Moderator: ${moderator}\nReason: ${reason}`
        });
      });
      await interaction.reply({ embeds:  });
    } catch (error) {
      console.error(error);
      await interaction.reply('Failed to fetch audit logs. Check bot permissions.');
    }
  }
};

This command uses the type parameter to filter only kicks and bans. You can extend it to include other action types by adding them to the array. The bot must have the View Audit Log permission and the Server Members Intent enabled.

Conclusion

You can now build a custom moderation tool that reads Discord audit logs programmatically using the Server Members Intent and the fetchAuditLogs() method in Discord.js. Start by enabling the intent in the Developer Portal and inviting the bot with the View Audit Log permission. Then use action type filtering to create targeted alerts for kicks, bans, role changes, or channel edits. For real-time monitoring, consider switching to the GUILD_AUDIT_LOG_ENTRY_CREATE gateway event instead of polling. This approach keeps your moderation data private and customizable without exposing the full server settings to every moderator.

ADVERTISEMENT