-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
259 lines (221 loc) · 8.33 KB
/
index.js
File metadata and controls
259 lines (221 loc) · 8.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
require('dotenv').config();
const { Client, GatewayIntentBits, Collection, EmbedBuilder, MessageFlags, ActivityType } = require('discord.js');
const fs = require('fs');
const path = require('path');
const config = require('./config');
const matchTracker = require('./services/matchTracker');
const { deleteGuildConfig } = require('./utils/guildConfigManager');
const { removeGuildFromAllUsers } = require('./utils/userLinksManager');
const { removeCommandsFromGuild } = require('./utils/commandDeployer');
const { deployGlobalCommands } = require('./utils/globalCommandDeployer');
const {
trackGuild,
markCommandsDeployed,
markOnboardingComplete,
untrackGuild,
detectNewGuilds,
getGuildsNeedingOnboarding,
} = require('./utils/guildTracker');
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
],
});
// Initialize slash commands collection
client.slashCommands = new Collection();
// Load slash commands from slashCommands directory
const slashCommandsPath = path.join(__dirname, 'slashCommands');
const slashCommandFiles = fs.readdirSync(slashCommandsPath).filter(file => file.endsWith('.js'));
for (const file of slashCommandFiles) {
const filePath = path.join(slashCommandsPath, file);
const command = require(filePath);
if ('data' in command && 'execute' in command) {
client.slashCommands.set(command.data.name, command);
console.log(`[COMMAND] Loaded slash command: ${command.data.name}`);
} else {
console.log(`[WARNING] The command at ${filePath} is missing required "data" or "execute" property.`);
}
}
/**
* Send onboarding/welcome message to a guild
* @param {Guild} guild - Discord guild object
*/
async function sendOnboardingMessage(guild) {
try {
// Find a suitable channel to send welcome message
const channels = await guild.channels.fetch();
const textChannel = channels.find(
channel => channel.isTextBased() &&
channel.permissionsFor(guild.members.me).has('SendMessages'),
);
if (!textChannel) {
console.log(`[ONBOARDING] No suitable channel found in ${guild.name} to send welcome message`);
return false;
}
// Send welcome embed
const embed = new EmbedBuilder()
.setColor('#0099ff')
.setTitle('Thanks for adding CS2 Roaster Bot!')
.setDescription('I automatically roast CS2 players based on their match statistics.')
.addFields(
{
name: 'Step 1: Setup',
value: 'An admin needs to run `/setup channel` to set the channel where roasts will be posted.\n' +
'Example: `/setup channel #roasts`',
},
{
name: 'Step 2: Link Accounts',
value: 'Users can link their Steam accounts using `/link`\n' +
'Find your Steam64 ID at: https://steamid.io/',
},
{
name: 'Step 3: Get Roasted!',
value: 'After linking, when you finish a CS2 match, your stats will be automatically analyzed and roasted in the configured channel!',
},
{
name: 'Other Commands',
value: '`/stats [@user]` - View stored stats\n' +
'`/tracker status` - View tracker status\n' +
'`/setup status` - View current setup',
},
);
await textChannel.send({ embeds: [embed] });
console.log(`[ONBOARDING] Sent welcome message to ${textChannel.name} in ${guild.name}`);
// Mark onboarding as complete
markOnboardingComplete(guild.id);
return true;
} catch (error) {
console.error(`[ONBOARDING ERROR] Failed to send welcome message to ${guild.name}:`, error);
return false;
}
}
/**
* Process guilds that need onboarding
* @param {Client} client - Discord client instance
*/
async function processOnboarding(client) {
const guildsNeedingOnboarding = getGuildsNeedingOnboarding();
if (guildsNeedingOnboarding.length === 0) {
return;
}
console.log(`[ONBOARDING] Processing ${guildsNeedingOnboarding.length} guild(s) needing onboarding...`);
for (const guildId of guildsNeedingOnboarding) {
try {
const guild = await client.guilds.fetch(guildId);
await sendOnboardingMessage(guild);
} catch (error) {
console.error(`[ONBOARDING ERROR] Failed to process onboarding for guild ${guildId}:`, error);
}
}
}
client.once('clientReady', async () => {
console.log(`Logged in as ${client.user.tag}`);
console.log('Bot is ready to roast some CS2 players!');
client.user.setActivity('CS2 players', { type: ActivityType.Watching });
// Deploy commands globally with user install support
console.log('[STARTUP] Deploying global commands...');
const success = await deployGlobalCommands();
if (success) {
console.log('[STARTUP] Global commands deployed successfully');
} else {
console.error('[STARTUP] Failed to deploy global commands');
}
// Detect new guilds that joined while bot was offline
console.log('[STARTUP] Checking for new guilds joined while offline...');
const newGuilds = await detectNewGuilds(client);
if (newGuilds.length > 0) {
console.log(`[STARTUP] Detected ${newGuilds.length} new guild(s) joined while offline:`);
for (const guild of newGuilds) {
console.log(` - ${guild.name} (${guild.id})`);
}
// Note: Commands are now deployed globally, so no per-guild deployment needed
// Just mark them as detected for tracking purposes
for (const guild of newGuilds) {
markCommandsDeployed(guild.id);
}
} else {
console.log('[STARTUP] No new guilds detected.');
}
// Process any guilds that need onboarding
await processOnboarding(client);
// Initialize and start automatic match tracking
matchTracker.initialize(client);
});
// Handle slash command interactions
client.on('interactionCreate', async (interaction) => {
if (!interaction.isChatInputCommand()) {
return;
}
const command = client.slashCommands.get(interaction.commandName);
if (!command) {
console.error(`[ERROR] No command matching ${interaction.commandName} was found.`);
return;
}
try {
await command.execute(interaction);
} catch (error) {
console.error(`[ERROR] Error executing command ${interaction.commandName}:`, error);
const errorMessage = {
content: 'There was an error executing that command. Maybe I roasted myself too hard?',
flags: [MessageFlags.Ephemeral],
};
if (interaction.replied || interaction.deferred) {
await interaction.followUp(errorMessage);
} else {
await interaction.reply(errorMessage);
}
}
});
// Handle bot joining a new guild
client.on('guildCreate', async (guild) => {
console.log(`[GUILD JOIN] Joined new guild: ${guild.name} (${guild.id})`);
// Track the guild
trackGuild(guild.id, guild.name, true);
// Note: Commands are deployed globally, no per-guild deployment needed
markCommandsDeployed(guild.id);
console.log('[GUILD JOIN] Guild tracked. Commands are available globally.');
// Send onboarding message
await sendOnboardingMessage(guild);
});
// Handle bot being removed from a guild
client.on('guildDelete', async (guild) => {
console.log(`[GUILD LEAVE] Removed from guild: ${guild.name} (${guild.id})`);
try {
// Remove slash commands from the guild (cleanup)
await removeCommandsFromGuild(guild.id);
// Delete guild configuration
deleteGuildConfig(guild.id);
console.log(`[GUILD LEAVE] Deleted configuration for guild ${guild.id}`);
// Remove guild from all user links
removeGuildFromAllUsers(guild.id);
console.log(`[GUILD LEAVE] Removed guild ${guild.id} from all user links`);
// Untrack the guild
untrackGuild(guild.id);
console.log(`[GUILD LEAVE] Untracked guild ${guild.id}`);
} catch (error) {
console.error(`[GUILD LEAVE ERROR] Error cleaning up data for guild ${guild.id}:`, error);
}
});
client.on('error', (error) => {
console.error('Discord client error:', error);
});
// Graceful shutdown
process.on('SIGINT', () => {
console.log('\nShutting down gracefully...');
matchTracker.stopTracking();
client.destroy();
process.exit(0);
});
process.on('SIGTERM', () => {
console.log('\nShutting down gracefully...');
matchTracker.stopTracking();
client.destroy();
process.exit(0);
});
// Login to Discord
client.login(config.token).catch((error) => {
console.error('Failed to login to Discord:', error);
process.exit(1);
});