Your bot token is the single most important secret in your project. Anyone who has it can log in as your bot, with every permission you have given it, in every server it has joined. Tokens leak in boring ways: a public GitHub repo, a screenshot of your editor, a pasted error log in a help channel, a config file shared with a friend. This guide covers what an attacker can do with a leaked token, how to keep yours out of your code, and what to do in the first five minutes if it gets out.
What a leaked token allows
A bot token is not a password for your Discord account. It is a credential for the bot user itself. That limits the damage in one way (nobody gets into your personal account or your Developer Portal), but inside the servers your bot is in, the attacker is your bot. Whatever the bot can do, they can do:
- Destroy servers. With Administrator, or Manage Channels and Manage Roles, a script can delete every channel and role in seconds. This is the classic "nuke" and it is very hard to undo.
- Ban or kick members in bulk, if the bot has those permissions.
- Spam and phish. The bot can post in any channel it can see and DM members it shares a server with. Scam links sent from a trusted bot get clicked far more often than links from random accounts.
- Read messages. If the Message Content intent is enabled, the attacker can read everything the bot can see, including private staff channels.
- Get your bot banned. Abuse from your bot's account can lead Discord to disable the application, which takes it offline for everyone.
Attackers do not need to find your token by hand. Automated scanners watch public code sites and paste sites constantly, and a token pushed to a public repository can be abused within minutes.
Keep the token out of your code
The rule is simple: the token never appears in a file that gets committed, shared or screenshotted. Your code reads it from the environment at startup instead.
Use a .env file locally
Create a file named .env in your project folder:
DISCORD_TOKEN=paste-your-token-hereIn Node.js (discord.js), load it with the dotenv package, or with Node's built-in --env-file=.env flag on Node 20.6 and newer:
// npm install dotenv
require('dotenv').config();
const { Client, GatewayIntentBits } = require('discord.js');
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
client.login(process.env.DISCORD_TOKEN);In Python (discord.py, Pycord, Nextcord), use python-dotenv:
# pip install python-dotenv
import os
from dotenv import load_dotenv
import discord
load_dotenv()
token = os.getenv("DISCORD_TOKEN")
if not token:
raise SystemExit("DISCORD_TOKEN is not set")
client = discord.Client(intents=discord.Intents.default())
client.run(token)Checking that the variable exists gives you a clear error instead of a confusing login failure when it is missing.
Add .env to .gitignore before your first commit
A .env file only protects you if Git never sees it. Add it to .gitignore straight away:
# .gitignore
.env
.env.*
!.env.example
node_modules/
__pycache__/Commit a .env.example with the variable names and empty values instead, so anyone cloning the project knows what to set:
DISCORD_TOKEN=
DATABASE_URL=Run git status before committing and make sure .env is not listed. If you add .gitignore after the file was already committed, Git keeps tracking it. Remove it from the index with git rm --cached .env and commit that change.
Deleting the commit is not enough
If a token was ever pushed, assume it is compromised. Removing the line in a new commit leaves it in the history, forks and clones keep their copies, and scanners may have already grabbed it. Rewriting history with a tool like git filter-repo is good hygiene, but the only real fix is to regenerate the token.
GitHub secret scanning and automatic resets
Discord is a GitHub secret scanning partner. When a Discord bot token is pushed to a public GitHub repository or gist, GitHub notifies Discord, and Discord invalidates the token and sends the bot's owner a system message explaining that the token was found and reset. Your bot then fails to log in until you put a new token in place.
This is a useful safety net, but do not rely on it:
- It only covers public GitHub. Private repos, other code hosts, pastebins, Discord messages, screenshots and zip files you send to people are not covered.
- Other scanners are fast too, so there can be a window between the push and the reset.
- If your bot suddenly goes offline with an "invalid token" or "401 Unauthorized" error and you didn't change anything, check your Discord messages. A reset after a leak is a common cause.
How to regenerate a token
If you think your token has leaked, even if you are not sure, reset it. It takes a minute and costs nothing.
- Open the Discord Developer Portal and select your application.
- Go to the Bot page and click Reset Token. Confirm, and enter your two-factor code if asked.
- Copy the new token. Discord shows it only once. The old token stops working immediately, which disconnects anyone using it.
- Update the token wherever your bot runs: your local
.envand the variable on your host. Then restart the bot. - Check your servers for damage: audit logs, deleted channels, unexpected bans, new webhooks and messages posted by the bot.
Then work out how it leaked and close that gap, otherwise the new token will follow the old one. Also protect the account that owns the application with two-factor authentication. Anyone who gets into your Developer Portal can reset tokens and change your bot, so that login matters as much as the token itself.
Least privilege: limit the damage in advance
You can't make a leaked token harmless, but you can decide how much harm it can do. A bot that only has the permissions it actually needs is a much smaller prize.
Permissions
Avoid Administrator. It bypasses every channel override and turns a leak into a server wipe. Build your invite link in the Developer Portal's OAuth2 URL generator with only the permissions your commands use. A music bot needs Connect and Speak, not Ban Members. A logging bot needs View Channel and Send Messages in its log channel, not Manage Roles. Server owners can also keep the bot's role low in the role list, since a bot can't manage roles above its own.
| Bot type | Typical permissions | Usually not needed |
|---|---|---|
| Utility / slash commands | View Channels, Send Messages, Embed Links | Administrator, Manage Server |
| Moderation | Kick, Ban, Timeout Members, Manage Messages | Administrator, Manage Webhooks |
| Music | Connect, Speak, Send Messages | Manage Channels, Ban Members |
| Reaction roles | Manage Roles, Add Reactions | Administrator, Manage Channels |
Gateway intents
Intents control which events Discord sends your bot. Three are privileged and must be switched on in the Developer Portal: Message Content, Server Members and Presence. Only enable the ones your bot really uses, and request the same set in your code. If your bot works with slash commands, it probably doesn't need Message Content at all, which means a leaked token can't be used to read your members' conversations.
// discord.js: request only what you need
const client = new Client({
intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages]
});Fewer intents also means less data in memory and less work for your bot, so this is good for performance as well as security.
Never log or print the token
Logs get shared. People paste console output into support tickets, GitHub issues and Discord help channels all the time, and a token in a log line goes with it.
- Don't
console.log(process.env)orprint(os.environ)while debugging. It dumps every secret at once. - Don't log your config object if it holds the token. Log a safe summary instead, for example whether the token is set.
- Be careful with error handlers that print a full request or client object. HTTP requests to Discord carry the token in the
Authorizationheader. - Never put the token in a command reply or status message. If your bot has an owner-only eval command, make sure it filters the token from its output, or better, remove the command from production.
- Before sharing a screenshot of your editor or terminal, check that no secret is visible.
Environment variables on a host
When your bot moves off your PC, the same rule applies: the token lives in the environment, not in the code. On Zettako bot hosting you add your token as a variable or a .env file, uploaded through SFTP or the web file manager. Either way, your code reads it the same way it does locally, so there is nothing to change between development and production.
A few habits that help on any host:
- Use a separate bot for testing. Create a second application in the Developer Portal for development, with its own token, and invite it only to a test server. A leaked test token can't touch your real community.
- Limit who has access. Anyone who can open your files can read your
.env. Only share panel or SFTP access with people you trust. - Treat backups as secrets. A backup or zip of your bot folder includes the
.envfile. Don't post it anywhere public. - Rotate when people leave. If a developer who had access to the token leaves the project, reset it.
Quick checklist
- The token is in
.envor a host variable, never in source code. .envis in.gitignore, and a.env.exampleis committed instead.- Two-factor authentication is on for the account that owns the application.
- The bot has no Administrator permission and only the intents it uses.
- Nothing logs, prints or replies with the token.
- You know where Reset Token is, and you use it the moment you suspect a leak.
None of this takes long to set up, and it turns a leaked token from a disaster into a minor inconvenience.