所以,最近有人告诉我,仅将 Discord Bot 令牌存储在顶部的变量中是不好的做法,使用 .env 文件会更好.有人可以向我解释如何创建包含令牌的 .env 文件并将其导入到我的 bot.py 文件中吗?
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?
你可以使用一个名为 python-dotenv 的库/模块,安装该库
You can use a libary/module called python-dotenv, install the library with
pip install python-dotenv
要在您的代码中使用它,您必须导入 os 模块以及新安装的 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
在导入后代码的开头,您应该使用 load_dotenv() 来加载 .env 文件.然后就可以使用os.getenv("DOTENV variablename here")来获取文件的内容了.
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.
指令列表:
pip install python-dotenv..env 的文件.import os 和 from dotenv import load_dotenv.load_dotenv() 来加载文件.os.getenv("DISCORD_TOKEN").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").示例代码:
import os
from dotenv import load_dotenv
load_dotenv()
TOKEN = os.getenv("DISCORD_TOKEN")
dotenv 文件示例:
Example dotenv file:
DISCORD_TOKEN=this.is.my.token.blah.blah.blah
这篇关于我将如何为我的不和谐机器人令牌创建一个 .env 文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
python:不同包下同名的两个模块和类python: Two modules and classes with the same name under different packages(python:不同包下同名的两个模块和类)
配置 Python 以使用站点包的其他位置Configuring Python to use additional locations for site-packages(配置 Python 以使用站点包的其他位置)
如何在不重复导入顶级名称的情况下构造python包How to structure python packages without repeating top level name for import(如何在不重复导入顶级名称的情况下构造python包)
在 OpenShift 上安装 python 包Install python packages on OpenShift(在 OpenShift 上安装 python 包)
如何刷新 sys.path?How to refresh sys.path?(如何刷新 sys.path?)
分发带有已编译动态共享库的 Python 包Distribute a Python package with a compiled dynamic shared library(分发带有已编译动态共享库的 Python 包)