如何解决discord.py中的身份验证错误

我正在使用discord.py 制作discord 机器人。但是当我打开机器人时,它收到错误discord.errors.ConnectionClosed:WebSocket连接已关闭:代码= 4004(私人使用),原因=身份验证失败。有什么办法可以解决这个问题吗?


我已经尝试过生成新的代币,或者制作新的机器人。我现在使用的代码之前运行成功。当我在其他计算机(没有相同的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.


泛舟湖上清波郎朗
浏览 192回答 1
1回答

德玛西亚99

我建议使用环境变量,但如果您坚持从文件中读取,请尝试: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将其删除,但让函数返回您的标记是更好的做法。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python