学习编写 Discord 机器人。我为我的机器人密钥设置了一个 .env 文件,但我得到了discord.errors.LoginFailure: Improper token has been passed.
如果我将密钥直接放入client.run(KEY_HERE)
它连接就好了,没有错误。只有当我从 .env 文件中调用它时才会出现问题。
文件树只是项目根目录,其中包含 bot.py 和 .env。我正在使用 PyCharm。
机器人.py:
import os
import discord
import dotenv
from dotenv import load_dotenv
load_dotenv()
token = os.getenv('DISCORD_TOKEN')
client = discord.Client()
@client.event
async def on_ready():
print("connected")
client.run(token)
.env:
DISCORD_TOKEN={"secret_key_here"}
这是完整的错误输出:
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/discord/http.py", line 258, in static_login
data = await self.request(Route('GET', '/users/@me'))
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/discord/http.py", line 222, in request
raise HTTPException(r, data)
discord.errors.HTTPException: 401 UNAUTHORIZED (error code: 0): 401: Unauthorized
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "bot.py", line 16, in <module>
client.run(token)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/discord/client.py", line 598, in run
return future.result()
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/discord/client.py", line 579, in runner
await self.start(*args, **kwargs)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/discord/client.py", line 542, in start
await self.login(*args, bot=bot)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/discord/client.py", line 400, in login
await self.http.static_login(token, bot=bot)
File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/discord/http.py", line 262, in static_login
raise LoginFailure('Improper token has been passed.') from exc
discord.errors.LoginFailure: Improper token has been passed.
谢谢!!