我正在使用discord.py 制作discord 機器人。但是當我打開機器人時,它收到錯誤discord.errors.ConnectionClosed:WebSocket連接已關閉:代碼= 4004(私人使用),原因=身份驗證失敗。有什么辦法可以解決這個問題嗎?我已經嘗試過生成新的代幣,或者制作新的機器人。我現在使用的代碼之前運行成功。當我在其他計算機(沒有相同的IP)上運行此代碼時,它可以正常工作。我怎么解決這個問題?import asyncioimport discordapp = 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.eventasync 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.eventasync 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 excdiscord.errors.ConnectionClosed: WebSocket connection is closed: code = 4004 (private use), reason = Authentication failed.
1 回答

德瑪西亞99
TA貢獻1770條經驗 獲得超3個贊
我建議使用環境變量,但如果您堅持從文件中讀取,請嘗試:
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將其刪除,但讓函數返回您的標記是更好的做法。
添加回答
舉報
0/150
提交
取消