diff --git a/bot_twitch.py b/bot_twitch.py index 029bc68..e39c821 100644 --- a/bot_twitch.py +++ b/bot_twitch.py @@ -112,7 +112,7 @@ class TwitchBot(commands.Bot): async def refresh_access_token(self): """ 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...") @@ -137,8 +137,13 @@ class TwitchBot(commands.Bot): os.environ["TWITCH_REFRESH_TOKEN"] = self.refresh_token self.update_env_file() - self.log("Twitch token refreshed successfully.") - return # Success, exit function + self.log("Twitch token refreshed successfully. Restarting bot...") + + # 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: 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 self.log("Twitch token refresh failed after 3 attempts.", "FATAL") + def update_env_file(self): """ 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): try: 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: 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): self.log(f"The Twitch bot experienced an initialization glitch. Try starting again", "FATAL") await asyncio.sleep(5) # Wait before retrying to authenticate