From defc9ef1e94ccc35cc105694f50d6038c9fd746d Mon Sep 17 00:00:00 2001 From: Revulate Date: Mon, 14 Oct 2024 17:28:20 -0700 Subject: [PATCH] modified: bot.py modified: twitch_helix_client.py --- bot.py | 5 +--- twitch_helix_client.py | 64 +++++++++++++++++------------------------- 2 files changed, 27 insertions(+), 42 deletions(-) diff --git a/bot.py b/bot.py index 89d201c..a8028fd 100644 --- a/bot.py +++ b/bot.py @@ -12,6 +12,7 @@ import aiohttp import sys import codecs +import traceback sys.stdout = codecs.getwriter("utf-8")(sys.stdout.buffer, "strict") sys.stderr = codecs.getwriter("utf-8")(sys.stderr.buffer, "strict") @@ -223,10 +224,6 @@ async def main(): while True: try: await bot.start() - except AuthenticationError: - logger.error("Authentication failed. Refreshing token and retrying...") - await bot.twitch_api.refresh_oauth_token() - continue except Exception as e: logger.error(f"An unexpected error occurred: {e}") logger.error(f"Error traceback: {traceback.format_exc()}") diff --git a/twitch_helix_client.py b/twitch_helix_client.py index bf7a36c..fea3610 100644 --- a/twitch_helix_client.py +++ b/twitch_helix_client.py @@ -114,12 +114,13 @@ async def refresh_oauth_token(self): async def ensure_token_valid(self): if not self.oauth_token or (self.token_expiry and datetime.datetime.now() >= self.token_expiry): - return await self.refresh_oauth_token() + success = await self.refresh_oauth_token() + if not success: + raise Exception("Failed to refresh OAuth token") return True async def api_request(self, endpoint, params=None, method="GET", data=None): - if not await self.ensure_token_valid(): - raise Exception("Failed to obtain a valid token") + await self.ensure_token_valid() url = f"{self.BASE_URL}/{endpoint}" headers = { @@ -127,41 +128,28 @@ async def api_request(self, endpoint, params=None, method="GET", data=None): "Client-ID": self.client_id, } - session = self.session or aiohttp.ClientSession() - should_close_session = self.session is None - - try: - for _ in range(2): # Try twice: once with current token, once after refreshing - try: - if method == "GET": - async with session.get(url, params=params, headers=headers) as response: - if response.status == 401: - if await self.refresh_oauth_token(): - headers["Authorization"] = f"Bearer {self.oauth_token}" - continue - else: - raise Exception("Failed to refresh token") - response.raise_for_status() - return await response.json() - elif method == "POST": - async with session.post(url, params=params, headers=headers, json=data) as response: - if response.status == 401: - if await self.refresh_oauth_token(): - headers["Authorization"] = f"Bearer {self.oauth_token}" - continue - else: - raise Exception("Failed to refresh token") - response.raise_for_status() - return await response.json() - except aiohttp.ClientResponseError as e: - logger.error(f"API request error: {e}", exc_info=True) - if e.status != 401: - raise - break # If we get here, we've either succeeded or failed after a refresh - raise Exception("Failed to complete API request") - finally: - if should_close_session: - await session.close() + async def perform_request(session): + try: + if method == "GET": + async with session.get(url, params=params, headers=headers) as response: + response.raise_for_status() + return await response.json() + elif method == "POST": + async with session.post(url, params=params, headers=headers, json=data) as response: + response.raise_for_status() + return await response.json() + except aiohttp.ClientResponseError as e: + if e.status == 401: + if await self.refresh_oauth_token(): + headers["Authorization"] = f"Bearer {self.oauth_token}" + return await perform_request(session) + raise + + if self.session: + return await perform_request(self.session) + else: + async with aiohttp.ClientSession() as session: + return await perform_request(session) async def get_streams(self, user_logins): params = {"user_login": user_logins}