【问题标题】:How can I solve authentication error in discord.py如何解决 discord.py 中的身份验证错误
【发布时间】:2020-09-26 08:54:56
【问题描述】:

我正在使用 discord.py 制作不和谐机器人。但是当我打开机器人时,它得到错误 discord.errors.ConnectionClosed: WebSocket connection is closed: code = 4004 (private use), reason = Authentication failed。有没有办法解决这个问题?

我已经尝试过生成新的令牌,或者制作新的机器人。我现在使用的代码之前运行成功。当我在其他计算机上运行此代码时(没有相同的 ip),它可以正常工作。我该如何解决这个问题?

import asyncio
import discord

app = discord.Client()

def get_token(): # Get tokens from key.key
    global token # This part works properly
    f = open("Key.key", "r")
    token = str(f.readline())

@app.event
async def on_ready(): #Login Part
    print("Logining to : ")
    print(app.user.name)
    print(app.user.id)
    print("==========")
    game = discord.Game("Bot is working properly!")
    await app.change_presence(status=discord.Status.online, activity=game)



@app.event
async def on_message(message):
    if message.author.bot:
        return None
    if message.content == "!hello":
        await message.channel.send("hello?")

get_token()
app.run(token)

这是我的源代码,下面是回溯

  File "d:\Code\Project\discord_bot\Koi_Bot_Discord\Main.py", line 30, in <module>
    app.run(token)
  File "D:\Python\lib\site-packages\discord\client.py", line 598, in run
    return future.result()
  File "D:\Python\lib\site-packages\discord\client.py", line 579, in runner
    await self.start(*args, **kwargs)
  File "D:\Python\lib\site-packages\discord\client.py", line 543, in start
    await self.connect(reconnect=reconnect)
  File "D:\Python\lib\site-packages\discord\client.py", line 457, in connect
    await self._connect()
  File "D:\Python\lib\site-packages\discord\client.py", line 421, in _connect
    await self.ws.poll_event()
  File "D:\Python\lib\site-packages\discord\gateway.py", line 476, in poll_event
    raise ConnectionClosed(exc, shard_id=self.shard_id) from exc
discord.errors.ConnectionClosed: WebSocket connection is closed: code = 4004 (private use), reason = Authentication failed.

【问题讨论】:

    标签: python discord.py


    【解决方案1】:

    我建议使用environment variables,但如果您坚持从文件中读取,请尝试:

    def get_token(): # Get tokens from key.key
        with open("Key.key", "r") as f:
            return f.readline().strip()
    ...
    
    app.run(get_token())
    

    您很可能从 readline 获得换行符,因此 strip 将删除它,但让函数返回您的令牌是更好的做法。

    【讨论】:

    • 很高兴,如果我的回答解决了您的问题,请将其标记为解决方案,谢谢!
    【解决方案2】:

    使用“python -m pip install -U discord.py”更新不和谐模块是一种解决方案

    【讨论】:

      猜你喜欢
      • 2013-02-27
      • 2017-10-28
      • 2015-11-04
      • 1970-01-01
      • 2018-03-19
      • 2014-04-04
      • 2018-02-01
      • 2018-11-05
      相关资源
      最近更新 更多