Skip to content

Commit

Permalink
modified: bot.py
Browse files Browse the repository at this point in the history
	modified:   twitch_helix_client.py
  • Loading branch information
Revulate committed Oct 15, 2024
1 parent fcab2b3 commit defc9ef
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 42 deletions.
5 changes: 1 addition & 4 deletions bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down Expand Up @@ -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()}")
Expand Down
64 changes: 26 additions & 38 deletions twitch_helix_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,54 +114,42 @@ 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 = {
"Authorization": f"Bearer {self.oauth_token}",
"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}
Expand Down

0 comments on commit defc9ef

Please sign in to comment.