Learnmonkey Learnmonkey Logo
× Warning:

The tutorial you are reading is currently a work in-progress.

Discord.py Storing Your Bot Token

The Importance of Storing your Bot Token

As already mentioned, bot tokens are the password to your bot. If someone has access to your bot token, they basically control the bot. So, we regenerate the token whenever we need to. However, it is still very important to store your bot token, because we might not know when our token is leaked. Right now, our token is stored directly in our code. However, this is bad because anyone who sees our code can control our bot.

Using a .env file

One option is to use a .env file. So, create a file in the same folder as your code files and type the following in it:

TOKEN='your token here'

Then, we need to install the python-dotenv module by running pip install python-dotenv in the command line. Then, in our Python file we can type:


from dotenv import load_dotenv

load_dotenv()
    

Now, we need to actually get the token using the built-in os module:


from dotenv import load_dotenv
from os import getenv

load_dotenv()

token = getenv("TOKEN")
    

That's it! Now you can run your bot:

bot.run(token)