Skip to content

Commit

Permalink
modified: cogs/afk.py
Browse files Browse the repository at this point in the history
	modified:   cogs/remind.py
	modified:   twitch_helix_client.py
  • Loading branch information
Revulate committed Oct 16, 2024
1 parent f175503 commit c75aa6d
Show file tree
Hide file tree
Showing 3 changed files with 62 additions and 63 deletions.
2 changes: 1 addition & 1 deletion cogs/afk.py
Original file line number Diff line number Diff line change
Expand Up @@ -172,4 +172,4 @@ def format_duration_string(self, duration):


def prepare(bot):
bot.add_cog(Afk(bot))
bot.add_cog(Afk(bot))
8 changes: 4 additions & 4 deletions cogs/remind.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import asyncio
import uuid
from datetime import datetime, timezone
from datetime import datetime, timezone, timedelta
import aiosqlite
from twitchio.ext import commands
from utils import parse_time, format_time_delta, normalize_username, fetch_user, get_channel
Expand Down Expand Up @@ -141,8 +141,8 @@ async def remind_command(self, ctx: commands.Context, target_identifier: str, *,
if created_at.tzinfo is None:
created_at = created_at.replace(tzinfo=timezone.utc)

remind_time, message = parse_time(message.split())
remind_time = created_at + remind_time if remind_time else None
remind_time_delta, message = parse_time(message.split())
remind_time = created_at + remind_time_delta if remind_time_delta else None

reminder = Reminder(
reminder_id=reminder_id,
Expand Down Expand Up @@ -222,4 +222,4 @@ def row_to_reminder(self, row):


def prepare(bot):
bot.add_cog(Remind(bot))
bot.add_cog(Remind(bot))
115 changes: 57 additions & 58 deletions twitch_helix_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,18 +63,18 @@ async def exchange_code_for_token(self, code):
"grant_type": "authorization_code",
"redirect_uri": self.redirect_uri,
}
async with aiohttp.ClientSession() as session:
async with session.post(self.TOKEN_URL, data=params) as response:
if response.status == 200:
data = await response.json()
self.oauth_token = data["access_token"]
self.refresh_token = data["refresh_token"]
self.token_expiry = datetime.datetime.now() + datetime.timedelta(seconds=data["expires_in"])
self.save_tokens()
return True
else:
log_error(f"Failed to exchange code for token: {await response.text()}")
return False
await self.ensure_session()
async with self.session.post(self.TOKEN_URL, data=params) as response:
if response.status == 200:
data = await response.json()
self.oauth_token = data["access_token"]
self.refresh_token = data["refresh_token"]
self.token_expiry = datetime.datetime.now() + datetime.timedelta(seconds=data["expires_in"])
self.save_tokens()
return True
else:
log_error(f"Failed to exchange code for token: {await response.text()}")
return False

async def refresh_oauth_token(self):
if not self.refresh_token:
Expand All @@ -87,20 +87,20 @@ async def refresh_oauth_token(self):
"grant_type": "refresh_token",
"refresh_token": self.refresh_token,
}
await self.ensure_session()
try:
async with aiohttp.ClientSession() as session:
async with session.post(self.TOKEN_URL, data=params) as response:
if response.status == 200:
data = await response.json()
self.oauth_token = data["access_token"]
self.refresh_token = data.get("refresh_token", self.refresh_token)
self.token_expiry = datetime.datetime.now() + datetime.timedelta(seconds=data["expires_in"])
self.save_tokens()
log_info("OAuth token refreshed successfully")
return True
else:
log_error(f"Failed to refresh token: {await response.text()}")
return False
async with self.session.post(self.TOKEN_URL, data=params) as response:
if response.status == 200:
data = await response.json()
self.oauth_token = data["access_token"]
self.refresh_token = data.get("refresh_token", self.refresh_token)
self.token_expiry = datetime.datetime.now() + datetime.timedelta(seconds=data["expires_in"])
self.save_tokens()
log_info("OAuth token refreshed successfully")
return True
else:
log_error(f"Failed to refresh token: {await response.text()}")
return False
except Exception as e:
log_error(f"Error during token refresh: {e}", exc_info=True)
return False
Expand All @@ -122,24 +122,22 @@ async def api_request(self, endpoint, params=None, method="GET", data=None):
"Client-ID": self.client_id,
}

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

return await perform_request(self.session)
try:
if method == "GET":
async with self.session.get(url, params=params, headers=headers) as response:
response.raise_for_status()
return await response.json()
elif method == "POST":
async with self.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 self.api_request(endpoint, params, method, data)
log_error(f"Request failed: {e}")
raise

async def get_streams(self, user_logins):
params = {"user_login": user_logins}
Expand All @@ -164,22 +162,23 @@ async def get_channel_games(self, channel_name):
return None

async def get_game_image_url(self, game_name):
await self.ensure_session()
headers = {"Client-ID": self.client_id, "Authorization": f"Bearer {self.oauth_token}"}
params = {"name": game_name}
url = f"{self.BASE_URL}/games"

try:
url = f"{self.BASE_URL}/games"
headers = {"Client-ID": self.client_id, "Authorization": f"Bearer {self.oauth_token}"}
params = {"name": game_name}
async with aiohttp.ClientSession() as session:
async with session.get(url, headers=headers, params=params) as response:
if response.status == 200:
data = await response.json()
if data["data"]:
box_art_url = data["data"][0]["box_art_url"]
formatted_url = box_art_url.replace("{width}", "285").replace("{height}", "380")
if validators.url(formatted_url):
log_info(f"Generated image URL for '{game_name}': {formatted_url}")
return formatted_url
else:
log_warning(f"Invalid image URL generated for '{game_name}': {formatted_url}")
async with self.session.get(url, headers=headers, params=params) as response:
if response.status == 200:
data = await response.json()
if data["data"]:
box_art_url = data["data"][0]["box_art_url"]
formatted_url = box_art_url.replace("{width}", "285").replace("{height}", "380")
if validators.url(formatted_url):
log_info(f"Generated image URL for '{game_name}': {formatted_url}")
return formatted_url
else:
log_warning(f"Invalid image URL generated for '{game_name}': {formatted_url}")
log_warning(f"No image found for game: {game_name}")
except Exception as e:
log_error(f"Error fetching image URL for {game_name}: {e}", exc_info=True)
Expand Down

0 comments on commit c75aa6d

Please sign in to comment.