Skip to content

Instantly share code, notes, and snippets.

@MoonlightCapital
Last active August 28, 2021 19:21
Show Gist options
  • Save MoonlightCapital/54a3434190dc287037b0599931e7db1a to your computer and use it in GitHub Desktop.
Save MoonlightCapital/54a3434190dc287037b0599931e7db1a to your computer and use it in GitHub Desktop.
Storing your bot token safely

Storing your bot token safely

Your bot token is a very crucial piece of information. It must be protected from being leaked at all cost, otherwise a malicious actor may use it to perform disruptive actions as your bot.

Using an env file

An env file is used to store environment variables, which are kept separate for the rest of the code. They are ideal to store tokens, API keys and other kind of sensitive information. Python does not support them natively, so we're going to install a package to make use of them. Type this command in your terminal:

pip install python-dotenv

Code changes

Now, using the basic bot example code, we'll have to make some modifications.

Add this at the beginning of your bot file:

import os
from dotenv import load_dotenv
load_dotenv()

We have successfully loaded the files in the env file (which we're going to create next), now, let's put them to use.

Change the last line of the file to:

bot.run(os.environ.get('DISCORD_BOT_TOKEN'))

Making the env file

In your bot's main directory, create a file named .env. Be careful because the dot at the start is important.

Now open the file in a text editor, and paste the following into it:

DISCORD_BOT_TOKEN=<your token here>

Replacing <your token here> with your actual token, then save the file. It's not over yet, as some additional steps need to be taken.

Adding your env file to gitignore

Gitignore is a very useful file as it defines rules for which files are not committed to git, so you won't accidentally push your sensitive data to your repository. To start, create a file named .gitignore (again, the dot at the start is important) or open it if exists.

Add the following in a new line to the file:

.env

That's it! Once saved, git won't publish the env file anymore.

Extras

If your token ever gets leaked, immediately regenerate it by going to the Discord developer portal, select your application, go to the "Bot" tab and click the "Regenerate", then confirm. Remember to update the token in your code afterwards.

For more information about the python-dotenv package, please refer to https://pypi.org/project/python-dotenv/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment