This guide shows you how to lock down a Discord bot that executes coding agent commands (like running tests, applying patches, or invoking an AI coding assistant). You’ll learn to control who can trigger it, what the bot can access, and how to contain the damage if something goes wrong. By the end, you’ll have a bot that’s useful but not a security hole.
What You’ll Need
- A Discord bot token (from the Discord Developer Portal) and the bot added to your server
- Node.js (v18+) or Python 3.9+ depending on your bot framework
- Basic familiarity with your coding agent CLI (e.g., a command that runs tests or applies diffs)
- A server or machine where the bot will run (separate from your main work machine is better)
Step-by-Step
- Create a dedicated bot account with minimal permissions.
In the Discord Developer Portal, create a new bot (or reconfigure an existing one). Under “Bot� settings, disable “Public Bot� so only your server can add it. Under “OAuth2� → “Scopes�, select “bot�. Under “Bot Permissions�, only grant what the bot absolutely needs: typically “Send Messages�, “Read Message History�, and “Use Slash Commands�. Do not grant “Administrator�, “Manage Server�, or “Manage Channels�. - Restrict command usage to a specific role.
In your server, create a role like “DevBot Admin�. In the bot’s code, before executing any command, check that the message author has that role. For slash commands, use Discord’s built-in default permissions or checkinteraction.member.roles. Example (discord.js):if (!interaction.member.roles.cache.some(r => r.name === 'DevBot Admin')) return interaction.reply('No permission'); - Whitelist channels.
Only allow the bot to respond in a specific channel (e.g., #dev-bot). This prevents accidental triggers elsewhere and keeps logs tidy. Checkinteraction.channel.nameor use a channel ID constant. - Sanitize and validate every command input.
Never pass raw user input directly to a shell. Use a parser that only accepts a predefined set of commands and arguments. For example, if your agent supportsrun-testsandapply-patch, map those to exact CLI invocations. Reject anything that contains shell metacharacters like;,&,|,$(), or backticks. - Run the bot in a sandboxed environment.
Use a Docker container with read-only filesystem where possible, or a dedicated user account with no sudo privileges. Limit CPU and memory withdocker run --memory=1g --cpus=1. This contains any malicious code your agent might generate. - Use a separate token and never hardcode it.
Store the bot token and any API keys in environment variables or a secrets manager. Do not commit them to version control. If using Docker, pass them via--env-file. - Add an approval queue for destructive actions.
For commands that modify code (like applying patches or pushing commits), make the bot output a preview and wait for a second confirmation from a different authorized user. Implement a simple state machine: first command creates a pending action, second command (with a confirmation ID) executes it. - Log all commands and outputs.
Write every command, the invoking user, timestamp, and the result to a log file or a separate Discord channel. This gives you an audit trail if something goes wrong. - Set a timeout and kill switch.
Wrap command execution in a timeout (e.g., 60 seconds) and terminate the process if it exceeds. Have a “shutdown� command that only the bot owner can use to stop the bot remotely. - Keep dependencies updated and pin versions.
Use a lockfile (package-lock.json or requirements.txt) and regularly update the bot framework and the coding agent to patch known vulnerabilities.
Common Mistakes
- Granting the bot “Administrator� permission “just in case� – this allows any command to escalate privileges.
- Using
child_process.execwith string concatenation – this is shell injection waiting to happen. - Forgetting to check the user’s role on every command, including hidden ones.
- Running the bot as root or with your personal user account – a compromised bot then has full access to your files.
- Not logging anything – you can’t investigate an incident without logs.
- Allowing the bot to access the internet without restrictions – it could exfiltrate data.
Tips
- Use a separate Discord server for testing before deploying to your main server.
- Implement a rate limiter (e.g., max 5 commands per minute per user) to prevent abuse.
- If your coding agent can run arbitrary code, treat it as untrusted – even if it’s “just� a tool.
- Consider using a virtual machine or a dedicated low-cost VPS for the bot, isolated from your network.
- Store the bot’s working directory in a temporary folder that gets wiped after each command.
- For extra security, require a second factor (like a random code from the user’s DMs) for destructive commands.
Troubleshooting
- Bot doesn’t respond to commands: Check that the bot has “Send Messages� permission in the channel and that the channel is in your whitelist. Also verify the bot is online and the token is correct.
- Permission check fails: Ensure the role name matches exactly (case-sensitive). If using Discord’s built-in permissions, make sure the role is assigned in the server settings.
- Command times out: Increase the timeout in your code, but also check if the coding agent is hanging due to missing input. Add a
--yesflag to your CLI to avoid prompts. - Shell injection attempts are still passing: Review your validation logic – you must whitelist, not blacklist. Blacklists are easy to bypass.
- Bot crashes after a command: Look at the error logs – it might be an unhandled promise rejection. Add a global error handler to keep the bot alive.
- Docker container can’t access the network: If you need internet access, you’ll have to allow it, but consider using a proxy or restricting egress to only necessary domains.
Frequently Asked Questions
Q: Can I make the bot only work for me and not others?
A: Yes, check that the user ID matches your own Discord ID in the code. That’s the most restrictive option.
Q: What if my coding agent needs to access a private repository?
A: Use a separate deploy key with read-only access to that repo, and store the key in an environment variable. Never use your personal SSH key.
Q: Is it safe to let the bot run commands like “git push�?
A: Only if you have a confirmation step and the bot runs in a container with limited credentials. Even then, it’s risky – consider having the bot create a pull request instead.
Q: How do I prevent the bot from being used to spam commands?
A: Add a cooldown per user and per channel. Discord’s rate limits help, but your own limiter is more precise.
Q: What should I do if the bot is compromised?
A: Immediately revoke the bot token in the Developer Portal, shut down the process, and check logs for what was executed. Rotate any credentials the bot had access to.
Q: Can I use a slash command instead of a prefix?
A: Yes, slash commands are recommended because they’re easier to secure (permissions are built-in) and less prone to injection.
Related
General steps for current mainstream versions; menus can differ by device and version. See the disclaimer or report an error.
More in this bed
- How to Edit Messages in WhatsApp: Full Guide
- How to Wash Windows Like a Pro: Step-by-Step Guide
- Last of Us Part II Crashing on PC: Fixes
- Install Adobe Creative Cloud on Linux: The Real Options
- HTC Salsa vs HTC ChaCha: Facebook Phones Compared
- Remove Snake Keylogger Malware: PC Cleanup Guide