You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

开发Discord Bot时.env文件TOKEN读取失败问题求助

Discord Bot无法加载.env文件导致启动失败的解决方法

问题

我在main.py同级目录创建了.env文件,原本以为运行main.py时会自动加载该文件,让Discord Bot正常启动,但实际并未生效,运行后报错。

我的代码

import discord
import os


client = discord.Client(intents=discord.Intents.default())

@client.event
async def on_ready():
  print('We have loggined 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')

client.run(os.getenv('TOKEN'))

运行报错信息

Traceback (most recent call last):
File "c:\Users\User\Desktop\python_work\main.py", line 19, in 
client.run(os.getenv('TOKEN'))
File "C:\Users\User\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 860, in run
asyncio.run(runner())
File "C:\Users\User\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 190, in run
return runner.run(main)
^^^^^^^^^^^^^^^^
File "C:\Users\User\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 118, in run
return self._loop.run_until_complete(task)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\User\AppData\Local\Programs\Python\Python311\Lib\asyncio\base_events.py", line 653, in run_until_complete
return future.result()
^^^^^^^^^^^^^^^
File "C:\Users\User\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 849, in runner
await self.start(token, reconnect=reconnect)
File "C:\Users\User\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 777, in start
await self.login(token)
File "C:\Users\User\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\client.py", line 609, in login
raise TypeError(f'expected token to be a str, received {token.__class__.__name__} instead')
TypeError: expected token to be a str, received NoneType instead
PS C:\Users\User>

解决步骤

  • 安装python-dotenv库:Python默认不会自动读取.env文件,需要依赖这个第三方库,执行命令:
    pip install python-dotenv
    
  • 修改代码加载.env文件:在代码开头添加加载逻辑,修改后的代码如下:
    import discord
    import os
    from dotenv import load_dotenv
    
    # 加载同级目录的.env文件
    load_dotenv()
    
    client = discord.Client(intents=discord.Intents.default())
    
    @client.event
    async def on_ready():
      print('We have loggined 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')
    
    client.run(os.getenv('TOKEN'))
    
  • 检查.env文件格式:确保文件内容为TOKEN=你的机器人令牌,注意不要给令牌加引号,也不要在等号前后加多余空格。

内容的提问来源于stack exchange,提问作者Becky

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 11:24:55