我已经挠头好几个小时了,我似乎无法让我的机器人连接到不和谐,我正在为机器人使用此代码:
import os
import discord
from dotenv import load_dotenv
load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
client = discord.Client()
@client.event
async def on_ready():
print(f'{client.user} has connected to Discord!')
client.run(TOKEN)
这个是 .env 文件
DISCORD_TOKEN = "token here"
然而,这个错误一直在运行:
Traceback (most recent call last):
File "C:\Users\amber\OneDrive\Desktop\Python39\MemeBot\MemeBot.py", line 16, in <module>
client.run(TOKEN)
File "C:\Users\amber\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\client.py", line 723, in run
return future.result()
File "C:\Users\amber\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\client.py", line 702, in runner
await self.start(*args, **kwargs)
File "C:\Users\amber\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\client.py", line 665, in start
await self.login(*args, bot=bot)
File "C:\Users\amber\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\discord\client.py", line 511, in login
await self.http.static_login(token.strip(), bot=bot)
AttributeError: 'NoneType' object has no attribute 'strip'
我很难过,任何帮助将不胜感激:)
答案 0 :(得分:0)
TL;DR:将 .env
文件放在与脚本相同或更高的目录中
问题是 discord 库试图剥离您的令牌,但它是 None
类型。所以你的环境变量没有正确加载。
确保您的 .env
文件位于目录结构中的正确位置并正确加载。来自文档:https://pypi.org/project/python-dotenv/
默认情况下,load_dotenv 不会覆盖现有环境 变量。
配置开发环境,在根目录添加一个.env 项目目录:
├── .env
└── foo.py
只需将 .env
文件和 python 脚本放在同一目录中,我就能让您的代码正常工作。