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:
pip install python-dotenv
.- Create a file named
.env
in the root of your project. - Write one line: DISCORD_TOKEN = your token (no quotes needed)
- you should have
import os
andfrom dotenv import load_dotenv
in your code. - Call
load_dotenv()
at the beginning of your program to load the file. - 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?"