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

2023-05-12Python开发问题
6

本文介绍了我将如何为我的不和谐机器人令牌创建一个 .env 文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

限时送ChatGPT账号..

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

这篇关于我将如何为我的不和谐机器人令牌创建一个 .env 文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

在xarray中按单个维度的多个坐标分组
groupby multiple coords along a single dimension in xarray(在xarray中按单个维度的多个坐标分组)...
2024-08-22 Python开发问题
15

Pandas中的GROUP BY AND SUM不丢失列
Group by and Sum in Pandas without losing columns(Pandas中的GROUP BY AND SUM不丢失列)...
2024-08-22 Python开发问题
17

pandas 有从特定日期开始的按月分组的方式吗?
Is there a way of group by month in Pandas starting at specific day number?( pandas 有从特定日期开始的按月分组的方式吗?)...
2024-08-22 Python开发问题
10

GROUP BY+新列+基于条件的前一行抓取值
Group by + New Column + Grab value former row based on conditionals(GROUP BY+新列+基于条件的前一行抓取值)...
2024-08-22 Python开发问题
18

PANDA中的Groupby算法和插值算法
Groupby and interpolate in Pandas(PANDA中的Groupby算法和插值算法)...
2024-08-22 Python开发问题
11

PANAS-基于列对行进行分组,并将NaN替换为非空值
Pandas - Group Rows based on a column and replace NaN with non-null values(PANAS-基于列对行进行分组,并将NaN替换为非空值)...
2024-08-22 Python开发问题
10