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?
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
..env
in the root of your project.import os
and from dotenv import load_dotenv
in your code.load_dotenv()
at the beginning of your program to load the file.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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With