Why bot security matters

A compromised Discord bot can delete channels, ban members, leak private messages, and destroy a community in seconds. Bot tokens are the number one target for attackers because a single leaked token gives full access to everything your bot can do. Security is not optional. It is the foundation that every other feature depends on.

This guide covers the practical security measures every Discord bot developer should implement, from basic token management to advanced hosting hardening. Whether your bot serves one server or hundreds, these practices protect both you and your users.

Token management

Your bot token is equivalent to a password that never expires and provides full access to your bot's Discord account. Treat it with the same care you would treat a banking password.

Never hardcode tokens

The single most common security mistake is putting your bot token directly in your source code. This means anyone who sees your code sees your token. If your repository is public, your token is public. Even in private repositories, hardcoded tokens end up in git history permanently.

Instead, use environment variables. Store your token in a .env file that is excluded from version control, and load it at runtime. For a detailed guide on setting this up, read our environment variables guide.

Node.js example

// Install: npm install dotenv
require('dotenv').config();

const { Client, GatewayIntentBits } = require('discord.js');
const client = new Client({ intents: [GatewayIntentBits.Guilds] });

// Token loaded from .env file, never from source code
client.login(process.env.DISCORD_TOKEN);

Python example

# Install: pip install python-dotenv
import os
from dotenv import load_dotenv
import discord

load_dotenv()

client = discord.Client(intents=discord.Intents.default())
client.run(os.getenv('DISCORD_TOKEN'))

Your .env file

DISCORD_TOKEN=your_token_here

Your .gitignore must include

.env
*.env
.env.*

What to do if your token leaks

  1. Regenerate immediately. Go to the Discord Developer Portal, select your application, navigate to the Bot section, and click Reset Token. This invalidates the old token instantly.
  2. Update your hosting. Deploy the new token to your hosting environment. On MonkeyBytes, update the environment variable in your dashboard or re-upload your .env file via SFTP.
  3. Audit your bot's actions. Check your server's audit log for any actions your bot performed that you did not initiate. Look for channel deletions, role changes, mass bans, or message deletions.
  4. Check git history. If the token was committed to a repository, it exists in the git history even after you remove it from the current code. Consider the repository compromised. For public repos, rotate any other secrets that were in the same repository.

Permission configuration

Discord's permission system is your primary access control mechanism. A bot should only request the permissions it actually needs. Over-permissioning is a security risk because it increases the damage a compromised bot can do.

Principle of least privilege

When generating your bot's invite link, only enable the permissions your bot requires for its current features. A moderation bot needs kick and ban permissions. A music bot needs voice channel permissions. Neither needs administrator access.

The Administrator permission grants every other permission automatically. Never request it unless your bot genuinely needs every single Discord permission. Most bots do not.

Common permission sets by bot type

Bot type Required permissions Not needed
Moderation bot Kick Members, Ban Members, Manage Messages, View Audit Log Administrator, Manage Server, Manage Channels
Welcome bot Send Messages, Manage Roles (for auto-role), View Channels Administrator, Kick/Ban Members
Utility bot Send Messages, Embed Links, Read Message History Administrator, Manage anything
Music bot Connect, Speak, View Channels, Send Messages Administrator, Manage Members

Gateway intents

Similar to permissions, only enable the gateway intents your bot needs. Privileged intents like Message Content, Server Members, and Presence require explicit approval from Discord for verified bots and should only be enabled if your bot processes that data. Requesting unnecessary intents is both a privacy concern and a performance overhead. For more on intent configuration, see our troubleshooting guide.

Dependency security

Your bot depends on third-party packages. Each dependency is code you did not write and must trust. Supply chain attacks, where malicious code is injected into popular packages, are a growing threat in both the npm and PyPI ecosystems.

Keep dependencies updated

Outdated packages often contain known vulnerabilities. Run regular dependency audits:

# Node.js
npm audit
npm update

# Python
pip list --outdated
pip install --upgrade discord.py

Lock your dependency versions

Use a lockfile (package-lock.json for Node.js, requirements.txt with pinned versions for Python) to ensure consistent installations. Without a lockfile, running npm install or pip install might pull a newer version of a package that introduces breaking changes or malicious code.

Audit before installing new packages

Before adding a new dependency, check its download count, last update date, maintainer reputation, and open issues. A package with 12 weekly downloads and no updates in two years is a higher risk than an actively maintained package with millions of downloads.

Minimise your dependency tree

Every dependency you add increases your attack surface. Before installing a package, ask whether you can achieve the same result with built-in language features or a smaller, more focused library. A bot that depends on 200 packages has 200 potential points of failure.

