无法将Bot连接到Disord

时间:2020-02-23 09:04:00

标签: python python-3.x discord discord.py

我正在学习使用python编写不和谐的bot。 最近创建了一个漫游器,并将其成功添加到我的Discord服务器中。 我使用pip安装了discord.py和python-dotenv。 得到了错误:

Traceback (most recent call last):
  File "C:\Users\jjjf9\AppData\Roaming\Python\Python38\site-packages\discord\http.py", line 261, in static_login
    data = await self.request(Route('GET', '/users/@me'))
  File "C:\Users\jjjf9\AppData\Roaming\Python\Python38\site-packages\discord\http.py", line 225, 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 "e:/discord/bot.py", line 15, in <module>
    client.run(token)
  File "C:\Users\jjjf9\AppData\Roaming\Python\Python38\site-packages\discord\client.py", line 640, in run
    return future.result()
  File "C:\Users\jjjf9\AppData\Roaming\Python\Python38\site-packages\discord\client.py", line 621, in runner
    await self.start(*args, **kwargs)
  File "C:\Users\jjjf9\AppData\Roaming\Python\Python38\site-packages\discord\client.py", line 584, in start
    await self.login(*args, bot=bot)
  File "C:\Users\jjjf9\AppData\Roaming\Python\Python38\site-packages\discord\client.py", line 442, in login
    await self.http.static_login(token.strip(), bot=bot)
  File "C:\Users\jjjf9\AppData\Roaming\Python\Python38\site-packages\discord\http.py", line 265, in static_login
    raise LoginFailure('Improper token has been passed.') from exc
discord.errors.LoginFailure: Improper token has been passed.
Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x000001C7B373F700>
Traceback (most recent call last):
  File "C:\Program Files\Python38\lib\asyncio\proactor_events.py", line 116, in __del__ 
    self.close()
  File "C:\Program Files\Python38\lib\asyncio\proactor_events.py", line 108, in close   
    self._loop.call_soon(self._call_connection_lost, None)
  File "C:\Program Files\Python38\lib\asyncio\base_events.py", line 715, in call_soon   
    self._check_closed()
  File "C:\Program Files\Python38\lib\asyncio\base_events.py", line 508, in _check_closed
    raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed

代码: bot.py

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={XXXXXXXXXXXX}

3 个答案:

答案 0 :(得分:2)

看起来像无效的令牌。

尝试从.env文件中的令牌中删除花括号。

答案 1 :(得分:1)

尝试做

token= "yourtokenhere"

代替

token = os.getenv('DISCORD_TOKEN')

测试您的os.getenv是否正确检索了令牌。如果工作正常,您将知道os.getenv无法正常工作。如果它给出相同的错误,则说明您的令牌无效。

答案 2 :(得分:0)

在执行以下操作之前,我遇到了相同的问题:

将第6行更改为

load_dotenv()

load_donenv('.env.txt')