server registration and subscription
This commit is contained in:
343
src/Bot.js
343
src/Bot.js
@@ -1,263 +1,144 @@
|
||||
const { Client, GatewayIntentBits } = require("discord.js");
|
||||
const CommandHandler = require("./commands/CommandHandler.js");
|
||||
const PlayerService = require("./services/PlayerService.js");
|
||||
const NotificationService = require("./services/NotificationService.js");
|
||||
const MatchCommands = require("./commands/MatchCommands.js");
|
||||
const SupabaseService = require("./services/SupabaseService.js");
|
||||
const SubscriptionCommands = require("./commands/SubscriptionCommands.js");
|
||||
const CooldownManager = require("./utils/CooldownManager.js");
|
||||
const Logger = require("./utils/Logger.js");
|
||||
const { Client, GatewayIntentBits } = require('discord.js');
|
||||
const CommandHandler = require('./commands/CommandHandler');
|
||||
const SubscriptionCommands = require('./commands/SubscriptionCommands');
|
||||
const PlayerService = require('./services/PlayerService');
|
||||
const SupabaseService = require('./services/SupabaseService');
|
||||
const NotificationService = require('./services/NotificationService');
|
||||
const Logger = require('./utils/Logger');
|
||||
const ServerRegistrationService = require('./services/ServerRegistrationService');
|
||||
|
||||
class Bot {
|
||||
constructor() {
|
||||
this.logger = new Logger('Bot');
|
||||
this.cooldownManager = new CooldownManager();
|
||||
constructor(token, supabase, logger) {
|
||||
if (!logger || typeof logger.error !== 'function') {
|
||||
throw new Error('Invalid logger provided to Bot constructor');
|
||||
}
|
||||
|
||||
this.client = new Client({
|
||||
intents: [
|
||||
GatewayIntentBits.Guilds,
|
||||
GatewayIntentBits.GuildMessages,
|
||||
GatewayIntentBits.MessageContent,
|
||||
],
|
||||
this.client = new Client({ intents: [GatewayIntentBits.Guilds] });
|
||||
this.token = token;
|
||||
this.supabase = supabase;
|
||||
this.logger = logger;
|
||||
this.processingLock = new Map();
|
||||
|
||||
// Initialize services
|
||||
this.playerService = new PlayerService(logger);
|
||||
this.serverRegistrationService = new ServerRegistrationService(supabase, logger);
|
||||
|
||||
// Initialize command handlers
|
||||
this.commandHandler = new CommandHandler(
|
||||
this.playerService,
|
||||
this.supabase,
|
||||
this.logger,
|
||||
this.serverRegistrationService
|
||||
);
|
||||
|
||||
this.subscriptionCommands = new SubscriptionCommands(supabase, logger);
|
||||
|
||||
// Setup event handlers
|
||||
this.client.on('ready', () => {
|
||||
this.logger.info(`Logged in as ${this.client.user.tag}`);
|
||||
});
|
||||
|
||||
this.logger.info('Initializing bot...');
|
||||
this.initializeServices();
|
||||
this.setupEventHandlers();
|
||||
}
|
||||
|
||||
initializeServices() {
|
||||
this.logger.debug('Initializing services...');
|
||||
|
||||
this.playerService = new PlayerService();
|
||||
this.commandHandler = new CommandHandler(this.playerService);
|
||||
this.matchCommands = new MatchCommands(this.playerService);
|
||||
this.notificationService = new NotificationService(this);
|
||||
|
||||
this.initializeSupabase();
|
||||
}
|
||||
|
||||
initializeSupabase() {
|
||||
this.logger.debug('Initializing Supabase service...');
|
||||
this.supabaseService = new SupabaseService();
|
||||
|
||||
if (this.supabaseService.supabase) {
|
||||
this.subscriptionCommands = new SubscriptionCommands(this.supabaseService);
|
||||
this.logger.info('Supabase service initialized successfully');
|
||||
} else {
|
||||
this.logger.warn('Supabase initialization failed. Subscription commands unavailable.');
|
||||
this.subscriptionCommands = null;
|
||||
}
|
||||
}
|
||||
|
||||
setupEventHandlers() {
|
||||
this.logger.debug('Setting up event handlers...');
|
||||
this.client.on('error', this.handleError.bind(this));
|
||||
this.client.once('ready', this.handleReady.bind(this));
|
||||
this.client.on('interactionCreate', this.handleInteraction.bind(this));
|
||||
}
|
||||
|
||||
async start(token) {
|
||||
this.logger.info('Starting bot...');
|
||||
async start() {
|
||||
try {
|
||||
await this.client.login(token);
|
||||
this.logger.info('Login successful');
|
||||
|
||||
const port = process.env.NOTIFICATION_PORT || 3000;
|
||||
await this.notificationService.start(port);
|
||||
this.logger.info(`Notification service started on port ${port}`);
|
||||
await this.client.login(this.token);
|
||||
} catch (error) {
|
||||
this.logger.error('Startup failed:', error);
|
||||
this.logger.error('Failed to start bot:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async stop() {
|
||||
this.logger.info('Stopping bot...');
|
||||
try {
|
||||
await this.notificationService.stop();
|
||||
await this.client.destroy();
|
||||
this.logger.info('Bot stopped successfully');
|
||||
} catch (error) {
|
||||
this.logger.error('Error stopping bot:', error);
|
||||
throw error;
|
||||
async handleInteraction(interaction) {
|
||||
if (!interaction.isCommand() && !interaction.isButton()) {
|
||||
this.logger.debug('Ignoring non-command/button interaction');
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
handleError(error) {
|
||||
this.logger.error('Discord client error:', error);
|
||||
}
|
||||
|
||||
handleReady() {
|
||||
this.logger.info(`Logged in as ${this.client.user.tag}`);
|
||||
}
|
||||
|
||||
handleInteraction(interaction) {
|
||||
this.logger.debug('Received interaction', {
|
||||
type: interaction.type,
|
||||
commandName: interaction.commandName,
|
||||
user: interaction.user.tag,
|
||||
guild: interaction.guild?.name,
|
||||
channel: interaction.channel?.name
|
||||
});
|
||||
|
||||
if (interaction.isCommand()) {
|
||||
this.handleCommand(interaction)
|
||||
.catch(error => this.handleInteractionError(interaction, error));
|
||||
} else if (interaction.isButton()) {
|
||||
this.handleButton(interaction)
|
||||
.catch(error => this.handleInteractionError(interaction, error));
|
||||
const lockKey = interaction.id;
|
||||
if (this.processingLock.get(lockKey)) {
|
||||
this.logger.debug('Interaction already being processed', { id: lockKey });
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
async handleCommand(interaction) {
|
||||
// Set the lock before any async operations
|
||||
this.processingLock.set(lockKey, true);
|
||||
|
||||
try {
|
||||
// Check cooldown
|
||||
const cooldownTime = this.cooldownManager.checkCooldown(interaction);
|
||||
if (cooldownTime > 0) {
|
||||
// Special handling for register_server command
|
||||
if (interaction.isCommand() && interaction.commandName === 'register_server') {
|
||||
// Send initial response immediately
|
||||
await interaction.reply({
|
||||
content: `Please wait ${cooldownTime.toFixed(1)} more seconds before using this command again.`,
|
||||
content: 'Attempting to register server...',
|
||||
ephemeral: true
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
this.logger.debug('Processing command', {
|
||||
command: interaction.commandName,
|
||||
user: interaction.user.tag
|
||||
});
|
||||
const guildId = interaction.guildId;
|
||||
const serverName = interaction.guild.name;
|
||||
|
||||
await this.processCommand(interaction);
|
||||
|
||||
} catch (error) {
|
||||
this.logger.error('Command error:', error);
|
||||
await this.handleCommandError(interaction, error);
|
||||
}
|
||||
}
|
||||
|
||||
async processCommand(interaction) {
|
||||
switch (interaction.commandName) {
|
||||
case "ping":
|
||||
await this.commandHandler.handlePing(interaction);
|
||||
break;
|
||||
case "finduser":
|
||||
await this.commandHandler.handleFindUser(interaction);
|
||||
break;
|
||||
case "matchhistory":
|
||||
await this.commandHandler.handleMatchHistory(interaction);
|
||||
break;
|
||||
case "subscribe":
|
||||
case "unsubscribe":
|
||||
case "list_subscriptions":
|
||||
await this.handleSubscriptionCommand(interaction);
|
||||
break;
|
||||
default:
|
||||
await interaction.reply({
|
||||
content: "Unknown command",
|
||||
ephemeral: true
|
||||
this.logger.debug('Starting server registration', {
|
||||
guildId,
|
||||
serverName,
|
||||
timestamp: new Date().toISOString()
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async handleSubscriptionCommand(interaction) {
|
||||
if (!this.subscriptionCommands) {
|
||||
await this.safeReply(interaction, "Subscription commands are not available.");
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
// Defer the reply immediately
|
||||
await this.safeReply(interaction, "Processing your request...");
|
||||
|
||||
switch (interaction.commandName) {
|
||||
case "subscribe":
|
||||
await this.subscriptionCommands.handleSubscribe(interaction);
|
||||
break;
|
||||
case "unsubscribe":
|
||||
await this.subscriptionCommands.handleUnsubscribe(interaction);
|
||||
break;
|
||||
case "list_subscriptions":
|
||||
await this.subscriptionCommands.handleListSubscriptions(interaction);
|
||||
break;
|
||||
}
|
||||
} catch (error) {
|
||||
this.logger.error('Subscription command error:', error);
|
||||
await this.safeReply(interaction, 'An error occurred while processing your request.');
|
||||
}
|
||||
}
|
||||
async handleButton(interaction) {
|
||||
const [action, matchId] = interaction.customId.split("_match_");
|
||||
|
||||
try {
|
||||
this.logger.debug('Processing button interaction', {
|
||||
action,
|
||||
matchId,
|
||||
user: interaction.user.tag
|
||||
});
|
||||
|
||||
switch (action) {
|
||||
case "accept":
|
||||
await this.matchCommands.handleMatchAccept(interaction, matchId);
|
||||
break;
|
||||
case "view":
|
||||
await this.matchCommands.handleViewDetails(interaction, matchId);
|
||||
break;
|
||||
default:
|
||||
this.logger.warn('Unknown button action', { action });
|
||||
await interaction.reply({
|
||||
content: "Unknown button action",
|
||||
ephemeral: true,
|
||||
try {
|
||||
// Attempt database operation first
|
||||
const result = await this.serverRegistrationService.registerServer(guildId, serverName);
|
||||
|
||||
this.logger.info('Server registration database operation completed', {
|
||||
status: result.status,
|
||||
guildId,
|
||||
serverId: result.server.id,
|
||||
timestamp: new Date().toISOString()
|
||||
});
|
||||
|
||||
// Update the response with the result
|
||||
const message = result.status === 'exists'
|
||||
? '⚠️ This Discord server is already registered with BattleBot.'
|
||||
: '✅ Server successfully registered with BattleBot! You can now use subscription commands.';
|
||||
|
||||
await interaction.editReply({
|
||||
content: message,
|
||||
ephemeral: true
|
||||
});
|
||||
|
||||
} catch (dbError) {
|
||||
this.logger.error('Server registration failed:', {
|
||||
error: dbError.message,
|
||||
stack: dbError.stack,
|
||||
guildId,
|
||||
timestamp: new Date().toISOString()
|
||||
});
|
||||
|
||||
await interaction.editReply({
|
||||
content: '❌ Failed to register server. Please try again.',
|
||||
ephemeral: true
|
||||
});
|
||||
}
|
||||
} else if (interaction.isCommand()) {
|
||||
// Handle all other commands through the command handler
|
||||
await this.commandHandler.handleCommand(interaction);
|
||||
} else if (interaction.isButton()) {
|
||||
// Handle button interactions
|
||||
await this.commandHandler.handleButton(interaction);
|
||||
}
|
||||
} catch (error) {
|
||||
this.logger.error("Error handling button:", error);
|
||||
await this.handleInteractionError(interaction, error);
|
||||
}
|
||||
}
|
||||
|
||||
async handleCommandError(interaction, error) {
|
||||
this.logger.error('Command error:', error);
|
||||
try {
|
||||
if (!interaction.replied && !interaction.deferred) {
|
||||
await interaction.reply({
|
||||
content: 'An error occurred while processing your command.',
|
||||
ephemeral: true
|
||||
});
|
||||
} else if (interaction.deferred && !interaction.replied) {
|
||||
await interaction.editReply('An error occurred while processing your command.');
|
||||
}
|
||||
} catch (e) {
|
||||
this.logger.error('Error sending error message:', e);
|
||||
}
|
||||
}
|
||||
|
||||
async safeReply(interaction, content, options = {}) {
|
||||
try {
|
||||
if (!interaction.deferred && !interaction.replied) {
|
||||
await interaction.reply({ content, ephemeral: true, ...options });
|
||||
} else if (interaction.deferred && !interaction.replied) {
|
||||
await interaction.editReply({ content, ...options });
|
||||
}
|
||||
} catch (error) {
|
||||
this.logger.error('Error in safeReply:', error);
|
||||
}
|
||||
}
|
||||
|
||||
async handleInteractionError(interaction, error) {
|
||||
this.logger.error('Interaction error:', error);
|
||||
try {
|
||||
if (!interaction.replied && !interaction.deferred) {
|
||||
await interaction.reply({
|
||||
content: 'An error occurred while processing your request.',
|
||||
ephemeral: true
|
||||
});
|
||||
} else if (interaction.deferred && !interaction.replied) {
|
||||
await interaction.editReply({
|
||||
content: 'An error occurred while processing your request.'
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
this.logger.error('Error sending error message:', e);
|
||||
this.logger.error('Command processing error:', {
|
||||
error: error.message,
|
||||
stack: error.stack,
|
||||
command: interaction.commandName,
|
||||
guild: interaction.guild?.name,
|
||||
timestamp: new Date().toISOString()
|
||||
});
|
||||
} finally {
|
||||
this.processingLock.delete(lockKey);
|
||||
this.logger.debug('Interaction processing completed', {
|
||||
id: lockKey,
|
||||
command: interaction.commandName,
|
||||
timestamp: new Date().toISOString()
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
File diff suppressed because it is too large
Load Diff
82
src/services/ServerRegistrationService.js
Normal file
82
src/services/ServerRegistrationService.js
Normal file
@@ -0,0 +1,82 @@
|
||||
class ServerRegistrationService {
|
||||
constructor(supabase, logger) {
|
||||
this.supabase = supabase;
|
||||
this.logger = logger;
|
||||
// Log when service is instantiated
|
||||
this.logger.info('ServerRegistrationService initialized');
|
||||
}
|
||||
|
||||
async registerServer(guildId, serverName) {
|
||||
// Add entry point log
|
||||
this.logger.info('registerServer method called', {
|
||||
guildId,
|
||||
serverName,
|
||||
timestamp: new Date().toISOString()
|
||||
});
|
||||
|
||||
try {
|
||||
this.logger.debug('Starting server registration process', {
|
||||
guildId,
|
||||
serverName,
|
||||
timestamp: new Date().toISOString()
|
||||
});
|
||||
|
||||
const { data: existingServer, error: checkError } = await this.supabase
|
||||
.from('servers')
|
||||
.select('*')
|
||||
.eq('discord_server_id', guildId)
|
||||
.single();
|
||||
|
||||
// Log the database query result
|
||||
this.logger.debug('Database query result', {
|
||||
hasExistingServer: !!existingServer,
|
||||
hasError: !!checkError,
|
||||
errorCode: checkError?.code
|
||||
});
|
||||
|
||||
if (existingServer) {
|
||||
this.logger.info('Server already exists', {
|
||||
serverId: existingServer.id,
|
||||
guildId
|
||||
});
|
||||
return { status: 'exists', server: existingServer };
|
||||
}
|
||||
|
||||
if (!existingServer || checkError?.code === 'PGRST116') {
|
||||
this.logger.debug('Attempting to create new server');
|
||||
const { data: newServer, error: insertError } = await this.supabase
|
||||
.from('servers')
|
||||
.insert([{
|
||||
discord_server_id: guildId,
|
||||
server_name: serverName,
|
||||
active: true
|
||||
}])
|
||||
.select()
|
||||
.single();
|
||||
|
||||
if (insertError) {
|
||||
this.logger.error('Failed to insert new server', { error: insertError });
|
||||
throw insertError;
|
||||
}
|
||||
|
||||
this.logger.info('New server created successfully', {
|
||||
serverId: newServer.id,
|
||||
guildId
|
||||
});
|
||||
return { status: 'created', server: newServer };
|
||||
}
|
||||
|
||||
throw checkError;
|
||||
} catch (error) {
|
||||
this.logger.error('Error in registerServer:', {
|
||||
error: error.message,
|
||||
stack: error.stack,
|
||||
guildId,
|
||||
serverName
|
||||
});
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = ServerRegistrationService;
|
||||
@@ -1,142 +1,370 @@
|
||||
const { createClient } = require('@supabase/supabase-js');
|
||||
const Logger = require('../utils/Logger');
|
||||
|
||||
class SupabaseService {
|
||||
constructor() {
|
||||
this.logger = new Logger('SupabaseService');
|
||||
const supabaseUrl = process.env.SUPABASE_URL;
|
||||
const supabaseKey = process.env.SUPABASE_KEY;
|
||||
|
||||
if (!supabaseUrl || !supabaseKey) {
|
||||
console.error('Supabase URL or key is missing. Please check your .env file.');
|
||||
this.logger.error('Missing configuration', {
|
||||
hasUrl: !!supabaseUrl,
|
||||
hasKey: !!supabaseKey
|
||||
});
|
||||
this.supabase = null;
|
||||
} else {
|
||||
this.supabase = createClient(supabaseUrl, supabaseKey);
|
||||
this.logger.debug('Supabase client created');
|
||||
}
|
||||
}
|
||||
|
||||
async testConnection() {
|
||||
if (!this.supabase) {
|
||||
console.error('Supabase client is not initialized.');
|
||||
this.logger.error('Client not initialized');
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
const { data, error } = await this.supabase
|
||||
this.logger.debug('Testing database connection...');
|
||||
|
||||
// Test servers table
|
||||
const { data: serverTest, error: serverError } = await this.supabase
|
||||
.from('servers')
|
||||
.select('count')
|
||||
.limit(1);
|
||||
|
||||
if (serverError) {
|
||||
this.logger.error('Server table test failed:', serverError);
|
||||
return false;
|
||||
}
|
||||
|
||||
// Test games table
|
||||
const { data: gameTest, error: gameError } = await this.supabase
|
||||
.from('games')
|
||||
.select('count')
|
||||
.limit(1);
|
||||
|
||||
if (error) {
|
||||
console.error('Supabase connection test error:', error);
|
||||
|
||||
if (gameError) {
|
||||
this.logger.error('Games table test failed:', gameError);
|
||||
return false;
|
||||
}
|
||||
|
||||
console.log('Supabase connection successful');
|
||||
this.logger.info('Database connection successful');
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.error('Supabase connection test failed:', error);
|
||||
this.logger.error('Connection test failed:', {
|
||||
error: error.message,
|
||||
stack: error.stack
|
||||
});
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async ensureServerRegistered(guildId, serverName) {
|
||||
try {
|
||||
this.logger.debug('Ensuring server is registered', { guildId, serverName });
|
||||
|
||||
// Try to find existing server
|
||||
const { data: existingServer, error: fetchError } = await this.supabase
|
||||
.from('servers')
|
||||
.select('*')
|
||||
.eq('discord_server_id', guildId)
|
||||
.single();
|
||||
|
||||
// If server exists, return it
|
||||
if (existingServer) {
|
||||
this.logger.debug('Server already registered', {
|
||||
serverId: existingServer.id,
|
||||
guildId,
|
||||
serverName: existingServer.server_name
|
||||
});
|
||||
return existingServer;
|
||||
}
|
||||
|
||||
// If server doesn't exist, create it
|
||||
this.logger.debug('Registering new server', { guildId, serverName });
|
||||
const { data: newServer, error: insertError } = await this.supabase
|
||||
.from('servers')
|
||||
.insert([{
|
||||
discord_server_id: guildId,
|
||||
server_name: serverName,
|
||||
active: true
|
||||
}])
|
||||
.select()
|
||||
.single();
|
||||
|
||||
if (insertError) {
|
||||
this.logger.error('Failed to register server', {
|
||||
error: insertError,
|
||||
guildId,
|
||||
serverName
|
||||
});
|
||||
throw insertError;
|
||||
}
|
||||
|
||||
this.logger.info('New server registered successfully', {
|
||||
serverId: newServer.id,
|
||||
guildId,
|
||||
serverName
|
||||
});
|
||||
|
||||
return newServer;
|
||||
} catch (error) {
|
||||
this.logger.error('Error in ensureServerRegistered:', {
|
||||
error: error.message,
|
||||
stack: error.stack,
|
||||
guildId,
|
||||
serverName
|
||||
});
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// Update the addSubscription method to use ensureServerRegistered
|
||||
async addSubscription(guildId, gameName, channelId, serverName) {
|
||||
if (!this.supabase) {
|
||||
this.logger.error('Client not initialized');
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
this.logger.debug('Adding subscription', { guildId, gameName, channelId });
|
||||
|
||||
// Ensure server is registered
|
||||
const server = await this.ensureServerRegistered(guildId, serverName);
|
||||
if (!server) {
|
||||
throw new Error('Failed to ensure server registration');
|
||||
}
|
||||
|
||||
// Get game ID
|
||||
const { data: gameData, error: gameError } = await this.supabase
|
||||
.from('games')
|
||||
.select('id')
|
||||
.eq('name', gameName)
|
||||
.eq('active', true)
|
||||
.single();
|
||||
|
||||
if (gameError) {
|
||||
this.logger.error('Game fetch error:', { gameError, gameName });
|
||||
throw gameError;
|
||||
}
|
||||
|
||||
// Create subscription
|
||||
const { data, error } = await this.supabase
|
||||
.from('server_game_preferences')
|
||||
.upsert({
|
||||
server_id: server.id,
|
||||
game_id: gameData.id,
|
||||
notification_channel_id: channelId
|
||||
}, {
|
||||
onConflict: '(server_id,game_id)',
|
||||
returning: true
|
||||
});
|
||||
|
||||
if (error) {
|
||||
this.logger.error('Subscription upsert error:', { error });
|
||||
throw error;
|
||||
}
|
||||
|
||||
this.logger.debug('Subscription added successfully', {
|
||||
serverId: server.id,
|
||||
gameId: gameData.id,
|
||||
channelId
|
||||
});
|
||||
|
||||
return data;
|
||||
} catch (error) {
|
||||
this.logger.error('Error in addSubscription:', {
|
||||
error: error.message,
|
||||
stack: error.stack,
|
||||
guildId,
|
||||
gameName
|
||||
});
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async getSubscriptions(guildId) {
|
||||
if (!this.supabase) {
|
||||
console.error('Supabase client is not initialized.');
|
||||
this.logger.error('Client not initialized');
|
||||
return [];
|
||||
}
|
||||
|
||||
const { data, error } = await this.supabase
|
||||
.from('server_game_preferences')
|
||||
.select(`
|
||||
games (name),
|
||||
notification_channel_id,
|
||||
servers!inner (discord_server_id)
|
||||
`)
|
||||
.eq('servers.discord_server_id', guildId);
|
||||
try {
|
||||
this.logger.debug('Fetching subscriptions', { guildId });
|
||||
|
||||
const { data, error } = await this.supabase
|
||||
.from('server_game_preferences')
|
||||
.select(`
|
||||
games (name),
|
||||
notification_channel_id,
|
||||
servers!inner (discord_server_id)
|
||||
`)
|
||||
.eq('servers.discord_server_id', guildId);
|
||||
|
||||
if (error) throw error;
|
||||
return data;
|
||||
if (error) {
|
||||
this.logger.error('Error fetching subscriptions:', { error, guildId });
|
||||
throw error;
|
||||
}
|
||||
|
||||
this.logger.debug('Subscriptions fetched', {
|
||||
count: data?.length || 0,
|
||||
guildId
|
||||
});
|
||||
|
||||
return data || [];
|
||||
} catch (error) {
|
||||
this.logger.error('Error in getSubscriptions:', {
|
||||
error: error.message,
|
||||
stack: error.stack,
|
||||
guildId
|
||||
});
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async addSubscription(guildId, gameName, channelId) {
|
||||
if (!this.supabase) {
|
||||
console.error('Supabase client is not initialized.');
|
||||
this.logger.error('Client not initialized');
|
||||
return null;
|
||||
}
|
||||
|
||||
// First, get or create server record
|
||||
const { data: serverData, error: serverError } = await this.supabase
|
||||
.from('servers')
|
||||
.upsert({
|
||||
discord_server_id: guildId
|
||||
}, {
|
||||
onConflict: 'discord_server_id',
|
||||
returning: true
|
||||
try {
|
||||
this.logger.debug('Adding subscription', { guildId, gameName, channelId });
|
||||
|
||||
// First, get or create server record
|
||||
const { data: serverData, error: serverError } = await this.supabase
|
||||
.from('servers')
|
||||
.upsert({
|
||||
discord_server_id: guildId,
|
||||
active: true
|
||||
}, {
|
||||
onConflict: 'discord_server_id',
|
||||
returning: true
|
||||
});
|
||||
|
||||
if (serverError) {
|
||||
this.logger.error('Server upsert error:', { serverError, guildId });
|
||||
throw serverError;
|
||||
}
|
||||
|
||||
if (!serverData || serverData.length === 0) {
|
||||
this.logger.error('Server creation failed - no data returned', { guildId });
|
||||
throw new Error('Server creation failed');
|
||||
}
|
||||
|
||||
// Get game ID
|
||||
const { data: gameData, error: gameError } = await this.supabase
|
||||
.from('games')
|
||||
.select('id')
|
||||
.eq('name', gameName)
|
||||
.eq('active', true)
|
||||
.single();
|
||||
|
||||
if (gameError) {
|
||||
this.logger.error('Game fetch error:', { gameError, gameName });
|
||||
throw gameError;
|
||||
}
|
||||
|
||||
// Create subscription
|
||||
const { data, error } = await this.supabase
|
||||
.from('server_game_preferences')
|
||||
.upsert({
|
||||
server_id: serverData[0].id,
|
||||
game_id: gameData.id,
|
||||
notification_channel_id: channelId
|
||||
}, {
|
||||
onConflict: '(server_id,game_id)',
|
||||
returning: true
|
||||
});
|
||||
|
||||
if (error) {
|
||||
this.logger.error('Subscription upsert error:', { error });
|
||||
throw error;
|
||||
}
|
||||
|
||||
this.logger.debug('Subscription added successfully', {
|
||||
serverId: serverData[0].id,
|
||||
gameId: gameData.id,
|
||||
channelId
|
||||
});
|
||||
|
||||
if (serverError) throw serverError;
|
||||
|
||||
// Get game ID
|
||||
const { data: gameData, error: gameError } = await this.supabase
|
||||
.from('games')
|
||||
.select('id')
|
||||
.eq('name', gameName)
|
||||
.eq('active', true)
|
||||
.single();
|
||||
|
||||
if (gameError) throw gameError;
|
||||
|
||||
// Create subscription
|
||||
const { data, error } = await this.supabase
|
||||
.from('server_game_preferences')
|
||||
.upsert({
|
||||
server_id: serverData[0].id,
|
||||
game_id: gameData.id,
|
||||
notification_channel_id: channelId
|
||||
}, {
|
||||
onConflict: '(server_id,game_id)',
|
||||
returning: true
|
||||
return data;
|
||||
} catch (error) {
|
||||
this.logger.error('Error in addSubscription:', {
|
||||
error: error.message,
|
||||
stack: error.stack,
|
||||
guildId,
|
||||
gameName
|
||||
});
|
||||
|
||||
if (error) throw error;
|
||||
return data;
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async removeSubscription(guildId, gameName) {
|
||||
if (!this.supabase) {
|
||||
console.error('Supabase client is not initialized.');
|
||||
this.logger.error('Client not initialized');
|
||||
return null;
|
||||
}
|
||||
|
||||
// Get server ID
|
||||
const { data: serverData, error: serverError } = await this.supabase
|
||||
.from('servers')
|
||||
.select('id')
|
||||
.eq('discord_server_id', guildId)
|
||||
.single();
|
||||
try {
|
||||
this.logger.debug('Removing subscription', { guildId, gameName });
|
||||
|
||||
if (serverError) throw serverError;
|
||||
// Get server ID
|
||||
const { data: serverData, error: serverError } = await this.supabase
|
||||
.from('servers')
|
||||
.select('id')
|
||||
.eq('discord_server_id', guildId)
|
||||
.single();
|
||||
|
||||
// Get game ID
|
||||
const { data: gameData, error: gameError } = await this.supabase
|
||||
.from('games')
|
||||
.select('id')
|
||||
.eq('name', gameName)
|
||||
.single();
|
||||
if (serverError) {
|
||||
this.logger.error('Server fetch error:', { serverError, guildId });
|
||||
throw serverError;
|
||||
}
|
||||
|
||||
if (gameError) throw gameError;
|
||||
// Get game ID
|
||||
const { data: gameData, error: gameError } = await this.supabase
|
||||
.from('games')
|
||||
.select('id')
|
||||
.eq('name', gameName)
|
||||
.single();
|
||||
|
||||
// Delete subscription
|
||||
const { data, error } = await this.supabase
|
||||
.from('server_game_preferences')
|
||||
.delete()
|
||||
.match({
|
||||
server_id: serverData.id,
|
||||
game_id: gameData.id
|
||||
})
|
||||
.single();
|
||||
if (gameError) {
|
||||
this.logger.error('Game fetch error:', { gameError, gameName });
|
||||
throw gameError;
|
||||
}
|
||||
|
||||
if (error) throw error;
|
||||
return data;
|
||||
// Delete subscription
|
||||
const { data, error } = await this.supabase
|
||||
.from('server_game_preferences')
|
||||
.delete()
|
||||
.match({
|
||||
server_id: serverData.id,
|
||||
game_id: gameData.id
|
||||
})
|
||||
.single();
|
||||
|
||||
if (error) {
|
||||
this.logger.error('Subscription deletion error:', { error });
|
||||
throw error;
|
||||
}
|
||||
|
||||
this.logger.debug('Subscription removed successfully', {
|
||||
serverId: serverData.id,
|
||||
gameId: gameData.id
|
||||
});
|
||||
|
||||
return data;
|
||||
} catch (error) {
|
||||
this.logger.error('Error in removeSubscription:', {
|
||||
error: error.message,
|
||||
stack: error.stack,
|
||||
guildId,
|
||||
gameName
|
||||
});
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
getClient() {
|
||||
|
||||
Reference in New Issue
Block a user