Input validation and command safety

If your bot accepts user input, that input is untrusted by default. Never pass user input directly to system commands, database queries, or file operations without validation and sanitisation.

Prevent command injection

If your bot executes any system commands based on user input, you are at risk of command injection. A user sending ; rm -rf / as part of a command argument could be catastrophic if the input is not sanitised. The safest approach is to never execute system commands based on user input. If you must, use parameterised execution and strict input validation.

Sanitise for display

User-provided content displayed in embeds or messages should be sanitised to prevent Discord markdown injection. While this is not a traditional security vulnerability, it can be used to create misleading messages that appear to come from your bot. Strip or escape any Discord formatting characters from user input before displaying it.

Rate limit your commands

Implement per-user cooldowns on commands that perform expensive operations, make API calls, or interact with databases. Without rate limiting, a single user can overwhelm your bot's resources or cause it to hit Discord's API rate limits, effectively creating a denial of service for all users.

Hosting security

Your hosting environment is the foundation your bot runs on. A secure bot on an insecure server is still vulnerable.

Managed hosting security advantages

Managed hosting platforms handle the majority of infrastructure security for you. MonkeyBytes uses Docker container isolation, which means each bot runs in its own sandboxed environment. One user's bot cannot access another user's files, processes, or network connections. TLS encryption protects all connections, and environment variables are stored securely within the container. Read more about our security features.

VPS security checklist

If you host on a VPS, you are responsible for server security. At minimum, implement these measures:

  • Disable root SSH login. Create a regular user account, add it to the sudo group, and disable root login in /etc/ssh/sshd_config.
  • Use SSH key authentication. Disable password authentication entirely. SSH keys are significantly more secure than passwords.
  • Configure a firewall. Use ufw or iptables to block all ports except those you explicitly need (typically 22 for SSH).
  • Install fail2ban. This automatically blocks IP addresses that make too many failed login attempts.
  • Enable automatic security updates. Configure unattended-upgrades on Debian/Ubuntu to automatically install security patches.
  • Run your bot as a non-root user. Never run your bot process as root. Create a dedicated user for the bot with minimal permissions.

For a comparison of VPS versus managed hosting security trade-offs, see our VPS vs free hosting comparison.

Logging and monitoring

You cannot secure what you cannot observe. Implement logging and monitoring to detect security incidents early.

What to log

  • Bot startup and shutdown events
  • Authentication failures and token validation errors
  • Permission denied errors
  • Unusual patterns like rapid command execution from a single user
  • Guild join and leave events
  • Error stack traces (with sensitive data redacted)

What not to log

  • User message content (privacy concern, potentially illegal depending on jurisdiction)
  • Tokens, API keys, or secrets in any form
  • Full IP addresses of users (GDPR considerations)

Monitoring your bot

Use the real-time console on MonkeyBytes to monitor your bot's output, or set up external monitoring to track uptime and response times. For a comprehensive guide on monitoring options, read our uptime monitoring guide.

Data protection and privacy

If your bot stores any user data, you have a responsibility to protect it. In many jurisdictions, you also have legal obligations under regulations like GDPR.

Minimise data collection

Only collect and store data your bot actually needs to function. If your moderation bot logs warnings, you need the user ID and the warning reason. You do not need their message history, avatar URL, or status information.

Secure data storage

If you use SQLite or file-based storage, ensure the files are not publicly accessible. On managed hosting like MonkeyBytes, your files are isolated by default. On a VPS, verify file permissions and ensure your data directory is not served by a web server.

Provide data deletion

Users should be able to request deletion of their data. Consider implementing a command that lets users remove their stored information. This is both good practice and may be a legal requirement depending on where your users are located.

Security checklist

Use this checklist to verify your bot's security posture:

  • Token stored in environment variable, not in code
  • .env file excluded from version control via .gitignore
  • Bot requests only necessary permissions, not Administrator
  • Only required gateway intents are enabled
  • Dependencies are up to date and audited
  • Dependency versions are locked via lockfile
  • User input is validated before processing
  • No user input is passed to system commands
  • Rate limiting is implemented on resource-intensive commands
  • Logging captures security-relevant events
  • No secrets appear in logs
  • Hosting environment is properly secured
  • Data collection is minimised
  • Users can request data deletion

Security is not a one-time task. Review these practices regularly, keep your dependencies updated, and stay informed about new threats in the Discord bot ecosystem. For help with common bot issues, visit our troubleshooting guide, or get started with secure hosting on MonkeyBytes.

Guide Complete Hosting Guide Guide Bot Troubleshooting Comparison VPS vs Free Hosting Features Platform Security Features