File size: 5,066 Bytes
0e6ca52
b49cf8b
0e6ca52
 
b49cf8b
0e6ca52
 
 
 
 
609e85d
 
b49cf8b
 
609e85d
 
b49cf8b
609e85d
0e6ca52
 
 
 
 
 
 
 
 
 
 
 
 
ebb41e4
 
 
 
 
 
 
93fafed
0e6ca52
 
 
 
 
93fafed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b49cf8b
0e6ca52
b49cf8b
 
 
 
0e6ca52
 
b49cf8b
0e6ca52
 
 
b49cf8b
 
0e6ca52
 
b49cf8b
0e6ca52
b49cf8b
 
 
 
 
0e6ca52
b49cf8b
0e6ca52
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93fafed
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
"use strict";
const { Client, GatewayIntentBits, MessageFlags } = require("discord.js");
const db = require("./db");

// Default configuration is robust enough for most networks
const client = new Client({
  intents: [
    GatewayIntentBits.Guilds,
    GatewayIntentBits.GuildMessages,
    GatewayIntentBits.MessageContent
  ],
  rest: {
    timeout: 15000, // 15s timeout
    retries: 5,     // Retry up to 5 times
  },
  ws: {
    large_threshold: 50, // Reduce initial load for faster startup
  }
});

client.once("ready", () => {
  console.log(`[BOT] Logged in as ${client.user.tag}`);
  console.log(`[BOT] Serving ${client.guilds.cache.size} guilds`);
});

client.on("messageCreate", (message) => {
  if (message.author.bot) return;

  const content = message.content.trim();
  const prefix = "!";

  // Track command usage (only if functions exist)
  try {
    if (db.trackServerActivity) db.trackServerActivity(message.guildId, message.guild?.name || "Unknown", message.guild?.memberCount || 0);
    if (db.trackCommandUsage) db.trackCommandUsage(message.guildId, message.author.id, message.author.tag, content.split(" ")[0]);
  } catch (e) {
    console.error("[ERROR] Tracking failed:", e.message);
  }

  if (content === `${prefix}ping`) {
    message.reply(`Pong! Latency: ${client.ws.ping}ms`);
    return;
  }

  // !servers-info
  if (content === `${prefix}servers-info`) {
    const allServers = db.getServerStats();
    const globalStats = db.getGlobalStats();
    
    if (!allServers || allServers.length === 0) {
      message.reply("No server data available yet.");
      return;
    }

    let embed = `\`\`\`
📊 SERVERS INFO - GLOBAL STATS
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Total Servers: ${client.guilds.cache.size}
Total Commands Used: ${globalStats?.total_commands || 0}
Active Users: ${globalStats?.total_users || 0}
\`\`\`\n`;

    embed += `\n**📍 Server Activity (Top 10):**\n`;
    
    allServers.slice(0, 10).forEach((server, index) => {
      embed += `\n**${index + 1}. ${server.guild_name}** (ID: ${server.guild_id})\n`;
      embed += `   • Members: ${server.member_count || 'N/A'}\n`;
      embed += `   • Commands: ${server.commands_used}\n`;
      embed += `   • Last Activity: <t:${Math.floor(new Date(server.last_activity).getTime() / 1000)}:R>\n`;

      // Get top 5 command users for this server
      const topUsers = db.getTopCommandUsers(server.guild_id, 5);
      if (topUsers && topUsers.length > 0) {
        embed += `   • Top Users:\n`;
        topUsers.forEach((user, idx) => {
          embed += `      ${idx + 1}. ${user.user_tag} (${user.count} commands)\n`;
        });
      }
    });

    embed += `\n\n**📋 All Connected Servers:**\n`;
    const allConnectedServers = client.guilds.cache.map(guild => `• ${guild.name} (${guild.memberCount} members)`).join("\n");
    
    if (allConnectedServers.length > 2000) {
      embed += allConnectedServers.substring(0, 2000) + "...\n*(List truncated - too many servers)*";
    } else {
      embed += allConnectedServers;
    }

    if (embed.length > 2000) {
      message.reply(embed.substring(0, 1990) + "...");
    } else {
      message.reply(embed);
    }
    return;
  }

  // !roster-add @User Role [in Team Name]
  if (content.startsWith(`${prefix}roster-add`)) {
    const fullText = content.slice(`${prefix}roster-add`.length).trim();
    
    // Match: <@123456789> Role Name in Team Name
    // Or: <@123456789> Role Name
    const user = message.mentions.users.first();
    if (!user) {
      message.reply("Usage: `!roster-add @User Role [in Team Name]`");
      return;
    }

    // Remove the mention from the string to parse the rest
    const rest = fullText.replace(/<@\d+>\s?/, "").trim();
    
    let role = "Member";
    let teamName = "General";

    // Check for " in " to split role and team
    const inIndex = rest.lastIndexOf(" in ");
    if (inIndex > -1) {
      role = rest.substring(0, inIndex).trim() || "Member";
      teamName = rest.substring(inIndex + 4).trim() || "General";
    } else {
      role = rest || "Member";
    }

    const userTag = user.tag;
    db.addRoster(teamName, userTag, role);
    message.reply(`✅ Added **${userTag}** as **${role}** to **${teamName}**.`);
  }
});

client.on("interactionCreate", async (interaction) => {
  if (!interaction.isChatInputCommand()) return;

  if (interaction.commandName === "ping") {
    await interaction.reply({ content: `Latency: ${client.ws.ping}ms`, flags: MessageFlags.Ephemeral });
  }

  if (interaction.commandName === "roster-add") {
    const team = interaction.options.getString("team") || "General";
    const user = interaction.options.getUser("user");
    const role = interaction.options.getString("role") || "Member";
    const userTag = user ? user.tag : "Unknown";

    db.addRoster(team, userTag, role);
    await interaction.reply({ content: `✅ Added **${userTag}** as **${role}** to **${team}**.`, flags: MessageFlags.Ephemeral });
  }
});

module.exports = { client };