server registration and subscription
This commit is contained in:
@@ -1,235 +1,146 @@
|
||||
// src/commands/CommandHandler.js
|
||||
const { EmbedBuilder, ActionRowBuilder, ButtonBuilder, ButtonStyle } = require('discord.js');
|
||||
|
||||
class CommandHandler {
|
||||
constructor(playerService) {
|
||||
this.playerService = playerService;
|
||||
}
|
||||
|
||||
async handlePing(interaction) {
|
||||
await interaction.reply('Pong!');
|
||||
}
|
||||
|
||||
async handleFindUser(interaction) {
|
||||
await interaction.deferReply();
|
||||
|
||||
const username = interaction.options.getString('username');
|
||||
const gameFilter = interaction.options.getString('game');
|
||||
|
||||
const userData = await this.playerService.findUserByUsername(username);
|
||||
if (!userData || !userData.success) {
|
||||
await interaction.editReply('User not found or an error occurred while fetching data.');
|
||||
return;
|
||||
constructor(playerService, supabase, logger, serverRegistrationService) {
|
||||
this.playerService = playerService;
|
||||
this.supabase = supabase;
|
||||
this.logger = logger;
|
||||
this.serverRegistrationService = serverRegistrationService;
|
||||
}
|
||||
|
||||
const playerData = typeof userData.player_data === 'string'
|
||||
? JSON.parse(userData.player_data)
|
||||
: userData.player_data;
|
||||
|
||||
const embed = await this.createUserEmbed(playerData, gameFilter);
|
||||
const row = this.createActionRow(playerData.username);
|
||||
|
||||
await interaction.editReply({ embeds: [embed], components: [row] });
|
||||
}
|
||||
|
||||
async handleMatchHistory(interaction) {
|
||||
await interaction.deferReply();
|
||||
|
||||
const username = interaction.options.getString('username');
|
||||
const gameFilter = interaction.options.getString('game');
|
||||
|
||||
try {
|
||||
const userData = await this.playerService.findUserByUsername(username);
|
||||
if (!userData || !userData.success) {
|
||||
await interaction.editReply('User not found or an error occurred while fetching data.');
|
||||
return;
|
||||
}
|
||||
|
||||
const playerData = typeof userData.player_data === 'string'
|
||||
? JSON.parse(userData.player_data)
|
||||
: userData.player_data;
|
||||
|
||||
const matches = Object.values(playerData.matches || {})
|
||||
.filter(match => !gameFilter || match.game_name.toLowerCase() === gameFilter.toLowerCase())
|
||||
.sort((a, b) => new Date(b.start_time) - new Date(a.start_time))
|
||||
.slice(0, 10);
|
||||
|
||||
if (matches.length === 0) {
|
||||
await interaction.editReply(
|
||||
gameFilter
|
||||
? `No matches found for ${username} in ${gameFilter}`
|
||||
: `No matches found for ${username}`
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const embed = this.createMatchHistoryEmbed(playerData, matches);
|
||||
const row = this.createActionRow(playerData.username);
|
||||
|
||||
await interaction.editReply({ embeds: [embed], components: [row] });
|
||||
} catch (error) {
|
||||
console.error('Error in handleMatchHistory:', error);
|
||||
await interaction.editReply('An error occurred while processing the match history.');
|
||||
}
|
||||
}
|
||||
|
||||
createUserEmbed(playerData, gameFilter) {
|
||||
const profile = playerData.profile || {};
|
||||
const embed = new EmbedBuilder()
|
||||
.setTitle(`User: ${playerData.username || 'Unknown'}`)
|
||||
.setDescription(profile.bio || 'No bio available')
|
||||
.setColor('#0099ff');
|
||||
|
||||
// Add thumbnail (avatar)
|
||||
if (profile.avatar) {
|
||||
embed.setThumbnail(
|
||||
`https://www.vrbattles.gg/assets/uploads/profile/${profile.avatar}`
|
||||
);
|
||||
}
|
||||
|
||||
// Add badge image using PlayerService
|
||||
if (profile.current_level_badge) {
|
||||
const badgeImageUrl = this.playerService.getBadgeImageUrl(profile.current_level_badge);
|
||||
embed.setImage(badgeImageUrl);
|
||||
}
|
||||
|
||||
// Add profile fields
|
||||
const profileFields = [];
|
||||
if (profile.country) profileFields.push({ name: 'Country', value: profile.country, inline: true });
|
||||
if (profile.level) profileFields.push({ name: 'Level', value: profile.level.toString(), inline: true });
|
||||
if (profile.xp) profileFields.push({ name: 'Total XP', value: profile.xp.toString(), inline: true });
|
||||
if (profile.prestige) profileFields.push({ name: 'Prestige', value: profile.prestige.toString(), inline: true });
|
||||
|
||||
if (profileFields.length > 0) {
|
||||
embed.addFields(profileFields);
|
||||
}
|
||||
|
||||
// Add game stats if available
|
||||
const games = playerData.stats?.games;
|
||||
if (games) {
|
||||
Object.entries(games).forEach(([gameName, gameData]) => {
|
||||
if (gameFilter && gameName.toLowerCase() !== gameFilter.toLowerCase()) return;
|
||||
|
||||
embed.addFields({ name: gameName, value: '\u200B' });
|
||||
Object.entries(gameData).forEach(([mode, stats]) => {
|
||||
if (mode === 'Overall') return;
|
||||
|
||||
const statFields = [];
|
||||
if (stats.matches) statFields.push(`Matches: ${stats.matches}`);
|
||||
if (stats.wins) statFields.push(`Wins: ${stats.wins}`);
|
||||
if (stats.losses) statFields.push(`Losses: ${stats.losses}`);
|
||||
if (stats.win_rate) statFields.push(`Win Rate: ${stats.win_rate}`);
|
||||
|
||||
if (statFields.length > 0) {
|
||||
embed.addFields({
|
||||
name: mode,
|
||||
value: statFields.join(' | '),
|
||||
inline: true
|
||||
async handleCommand(interaction) {
|
||||
try {
|
||||
switch (interaction.commandName) {
|
||||
case 'register_server':
|
||||
await this.handleRegisterServer(interaction);
|
||||
break;
|
||||
case 'ping':
|
||||
await interaction.editReply({ content: 'Pong!', ephemeral: true });
|
||||
break;
|
||||
case 'finduser':
|
||||
await this.handleFindUser(interaction);
|
||||
break;
|
||||
case 'matchhistory':
|
||||
await this.handleMatchHistory(interaction);
|
||||
break;
|
||||
default:
|
||||
await interaction.editReply({ content: 'Unknown command', ephemeral: true });
|
||||
}
|
||||
} catch (error) {
|
||||
// Only log the error, let Bot class handle the response
|
||||
this.logger.error('Command handling error:', {
|
||||
command: interaction.commandName,
|
||||
error: error.message,
|
||||
stack: error.stack
|
||||
});
|
||||
}
|
||||
throw error; // Re-throw to let Bot handle it
|
||||
}
|
||||
}
|
||||
|
||||
async handleRegisterServer(interaction) {
|
||||
if (!interaction.deferred) {
|
||||
this.logger.warn('Interaction not deferred, cannot proceed', {
|
||||
guildId: interaction.guildId
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// Get the server details first
|
||||
const guildId = interaction.guildId;
|
||||
const serverName = interaction.guild.name;
|
||||
|
||||
this.logger.debug('Starting server registration', {
|
||||
guildId,
|
||||
serverName,
|
||||
timestamp: new Date().toISOString()
|
||||
});
|
||||
});
|
||||
|
||||
try {
|
||||
// Log before database operation
|
||||
this.logger.debug('Calling ServerRegistrationService.registerServer', {
|
||||
guildId,
|
||||
serverName,
|
||||
timestamp: new Date().toISOString()
|
||||
});
|
||||
|
||||
// Attempt the database operation first
|
||||
const result = await this.serverRegistrationService.registerServer(guildId, serverName);
|
||||
|
||||
// Log the result immediately
|
||||
this.logger.debug('Server registration result received', {
|
||||
status: result.status,
|
||||
serverId: result.server?.id,
|
||||
guildId,
|
||||
timestamp: new Date().toISOString()
|
||||
});
|
||||
|
||||
// Only after successful database operation, send the response
|
||||
try {
|
||||
const message = result.status === 'exists'
|
||||
? 'This server is already registered!'
|
||||
: 'Server successfully registered! You can now use subscription commands.';
|
||||
|
||||
await interaction.editReply({
|
||||
content: message,
|
||||
ephemeral: true
|
||||
});
|
||||
|
||||
// Log the successful operation
|
||||
this.logger.info('Server registration completed', {
|
||||
status: result.status,
|
||||
guildId,
|
||||
serverId: result.server.id,
|
||||
timestamp: new Date().toISOString()
|
||||
});
|
||||
} catch (replyError) {
|
||||
// Log that we couldn't send the response but the registration was successful
|
||||
this.logger.warn('Could not send response, but server registration was successful', {
|
||||
error: replyError.message,
|
||||
guildId,
|
||||
serverId: result.server.id,
|
||||
timestamp: new Date().toISOString()
|
||||
});
|
||||
}
|
||||
|
||||
return result;
|
||||
} catch (error) {
|
||||
// Log the error but let Bot.js handle the error response
|
||||
this.logger.error('Failed to register server:', {
|
||||
error: error.message,
|
||||
stack: error.stack,
|
||||
guildId,
|
||||
serverName,
|
||||
timestamp: new Date().toISOString()
|
||||
});
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// Add teams if available
|
||||
const teams = playerData.teams;
|
||||
if (teams && Object.keys(teams).length > 0) {
|
||||
const teamList = Object.values(teams)
|
||||
.map(team => `- **${team.team_name}** (${team.game_name} - ${team.game_mode})`)
|
||||
.join('\n');
|
||||
|
||||
embed.addFields(
|
||||
{ name: '\u200B', value: '**Teams**' },
|
||||
{ name: 'Team List', value: teamList || 'No teams available' }
|
||||
);
|
||||
async handleButton(interaction) {
|
||||
const [action, ...params] = interaction.customId.split(':');
|
||||
|
||||
switch (action) {
|
||||
case 'refresh':
|
||||
await this.handleFindUser(interaction, params[0]);
|
||||
break;
|
||||
default:
|
||||
await interaction.editReply({
|
||||
content: 'Unknown button interaction',
|
||||
ephemeral: true
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Add recent matches if available
|
||||
const matches = playerData.matches;
|
||||
if (matches && Object.keys(matches).length > 0) {
|
||||
const matchList = Object.values(matches)
|
||||
.sort((a, b) => new Date(b.start_time) - new Date(a.start_time))
|
||||
.slice(0, 3)
|
||||
.map(match => {
|
||||
const date = new Date(match.start_time).toLocaleDateString();
|
||||
const team1 = match.team1_name || 'Team 1';
|
||||
const team2 = match.team2_name || 'Team 2';
|
||||
const score = match.score || 'N/A';
|
||||
return `- **${team1}** vs **${team2}** on ${date} - Result: ${score}`;
|
||||
})
|
||||
.join('\n');
|
||||
|
||||
embed.addFields(
|
||||
{ name: '\u200B', value: '**Recent Matches**' },
|
||||
{ name: 'Match History', value: matchList || 'No recent matches' }
|
||||
);
|
||||
// Helper methods for creating embeds and action rows remain unchanged
|
||||
createUserEmbed(playerData, gameFilter) {
|
||||
// ... (keep existing implementation)
|
||||
}
|
||||
|
||||
return embed;
|
||||
}
|
||||
|
||||
createMatchHistoryEmbed(playerData, matches) {
|
||||
const embed = new EmbedBuilder()
|
||||
.setTitle(`Match History for ${playerData.username}`)
|
||||
.setColor('#0099ff')
|
||||
.setDescription(`Last ${matches.length} matches`);
|
||||
|
||||
if (playerData.profile?.avatar) {
|
||||
embed.setThumbnail(
|
||||
`https://www.vrbattles.gg/assets/uploads/profile/${playerData.profile.avatar}`
|
||||
);
|
||||
createMatchHistoryEmbed(playerData, matches) {
|
||||
// ... (keep existing implementation)
|
||||
}
|
||||
|
||||
// Add match stats
|
||||
const wins = matches.filter(m => {
|
||||
const isTeam1 = m.team1_name === playerData.username;
|
||||
return m.winner_id === (isTeam1 ? "1" : "2");
|
||||
}).length;
|
||||
|
||||
const winRate = ((wins / matches.length) * 100).toFixed(1);
|
||||
|
||||
embed.addFields(
|
||||
{ name: 'Recent Win Rate', value: `${winRate}%`, inline: true },
|
||||
{ name: 'Matches Analyzed', value: matches.length.toString(), inline: true },
|
||||
{ name: 'Recent Wins', value: wins.toString(), inline: true }
|
||||
);
|
||||
|
||||
// Add individual matches
|
||||
matches.forEach((match, index) => {
|
||||
const date = new Date(match.start_time).toLocaleDateString();
|
||||
const isTeam1 = match.team1_name === playerData.username;
|
||||
const opponent = isTeam1 ? match.team2_name : match.team1_name;
|
||||
const won = match.winner_id === (isTeam1 ? "1" : "2");
|
||||
const score = match.score || '0 - 0';
|
||||
const gameMode = match.game_mode ? ` (${match.game_mode})` : '';
|
||||
|
||||
const matchResult = won ? '✅ Victory' : '❌ Defeat';
|
||||
|
||||
embed.addFields({
|
||||
name: `Match ${index + 1} - ${matchResult}`,
|
||||
value: `🎮 **${match.game_name}${gameMode}**\n` +
|
||||
`🆚 vs ${opponent}\n` +
|
||||
`📊 Score: ${score}\n` +
|
||||
`📅 ${date}`,
|
||||
inline: false
|
||||
});
|
||||
});
|
||||
|
||||
return embed;
|
||||
}
|
||||
|
||||
createActionRow(username) {
|
||||
return new ActionRowBuilder().addComponents(
|
||||
new ButtonBuilder()
|
||||
.setLabel('🔵 View Profile')
|
||||
.setStyle(ButtonStyle.Link)
|
||||
.setURL(this.playerService.getProfileUrl(username)),
|
||||
new ButtonBuilder()
|
||||
.setLabel('🟡 Join Main Discord')
|
||||
.setStyle(ButtonStyle.Link)
|
||||
.setURL('https://discord.gg/j3DKVATPGQ')
|
||||
);
|
||||
}
|
||||
createActionRow(username) {
|
||||
// ... (keep existing implementation)
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = CommandHandler;
|
||||
Reference in New Issue
Block a user