Skip to content

Commit 8dc9a5b

Browse files
Enhance my_team_command: add user registration check, improve team assignment messages, and include last sync time in response
1 parent bbac5ef commit 8dc9a5b

File tree

3 files changed

+83
-19
lines changed

3 files changed

+83
-19
lines changed

bot.py

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -601,11 +601,26 @@ async def my_team_command(interaction: discord.Interaction):
601601
)
602602
return
603603

604+
# Get the user's registered Matcherino username
605+
matcherino_username = await db.get_matcherino_username(user_id)
606+
if not matcherino_username:
607+
await interaction.followup.send(
608+
"You haven't registered your Matcherino username yet. Please use `/register <matcherino_username>` to set your username.",
609+
ephemeral=True
610+
)
611+
return
612+
613+
# Get user's team information
604614
team_info = await db.get_user_team(user_id)
605615

606616
if not team_info:
607617
await interaction.followup.send(
608-
"You are not currently assigned to any team. Make sure you've registered with your Matcherino username using the /register command.",
618+
f"You are not currently assigned to any team. Your registered Matcherino username is **{matcherino_username}**.\n\n"
619+
"Possible reasons:\n"
620+
"1. You haven't joined a team on Matcherino yet\n"
621+
"2. Your Matcherino username doesn't match what's in the database\n"
622+
"3. Teams haven't been synced recently\n\n"
623+
"Please verify your username with `/verify-username` or ask an admin to run `/sync-teams`.",
609624
ephemeral=True
610625
)
611626
return
@@ -621,7 +636,7 @@ async def my_team_command(interaction: discord.Interaction):
621636
# Add members to the embed
622637
member_list = ""
623638
for member in team_info['members']:
624-
is_you = " (You)" if str(member.get('discord_id', "")) == str(user_id) else ""
639+
is_you = " (You)" if str(member.get('discord_user_id', "")) == str(user_id) else ""
625640
discord_user = f" (Discord: {member['discord_username']})" if member.get('discord_username') else ""
626641
member_list += f"• {member['member_name']}{discord_user}{is_you}\n"
627642

@@ -631,6 +646,10 @@ async def my_team_command(interaction: discord.Interaction):
631646
inline=False
632647
)
633648

649+
# Add footer with last sync time
650+
if 'last_updated' in team_info:
651+
embed.set_footer(text=f"Team data last updated: {team_info['last_updated'].strftime('%Y-%m-%d %H:%M:%S UTC')}")
652+
634653
await interaction.followup.send(embed=embed, ephemeral=True)
635654

636655
except Exception as e:

db.py

Lines changed: 49 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -258,6 +258,9 @@ async def update_matcherino_teams(self, teams_data):
258258
# Process each team
259259
for team in teams_data:
260260
team_name = team['name']
261+
team_id_from_api = team.get('team_id') # Use API-provided team ID
262+
263+
logger.info(f"Processing team: {team_name} (ID from API: {team_id_from_api})")
261264

