fix some the signin and check recent but need to fix profile

This commit is contained in:
Rainy21
2026-04-23 00:36:34 -04:00
parent 0a972f6a3f
commit a8ddd363a7
13 changed files with 233 additions and 109 deletions
Binary file not shown.
Binary file not shown.
Binary file not shown.
+23 -26
View File
@@ -1,11 +1,9 @@
import discord
from discord import app_commands
from discord.ext import commands
import aiohttp
import os
from database.db import save_user
RIOT_API_KEY = os.getenv("LEAGUEAPI")
from services.riot_api import get_account
class LoginCog(commands.Cog):
def __init__(self, bot):
@@ -13,7 +11,7 @@ class LoginCog(commands.Cog):
async def _handle_login(self, interaction: discord.Interaction, summoner: str):
await interaction.response.defer(ephemeral=True)
if "#" not in summoner:
await interaction.followup.send("❌ Use the format `Name#TAG`", ephemeral=True)
return
@@ -26,41 +24,40 @@ class LoginCog(commands.Cog):
discord_id = str(interaction.user.id)
url = (
f"https://americas.api.riotgames.com/riot/account/v1/accounts"
f"/by-riot-id/{game_name}/{tag_line}"
)
headers = {"X-Riot-Token": RIOT_API_KEY}
async with aiohttp.ClientSession() as session:
async with session.get(url, headers=headers) as resp:
if resp.status == 404:
await interaction.followup.send("❌ Summoner not found. Check your Riot ID.", ephemeral=True)
return
if resp.status != 200:
await interaction.followup.send(f"❌ Riot API error ({resp.status}). Try again later.", ephemeral=True)
return
# Use the service instead of direct API call
data = await get_account(game_name, tag_line)
data = await resp.json()
puuid = data["puuid"]
if data is None:
await interaction.followup.send("❌ Summoner not found. Check your Riot ID.", ephemeral=True)
return
if isinstance(data, dict) and "error" in data:
if data["error"] == 401:
await interaction.followup.send(
"❌ Riot API error (401): Unauthorized. "
"This usually means the bot's API key has expired. "
"Please notify the bot owner to refresh it at developer.riotgames.com.",
ephemeral=True
)
else:
await interaction.followup.send(
f"❌ Riot API error ({data['error']}). Try again later.",
ephemeral=True
)
return
puuid = data["puuid"]
save_user(discord_id, puuid, game_name, tag_line)
await interaction.followup.send(
f"✅ Linked **{game_name}#{tag_line}** to your Discord account!",
ephemeral=True
)
@app_commands.command(name="login", description="Link your Riot account")
@app_commands.describe(summoner="Your Riot ID (e.g. Name#TAG)")
async def login(self, interaction: discord.Interaction, summoner: str):
await self._handle_login(interaction, summoner)
@app_commands.command(name="signin", description="Link your Riot account")
@app_commands.describe(summoner="Your Riot ID (e.g. Name#TAG)")
async def signin(self, interaction: discord.Interaction, summoner: str):
await self._handle_login(interaction, summoner)
async def setup(bot):
await bot.add_cog(LoginCog(bot))
+32 -32
View File
@@ -1,13 +1,10 @@
import discord
from discord import app_commands
from discord.ext import commands
import aiohttp
import os
from database.db import get_user
RIOT_API_KEY = os.getenv("LEAGUEAPI")
REGION = "na1"
from services.riot_api import get_summoner, get_rank
class ProfileCog(commands.Cog):
def __init__(self, bot):
@@ -29,28 +26,38 @@ class ProfileCog(commands.Cog):
return
_, puuid, game_name, tag_line = user
headers = {"X-Riot-Token": RIOT_API_KEY}
async with aiohttp.ClientSession() as session:
# 1. Get summoner data (level) via PUUID
summoner = await fetch(
session,
f"https://{REGION}.api.riotgames.com/lol/summoner/v4/summoners/by-puuid/{puuid}",
headers
)
if not summoner:
await interaction.followup.send("❌ Could not fetch summoner data.")
return
# 1. Get summoner data (level) via PUUID
summoner = await get_summoner(puuid)
if not summoner:
await interaction.followup.send("❌ Could not fetch summoner data (Summoner not found).")
return
if isinstance(summoner, dict) and "error" in summoner:
if summoner["error"] == 401:
await interaction.followup.send("❌ Riot API error (401): Unauthorized. API Key might be expired.")
else:
await interaction.followup.send(f"❌ Riot API error ({summoner['error']}).")
return
summoner_id = summoner["id"]
level = summoner["summonerLevel"]
# Ensure 'id' exists before accessing it
if "id" not in summoner:
await interaction.followup.send("❌ Unexpected data format from Riot API.")
return
summoner_id = summoner["id"]
level = summoner.get("summonerLevel", "N/A")
# 2. Get rank & LP (League-v4)
leagues = await get_rank(summoner_id)
if leagues is None:
leagues = []
elif isinstance(leagues, dict) and "error" in leagues:
await interaction.followup.send(f"❌ Riot API error ({leagues['error']}).")
return
# 2. Get rank & LP (League-v4)
leagues = await fetch(
session,
f"https://{REGION}.api.riotgames.com/lol/league/v4/entries/by-summoner/{summoner_id}",
headers
)
# Parse ranked solo queue data
rank_info = get_solo_rank(leagues)
@@ -81,16 +88,9 @@ class ProfileCog(commands.Cog):
await interaction.followup.send(embed=embed)
# ── Helpers ────────────────────────────────────────────────────────────────────
#try to get the information
async def fetch(session:aiohttp.ClientSession, url: str, headers: dict):
async with session.get(url, headers=headers) as resp:
if resp.status != 200:
return None
return await resp.json()
def get_solo_rank(leagues: list) -> dict:
def get_solo_rank(leagues) -> dict:
"""Extract solo queue entry from league data."""
if not leagues:
if not isinstance(leagues, list) or not leagues:
return {}
for entry in leagues:
if entry.get("queueType") == "RANKED_SOLO_5x5":
+27 -46
View File
@@ -1,27 +1,25 @@
import discord
from discord import app_commands
from discord.ext import commands
import aiohttp
import os
import asyncio
from database.db import get_user
from services.riot_api import get_match_ids, get_match, get_latest_patch
RIOT_API_KEY = os.getenv("LEAGUEAPI")
REGION = "na1"
CLUSTER = "americas"
CLUSTER_MAP = {
"na1": "americas", "br1": "americas", "la1": "americas", "la2": "americas",
"euw1": "europe", "eun1": "europe", "tr1": "europe", "ru": "europe",
"kr": "asia", "jp1": "asia",
}
class RecentCog(commands.Cog):
def __init__(self, bot) -> None:
self.bot = bot
self.patch = "14.8.1"
async def _update_patch(self):
new_patch = await get_latest_patch()
if new_patch:
self.patch = new_patch
@app_commands.command(name = "recent", description="Show your last N matches")
@app_commands.describe(count="Number of matches to show (1–10, default 5)")
async def recent(self , interaction: discord.Interaction, count: int = 5):
await interaction.response.defer(ephemeral=False)
await self._update_patch()
count = max(1, min(count, 10)) # clamp between 1 and 10
discord_id = str(interaction.user.id)
@@ -36,32 +34,28 @@ class RecentCog(commands.Cog):
#get user
_, puuid, game_name, tag_line = user
cluster = CLUSTER_MAP.get(REGION, "americas")
headers = {"X-Riot-Token": RIOT_API_KEY}
#get user data
async with aiohttp.ClientSession() as session:
# 1. Fetch match ID list
match_ids = await fetch(
session,
f"https://{cluster}.api.riotgames.com/lol/match/v5/matches/by-puuid/{puuid}/ids?count={count}",
headers
)
if not match_ids:
await interaction.followup.send("❌ Could not fetch match history.")
return
# 1. Fetch match ID list
match_ids = await get_match_ids(puuid, count=count)
if match_ids is None:
await interaction.followup.send("❌ Could not fetch match history.")
return
# 2. Fetch each match in parallel
match_data = await fetch_all(session, [
f"https://{cluster}.api.riotgames.com/lol/match/v5/matches/{mid}"
for mid in match_ids
], headers)
if isinstance(match_ids, dict) and "error" in match_ids:
await interaction.followup.send(f"❌ Riot API error ({match_ids['error']}).")
return
# 2. Fetch each match in parallel (get_match handles caching internally)
match_data = await asyncio.gather(*[get_match(mid) for mid in match_ids])
embeds = []
for match in match_data:
if match:
embed = build_match_embed(match , puuid, game_name,tag_line)
if match and isinstance(match, dict) and "error" not in match:
embed = build_match_embed(match , puuid, game_name, tag_line, self.patch)
if embed:
embeds.append(embed)
if not embeds:
await interaction.followup.send("❌ No recent matches found.")
return
@@ -78,19 +72,6 @@ class RecentCog(commands.Cog):
# ── Helpers ────────────────────────────────────────────────────────────────────
async def fetch(session: aiohttp.ClientSession, url: str, headers: dict):
async with session.get(url, headers=headers) as resp:
if resp.status != 200:
return None
return await resp.json()
async def fetch_all(session: aiohttp.ClientSession, urls: list, headers: dict):
"""Fetch multiple URLs concurrently."""
import asyncio
return await asyncio.gather(*[fetch(session, url, headers) for url in urls])
def get_player(match: dict, puuid: str) -> dict:
"""Find this player's participant data within the match."""
participants = match["info"]["participants"]
@@ -118,7 +99,7 @@ def queue_name(queue_id: int) -> str:
return queues.get(queue_id, "Other")
def build_match_embed(match: dict, puuid: str, game_name: str, tag_line: str):
def build_match_embed(match: dict, puuid: str, game_name: str, tag_line: str, patch: str):
player = get_player(match, puuid)
if not player:
return None
@@ -145,7 +126,7 @@ def build_match_embed(match: dict, puuid: str, game_name: str, tag_line: str):
embed.add_field(name="🌾 CS", value=f"{cs} ({cs_per_min}/min)", inline=True)
embed.add_field(name="👤 Player", value=f"{game_name}#{tag_line}", inline=True)
embed.set_thumbnail(
url=f"https://ddragon.leagueoflegends.com/cdn/14.8.1/img/champion/{champion}.png"
url=f"https://ddragon.leagueoflegends.com/cdn/{patch}/img/champion/{champion}.png"
)
return embed