Fixed (?) a Twitch authentication crash

- The automatic token refresh function crashed after a certain time since last token refresh. This should fix it
kami_dev
Kami 2025-02-10 13:02:51 +01:00
parent 3ad6504d69
commit 623aeab9fb
1 changed files with 14 additions and 3 deletions

View File

@ -112,7 +112,7 @@ class TwitchBot(commands.Bot):
async def refresh_access_token(self): async def refresh_access_token(self):
""" """
Refreshes the Twitch access token using the stored refresh token. Refreshes the Twitch access token using the stored refresh token.
Retries up to 2 times before logging a fatal error. Retries up to 3 times before logging a fatal error.
""" """
self.log("Attempting to refresh Twitch token...") self.log("Attempting to refresh Twitch token...")
@ -137,8 +137,13 @@ class TwitchBot(commands.Bot):
os.environ["TWITCH_REFRESH_TOKEN"] = self.refresh_token os.environ["TWITCH_REFRESH_TOKEN"] = self.refresh_token
self.update_env_file() self.update_env_file()
self.log("Twitch token refreshed successfully.") self.log("Twitch token refreshed successfully. Restarting bot...")
return # Success, exit function
# Restart the TwitchIO connection
await self.close() # Close the old connection
await self.start() # Restart with the new token
return # Exit function after successful refresh
else: else:
self.log(f"Twitch token refresh failed (Attempt {attempt+1}/3): {data}", "WARNING") self.log(f"Twitch token refresh failed (Attempt {attempt+1}/3): {data}", "WARNING")
@ -150,6 +155,7 @@ class TwitchBot(commands.Bot):
# If all attempts fail, log error # If all attempts fail, log error
self.log("Twitch token refresh failed after 3 attempts.", "FATAL") self.log("Twitch token refresh failed after 3 attempts.", "FATAL")
def update_env_file(self): def update_env_file(self):
""" """
Updates the .env file with the new Twitch token. Updates the .env file with the new Twitch token.
@ -212,8 +218,13 @@ class TwitchBot(commands.Bot):
if "Invalid or unauthorized Access Token passed." in str(e): if "Invalid or unauthorized Access Token passed." in str(e):
try: try:
await self.refresh_access_token() await self.refresh_access_token()
self.log("Retrying bot connection after token refresh...", "INFO")
await self.start() # Restart connection with new token
return # Exit retry loop
except Exception as e: except Exception as e:
self.log(f"Unable to refresh Twitch token! Twitch bot will be offline!", "CRITICAL") self.log(f"Unable to refresh Twitch token! Twitch bot will be offline!", "CRITICAL")
if self._keeper:
self._keeper.cancel()
if "'NoneType' object has no attribute 'cancel'" in str(e): if "'NoneType' object has no attribute 'cancel'" in str(e):
self.log(f"The Twitch bot experienced an initialization glitch. Try starting again", "FATAL") self.log(f"The Twitch bot experienced an initialization glitch. Try starting again", "FATAL")
await asyncio.sleep(5) # Wait before retrying to authenticate await asyncio.sleep(5) # Wait before retrying to authenticate