Refactor _make_request method in ModrinthTracker to streamline API request handling. Simplify retry logic, enhance session management, and improve error handling for network issues. Update response handling to return JSON data directly.
Some checks are pending
Run pre-commit / Run pre-commit (push) Waiting to run

This commit is contained in:
Valerie 2025-05-23 06:24:35 -04:00
parent fd2ace3025
commit 07f32c7b05

View file

@ -57,34 +57,37 @@ class ModrinthTracker(commands.Cog):
self.request_timestamps.append(current_time) self.request_timestamps.append(current_time)
async def _make_request(self, url, params=None, retries=3): async def _make_request(self, url, params=None):
"""Make a rate-limited request to the Modrinth API""" """Make a rate-limited request to the Modrinth API"""
await self._rate_limit() try:
# Ensure session is available
for attempt in range(retries): if self.session is None or self.session.closed:
try:
# Ensure session is available
if self.session is None or self.session.closed:
self.session = aiohttp.ClientSession()
async with self.session.get(url, params=params) as response:
if response.status == 429: # Too Many Requests
retry_after = int(response.headers.get('Retry-After', 60))
await asyncio.sleep(retry_after)
continue
return response
except (aiohttp.ClientConnectorError, aiohttp.ClientError) as e:
if attempt == retries - 1: # Last attempt
raise
# Close and recreate session
if self.session and not self.session.closed:
await self.session.close()
self.session = aiohttp.ClientSession() self.session = aiohttp.ClientSession()
await asyncio.sleep(1) # Wait a bit before retrying
except Exception as e: async with self.session.get(url, params=params) as response:
self.bot.logger.error(f"Error in _make_request: {str(e)}", exc_info=True) if response.status == 429: # Too Many Requests
raise retry_after = int(response.headers.get('Retry-After', 60))
await asyncio.sleep(retry_after)
return await self._make_request(url, params)
# Store response data before closing
if response.status == 200:
return await response.json()
return None
except (aiohttp.ClientConnectorError, aiohttp.ClientError) as e:
# Close and recreate session
if self.session and not self.session.closed:
await self.session.close()
self.session = aiohttp.ClientSession()
# Try one more time
async with self.session.get(url, params=params) as response:
if response.status == 200:
return await response.json()
return None
except Exception as e:
self.bot.logger.error(f"Error in _make_request: {str(e)}", exc_info=True)
raise
@commands.group() @commands.group()
@checks.admin() @checks.admin()
@ -102,18 +105,16 @@ class ModrinthTracker(commands.Cog):
""" """
try: try:
# Verify the project exists and get its info # Verify the project exists and get its info
response = await self._make_request(f"{BASE_URL}/project/{project_id}") project_data = await self._make_request(f"{BASE_URL}/project/{project_id}")
if response.status != 200: if not project_data:
await ctx.send(f"Error: Project `{project_id}` not found on Modrinth.") await ctx.send(f"Error: Project `{project_id}` not found on Modrinth.")
return return
project_data = await response.json()
# Get the latest version # Get the latest version
response = await self._make_request(f"{BASE_URL}/project/{project_id}/version") versions = await self._make_request(f"{BASE_URL}/project/{project_id}/version")
if response.status != 200: if not versions:
await ctx.send("Error: Could not fetch version information.") await ctx.send("Error: Could not fetch version information.")
return return
versions = await response.json()
latest_version = versions[0] if versions else None latest_version = versions[0] if versions else None
tracked_projects = await self.config.guild(ctx.guild).tracked_projects() tracked_projects = await self.config.guild(ctx.guild).tracked_projects()
@ -175,7 +176,7 @@ class ModrinthTracker(commands.Cog):
except aiohttp.ClientConnectorError: except aiohttp.ClientConnectorError:
await ctx.send("Error: Failed to connect to Modrinth API. Please try again in a few moments.") await ctx.send("Error: Failed to connect to Modrinth API. Please try again in a few moments.")
except aiohttp.ClientError as e: except aiohttp.ClientError as e:
await ctx.send(f"Error: Network error occurred while contacting Modrinth API. Please try again in a few moments.") await ctx.send("Error: Network error occurred while contacting Modrinth API. Please try again in a few moments.")
except asyncio.TimeoutError: except asyncio.TimeoutError:
await ctx.send("Error: Request to Modrinth API timed out. Please try again.") await ctx.send("Error: Request to Modrinth API timed out. Please try again.")
except Exception as e: except Exception as e: