Skip to content Skip to sidebar Skip to footer

How Would I Go About Creating An .env File For My Discord Bot Token?

So, I was recently told that just storing the Discord Bot token in a variable at the top is bad practice and a .env file would be better. Can someone explain to me how I would crea

Solution 1:

You can use a libary/module called python-dotenv, install the library with

pip install python-dotenv

To use it in your code, you have to import the os module as well as the freshly installed dotenv package

import os
from dotenv import load_dotenv

At the beginning of your code after the imports you should have load_dotenv() to load the .env file. Then you can use os.getenv("DOTENV variablename here") to get the content of the file.

Instruction List:

  1. pip install python-dotenv.
  2. Create a file named .env in the root of your project.
  3. Write one line: DISCORD_TOKEN = your token (no quotes needed)
  4. you should have import os and from dotenv import load_dotenv in your code.
  5. Call load_dotenv() at the beginning of your program to load the file.
  6. To get your token, you just have to do os.getenv("DISCORD_TOKEN").

Example code:

import os
from dotenv import load_dotenv

load_dotenv()

TOKEN = os.getenv("DISCORD_TOKEN")

Example dotenv file:

DISCORD_TOKEN=this.is.my.token.blah.blah.blah

Post a Comment for "How Would I Go About Creating An .env File For My Discord Bot Token?"