262265
# Insert or update team
263266
team_id = await conn.fetchval(
@@ -279,15 +282,13 @@ async def update_matcherino_teams(self, teams_data):
279282

280283
# Insert team members
281284
if team.get('members'):
285+
matched_count = 0
282286
for member_name in team['members']:
283-
# Try to find matching Discord user
284-
discord_user_id = await conn.fetchval(
285-
"""
286-
SELECT user_id FROM registrations
287-
WHERE matcherino_username = $1
288-
""",
289-
member_name
290-
)
287+
# Try to find matching Discord user with various matching strategies
288+
discord_user_id = await self._find_discord_user_for_member(conn, member_name)
289+
290+
if discord_user_id:
291+
matched_count += 1
291292

292293
# Insert team member with Discord user ID if found
293294
await conn.execute(
@@ -298,12 +299,39 @@ async def update_matcherino_teams(self, teams_data):
298299
""",
299300
team_id, member_name, discord_user_id
300301
)
302+
303+
logger.info(f"Team {team_name}: matched {matched_count}/{len(team['members'])} members to Discord users")
301304

302305
logger.info(f"Successfully updated {len(teams_data)} teams in database")
303306
except Exception as e:
304307
logger.error(f"Error updating Matcherino teams in database: {e}")
305308
raise
306309

310+
async def _find_discord_user_for_member(self, conn, member_name):
311+
"""
312+
Helper method to find a Discord user ID for a Matcherino member name using
313+
exact matching only.
314+
315+
Args:
316+
conn: Database connection
317+
member_name: The member name from the Matcherino API
318+
319+
Returns:
320+
int: Discord user ID if found, None otherwise
321+
"""
322+
# Only use exact match on matcherino_username
323+
discord_user_id = await conn.fetchval(
324+
"SELECT user_id FROM registrations WHERE matcherino_username = $1",
325+
member_name
326+
)
327+
328+
if discord_user_id:
329+
return discord_user_id
330+
331+
# No match found
332+
logger.info(f"No Discord user match found for Matcherino member: {member_name}")
333+
return None
334+
307335
async def get_matcherino_teams(self, active_only=True):
308336
"""
309337
Get all teams from the database with their members.
@@ -394,7 +422,7 @@ async def get_user_team(self, user_id):
394422
# Get team for this user
395423
team = await conn.fetchrow(
396424
"""
397-
SELECT t.*, tm.member_name
425+
SELECT t.team_id, t.team_name, t.last_updated
398426
FROM matcherino_teams t
399427
JOIN team_members tm ON t.team_id = tm.team_id
400428
WHERE tm.discord_user_id = $1 AND t.is_active = TRUE
@@ -405,21 +433,27 @@ async def get_user_team(self, user_id):
405433
if not team:
406434
return None
407435

408-
# Get all teammates
409-
teammates = await conn.fetch(
436+
# Get all members of the team, including the user
437+
members = await conn.fetch(
410438
"""
411439
SELECT tm.member_name, tm.discord_user_id, r.username AS discord_username
412440
FROM team_members tm
413441
LEFT JOIN registrations r ON tm.discord_user_id = r.user_id
414-
WHERE tm.team_id = $1 AND tm.discord_user_id != $2
415-
ORDER BY tm.member_name
442+
WHERE tm.team_id = $1
443+
ORDER BY
444+
CASE WHEN tm.discord_user_id = $2 THEN 0 ELSE 1 END,
445+
tm.member_name
416446
""",
417447
team['team_id'], user_id
418448
)
419449

420450
# Convert to dictionary
421-
result = dict(team)
422-
result['teammates'] = [dict(teammate) for teammate in teammates]
451+
result = {
452+
'team_id': team['team_id'],
453+
'team_name': team['team_name'],
454+
'last_updated': team['last_updated'],
455+
'members': [dict(member) for member in members]
456+
}
423457

424458
return result
425459
except Exception as e:

matcherino_scraper.py

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,9 @@ async def get_teams_data(self, tournament_id: Optional[str] = None) -> List[Dict
141141
# Get team name, with fallback
142142
team_name = team.get('name', 'Unknown Team')
143143

144+
# Get the correct team ID (use id field directly from the team object)
145+
team_id = team.get('id')
146+
144147
# Extract team members - checking both 'members' and possibly nested 'team.members'
145148
members = []
146149

@@ -149,6 +152,14 @@ async def get_teams_data(self, tournament_id: Optional[str] = None) -> List[Dict
149152
for member in team['members']:
150153
if 'displayName' in member:
151154
display_name = member['displayName'].strip()
155+
# Get the correct bountyTeamId from the member if present
156+
bounty_team_id = member.get('bountyTeamId', None)
157+
158+
# If bountyTeamId is present on the member, use it to verify team matching
159+
if bounty_team_id is not None and bounty_team_id != team_id:
160+
# If bountyTeamId doesn't match team.id, log it but still include the member
161+
logger.info(f"Member {display_name} has bountyTeamId {bounty_team_id} that doesn't match team.id {team_id}")
162+
152163
members.append({
153164
'name': display_name,
154165
'user_id': member.get('userId', ''),
@@ -179,8 +190,8 @@ async def get_teams_data(self, tournament_id: Optional[str] = None) -> List[Dict
179190
'name': team_name,
180191
'members': member_names,
181192
'members_data': members, # Full member data
182-
'team_id': team.get('id') or (team.get('team', {}) or {}).get('id', None),
183-
'bounty_team_id': team.get('bountyTeamId', None),
193+
'team_id': team_id, # Use the direct team ID
194+
'bounty_team_id': team.get('id'), # Store the ID in a separate field as well
184195
'created_at': team.get('createdAt', None),
185196
'raw_data': team # Include the raw data for debugging/future use
186197
})

0 commit comments

Comments
 (0)