Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 create the .env file with the token in it and import it into my bot.py file?

like image 766
DeeDeeAich Avatar asked Mar 03 '23 03:03

DeeDeeAich


1 Answers

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
like image 78
jreiss1923 Avatar answered Mar 05 '23 16:03

jreiss1923