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

Tags: , , , ,



I feel like I’m missing a simple way to solve this problem, but I can’t seem to find a way to handle the discord.errors.LoginFailure: Improper token has been passed. error. What I’m trying to do is run a function that essentially runs a bot and repeats itself if it comes across any errors (with try: and except:) and if it catches the ‘improper token’ error then change a setting in my code and retry it.

What I believe is happening is that try/except isn’t catching the error and it stops the program (printing the entire error in the process). I’ve tried some quick solutions like making the function into a while statement and until it reaches the end of the program it will keep repeating itself, however without catching the error I can’t continue any code.

My code is messy and has to do with a lot of variables that are defines earlier in this large python file, so I won’t show my entire function.

Here is the simplified version:

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())

The full error message:

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

As of writing this I found ‘Task exception never retrieved’ is this anything of importance or is that the usual ‘improper token’ error?

Thank you, sorry in advance for my bad coding practices and lack of experience using Stack Overflow.

Answer

Try this. I haven’t tried it myself. This is my best answer as to what I can understand from your problem and error message:

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


Source: stackoverflow