Discord Bot报错:期望token为str却收到NoneType的解决求助
Discord Bot TypeError:expected token to be a str, received <class 'NoneType'> instead
问题说明
编写Discord Bot时触发TypeError,提示token应为字符串但收到NoneType。已尝试用dotenv加载token.env文件,但问题未解决,打印os.getenv('TOKEN') is None返回True,说明环境变量未正确加载。
代码
import discord import os from dotenv import load_dotenv load_dotenv('token.env') from discord.ext import commands intents = discord.Intents.default() intents.message_content = True bot = commands.Bot(command_prefix='$', intents=intents, help_command=None) client = discord.Client(intents=discord.Intents.default()) @client.event async def on_ready(): print('We have logged in as {0.user}'.format(client)) @client.event async def on_message(message): if message.author == client.user: return if message.content.startswith('$hello'): await message.channel.send('Hello!') print(os.getenv('TOKEN') is None) client.run(os.getenv('TOKEN'))
运行报错
True 2022-08-18 08:59:59 INFO discord.client logging in using static token Traceback (most recent call last): File "main.py", line 26, in <module> client.run(os.getenv('TOKEN')) File "/home/runner/MyLibrary/venv/lib/python3.8/site-packages/discord/client.py", line 828, in run asyncio.run(runner()) File "/nix/store/2vm88xw7513h9pyjyafw32cps51b0ia1-python3-3.8.12/lib/python3.8/asyncio/runners.py", line 44, in run return loop.run_until_complete(main) File "/nix/store/2vm88xw7513h9pyjyafw32cps51b0ia1-python3-3.8.12/lib/python3.8/asyncio/base_events.py", line 616, in run_until_complete return future.result() File "/home/runner/MyLibrary/venv/lib/python3.8/site-packages/discord/client.py", line 817, in runner await self.start(token, reconnect=reconnect) File "/home/runner/MyLibrary/venv/lib/python3.8/site-packages/discord/client.py", line 745, in start await self.login(token) File "/home/runner/MyLibrary/venv/lib/python3.8/site-packages/discord/client.py", line 577, in login raise TypeError(f'expected token to be a str, received {token.__class__!r} instead') TypeError: expected token to be a str, received <class 'NoneType'> instead
解决步骤
检查token.env文件的正确性
- 确保文件和
main.py在同一目录下 - 文件内容格式为
TOKEN=你的机器人令牌,不要给令牌加引号,等号前后不要留空格
- 确保文件和
确认load_dotenv的加载逻辑
- 若文件路径无误仍加载失败,可打印当前目录确认路径:
print(os.getcwd()) - 建议将文件名改为
.env,然后直接调用load_dotenv()(无参数),dotenv会自动搜索当前目录下的.env文件,更符合规范
- 若文件路径无误仍加载失败,可打印当前目录确认路径:
验证环境变量加载状态
- 打印所有环境变量排查:
print(os.environ),确认TOKEN是否存在 - 通过load_dotenv的返回值判断加载是否成功:
if not load_dotenv('token.env'): print("加载环境变量文件失败")
- 打印所有环境变量排查:
清理冗余代码
- 代码中同时创建了
commands.Bot和discord.Client两个实例,这是冗余的,只需保留一个。比如改用Bot实例,调整事件装饰器并使用bot.run():# 移除client相关代码,保留bot实例 @bot.event async def on_ready(): print('We have logged in as {0.user}'.format(bot)) @bot.event async def on_message(message): if message.author == bot.user: return await bot.process_commands(message) # 必须加这行才能让命令正常工作 if message.content.startswith('$hello'): await message.channel.send('Hello!') bot.run(os.getenv('TOKEN'))
- 代码中同时创建了
内容的提问来源于stack exchange,提问作者SpaceNugget
相关产品推荐
相关产品推荐

