我将如何为我的不和谐机器人令牌创建一个 .env 文件?

2022-01-15 00:00:00 python discord discord.py

问题描述

所以,最近有人告诉我,仅将 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.

指令列表:

  1. pip install python-dotenv.
  2. 在项目的根目录中创建一个名为 .env 的文件.
  3. 写一行:DISCORD_TOKEN = 你的令牌(不需要引号)
  4. 您的代码中应该有 import osfrom dotenv import load_dotenv.
  5. 在程序开始时调用 load_dotenv() 来加载文件.
  6. 要获取令牌,您只需执行 os.getenv("DISCORD_TOKEN").
  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").

示例代码:

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

相关文章