Discord.py(重写):函数中的错误处理 "Improper Token"

Discord.py (rewrite): Error Handling "Improper Token" In Function

我觉得我缺少解决此问题的简单方法,但我似乎找不到处理 discord.errors.LoginFailure: Improper token has been passed. 错误的方法。我想做的是 运行 一个函数,它本质上是 运行 一个机器人,如果它遇到任何错误(try:except:)并且如果它捕获 'improper token' 错误,然后更改我的代码中的设置并重试。

我相信正在发生的事情是 try/except 没有捕捉到错误并且它停止了程序(打印过程中的整个错误)。我已经尝试了一些快速解决方案,例如将函数变成 while 语句,直到它到达程序末尾,它会不断重复自己,但是如果没有捕获到错误,我将无法继续任何代码。

我的代码很乱,并且与之前在这个大 python 文件中定义的许多变量有关,所以我不会展示我的整个函数。

这是简化版:

def code(mainText):
    mainLines = mainText.split("\n")
    # Do some stuff editing mainText
    final = "\n".join(mainLines)
    try:
        exec(final, globals())
    except Exception as e:
        print(str(e))
        # edit 'final' a bit
        exec(final, globals())

完整的错误信息:

Task exception was never retrieved
future: <Task finished coro=<Client.start() done, defined at E:\DiscordBot\lib\site-packages\discord\client.py:526> exception=LoginFailure('Improper token has been passed.')>
Traceback (most recent call last):
  File "E:\DiscordBot\lib\site-packages\discord\http.py", line 258, in static_login
    data = await self.request(Route('GET', '/users/@me'))
  File "E:\DiscordBot\lib\site-packages\discord\http.py", line 222, 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:\DiscordBot\lib\site-packages\discord\client.py", line 542, in start
    await self.login(*args, bot=bot)
  File "E:\DiscordBot\lib\site-packages\discord\client.py", line 400, in login
    await self.http.static_login(token, bot=bot)
  File "E:\DiscordBot\lib\site-packages\discord\http.py", line 262, in static_login
    raise LoginFailure('Improper token has been passed.') from exc
discord.errors.LoginFailure: Improper token has been passed.

在撰写本文时,我发现 'Task exception never retrieved' 这是重要的事情还是常见的 'improper token' 错误?

谢谢,对于我糟糕的编码习惯和缺乏使用 Stack Overflow 的经验,我深表歉意。

试试这个。我自己没有试过。这是我从您的问题和错误消息中可以理解的最佳答案:

#Put this at the bottom of your .py file
try:
    bot.run(BOT_TOKEN)
except discord.errors.LoginFailure as e:
    print("Login unsuccessful.")

你的token是字符串吗? 你是从不和谐的开发者门户网站得到的吗?也就是说,您确定这是正确的标记吗?

确保 BOT_TOKEN 是一个字符串并且您的令牌有效

看到有 HTTPException 和 Login Failure 的事实,你应该把它们都放在 except 后面,像这样:


try:
    bot.run(BOT_TOKEN)
except discord.errors.HTTPException and discord.errors.LoginFailure as e:
    print("Login unsuccessful.")

这也会捕获 HTTPException。因为就像我说的,如果您阅读错误,您会看到一个 HTTPException 一个 LoginFailure。如果您想捕获错误并生成自定义错误消息,则需要捕获这两个。