-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathbot.js
318 lines (267 loc) · 10.1 KB
/
bot.js
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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
const Discord = require("discord.js");
const conf = require("./conf/conf");
const ModuleHandler = require("./src/Modules/ModuleHandler");
const Topgg = require("@top-gg/sdk");
const DiscordServers = require("./src/Database/DiscordServers");
const Globals = require("./src/Globals");
const conn = require("./conf/mysql");
const Axios = require("axios").default;
const Utils = require("./src/Utils");
const Translator = require("./src/Translator/Translator");
const InteractContainer = require("./src/Discord/InteractContainer");
var bot = new Discord.Client({
intents: [
Discord.Intents.FLAGS.DIRECT_MESSAGES,
Discord.Intents.FLAGS.DIRECT_MESSAGE_REACTIONS,
Discord.Intents.FLAGS.DIRECT_MESSAGE_REACTIONS,
Discord.Intents.FLAGS.GUILDS,
Discord.Intents.FLAGS.GUILD_EMOJIS_AND_STICKERS,
Discord.Intents.FLAGS.GUILD_INTEGRATIONS,
Discord.Intents.FLAGS.GUILD_MESSAGES,
Discord.Intents.FLAGS.GUILD_MESSAGE_REACTIONS,
],
partials: ['MESSAGE', 'CHANNEL', 'REACTION'],
makeCache: Discord.Options.cacheWithLimits(),
});
process.on('unhandledRejection', err => {
let errorDate = new Date();
console.log(errorDate.toUTCString());
console.log(err);
});
console.log("Shard Starting ...");
let timeStart = Date.now();
async function startBot() {
try {
console.time("Load Translator");
await Translator.loadTranslator();
console.timeEnd("Load Translator");
console.time("Load Help Panel");
await Globals.loadHelpPanel();
console.timeEnd("Load Help Panel");
console.time("Load Appearances");
await Globals.loadAllAppearances();
console.timeEnd("Load Appearances");
Globals.moduleHandler = new ModuleHandler();
console.time("Bot login");
await bot.login(conf.discordbotkey);
console.timeEnd("Bot login");
setTimeoutToRemoveInactiveUsers();
Globals.isLoading = false;
} catch (error) {
let errorDate = new Date();
console.log("Error when connecting Shard. Restarting shard in 30 seconds...");
console.log(errorDate.toUTCString());
console.log(error);
//setTimeout(startBot, 30000);
}
}
async function removedInactiveUsers() {
let now = Date.now();
let inactiveUsers = 0;
for (let idUser in Globals.connectedUsers) {
let user = Globals.connectedUsers[idUser];
let diff = now - user.lastCommandUsed;
// 30 minutes inactive before removing some data from globals
if (diff / 60000 > Globals.inactiveTimeBeforeDisconnect) {
delete Globals.connectedUsers[user.id];
inactiveUsers++;
}
}
try {
console.log(`Removed: ${inactiveUsers} inactive users. Memory consumption: ${await getMemory()} MB`);
} catch (ex) { console.error(ex); }
//createDummyUsers();
setTimeoutToRemoveInactiveUsers();
}
function setTimeoutToRemoveInactiveUsers() {
setTimeout(removedInactiveUsers, Globals.inactiveTimeBeforeDisconnect * 60000);
}
async function createDummyUsers() {
let nbUsersToCreate = Math.round(Math.random() * 10000);
console.log(`Creating ${nbUsersToCreate} fake users...\nMemory before: ${await getMemory()} MB`);
let totalRequests = [];
const User = require("./src/Users/User");
const t = Date.now();
for (let i = 0; i < nbUsersToCreate; i++) {
let zerofilled = ('0000000' + Math.floor(Math.random() * 10000000)).slice(-7);
let u = new User(zerofilled, "Test User#1111", "");
u.token = ""; //When testing use your token don't forget to remove it
u.initAxios();
totalRequests.push(u.getAxios().get("/game/character/info"));
Globals.connectedUsers[zerofilled] = u;
}
console.log(`Memory after creation: ${await getMemory()} MB`);
console.time("Requesting");
await Promise.all(totalRequests);
console.log(`Avg time per requests: ${Math.round((Date.now() - t) / totalRequests.length)}ms; Number of requests per minute: ${1000 / Math.round((Date.now() - t) / totalRequests.length)}`);
console.log(`Memory after requests: ${await getMemory()} MB`);
console.timeEnd("Requesting");
}
async function getMemory() {
let totalMemory = await bot.shard.broadcastEval(() => process.memoryUsage().heapUsed);
let totalMemoryMB = 0;
for (let c of totalMemory) {
totalMemoryMB += Math.round(c / 1048576);
}
return totalMemoryMB;
}
/**
*
* @param {InteractContainer} interact
*/
async function tryHandleMessage(interact) {
try {
await Globals.moduleHandler.run(interact);
} catch (err) {
let msgError = "";
if (err.constructor == Discord.DiscordAPIError) {
msgError = "It seems to have an api error, you should check if the bot have all permissions it needs\n";
} else {
msgError = "Oops something went wrong, report the issue here (https://github.com/FightRPG-DiscordBotRPG/FightRPG-Discord-BugTracker/issues)\n";
}
msgError = Utils.prepareStackError(err, msgError);
interact.channel.send(msgError).catch((e) => interact.author.send(msgError).catch((e) => null));
}
}
/**
*
* @param {import("discord.js").CommandInteractionOption[]} interactions
* @param {InteractContainer} interact
*/
async function recursiveUpdateData(interactions, interact) {
for (let i of interactions) {
if (i.value !== undefined) {
const val = i.value.toString();
if (val.startsWith("<@")) {
const id = val.slice(2, val.length - 1);
interact.mentions.set(id, await bot.users.fetch(id))
} else {
interact.args.push(i.value);
}
} else {
if (i.type.toString().includes("SUB_COMMAND")) {
interact.command += i.name;
}
if (i.options) {
await recursiveUpdateData(i.options, interact);
}
}
}
}
bot.on("ready", async () => {
console.log("Shard Connected");
bot.user.setPresence({
activities: [{
name: "On " + await Utils.getTotalNumberOfGuilds(bot.shard) + " servers!"
}]
});
//const cmds = await bot.application?.commands.set([
// {
// name: "test",
// description: "test",
// options: [{
// name: "input",
// type: "",
// description: "ça sert à rien",
// require: true
// }],
// }
//]);
//console.log(`${bot.guilds.cache.size}\n${bot.shard.ids}\n${bot.shard.count}`);
if (conf.env === "prod") {
const api = new Topgg.Api(conf.topggkey);
setInterval(async () => {
console.log("Shards: " + bot.shard.ids);
console.log("Shard: " + bot.shard.ids[0] + " => Sending stats to https://top.gg/ ...");
await api.postStats({ serverCount: bot.guilds.cache.size, shardId: bot.shard.ids[0], shardCount: bot.shard.count });
console.log("Data sent");
}, 1800000);
}
DiscordServers.serversStats(bot.guilds);
console.log("Shard Loaded");
});
// Key Don't open
startBot();
bot.on("interactionCreate",
/**
*
* @param {Discord.Interaction} interaction
*/
async function handleInteract(interaction) {
const interact = new InteractContainer();
interact.author = interaction.user;
interact.channel = interaction.channel;
interact.interaction = interaction;
interact.guild = interaction.guild;
interact.command = interaction.commandName;
interact.client = bot;
let shouldHandleHere = false;
if (interaction.isCommand() || interaction.isAutocomplete()) {
await recursiveUpdateData(interaction.options.data, interact, bot);
shouldHandleHere = true;
} else if (interaction.isContextMenu()) {
interact.mentions.set(interaction.targetId, await bot.users.fetch(interaction.targetId), bot);
shouldHandleHere = true;
}
if (shouldHandleHere) {
await tryHandleMessage(interact);
}
});
bot.on("messageCreate", async (message) => {
const interact = new InteractContainer();
interact.author = message.author;
interact.channel = message.channel;
interact.message = message;
interact.guild = message.guild;
interact.client = bot;
interact.mentions = message.mentions.users;
await tryHandleMessage(interact);
});
bot.on('guildCreate', async (guild) => {
bot.user.setPresence({
activity: {
name: "On " + await Utils.getTotalNumberOfGuilds(bot.shard) + " servers!",
},
});
DiscordServers.newGuild(guild);
});
bot.on('guildDelete', async (guild) => {
bot.user.setPresence({
activity: {
name: "On " + await Utils.getTotalNumberOfGuilds(bot.shard) + " servers!",
},
});
});
bot.on("userUpdate", async (oldUser, newUser) => {
if (oldUser.tag != newUser.tag) {
let axios;
if (Globals.connectedUsers[newUser.id]) {
axios = Globals.connectedUsers[newUser.id].getAxios();
Globals.connectedUsers[newUser.id].avatar = newUser.avatar;
Globals.connectedUsers[newUser.id].username = newUser.username;
} else {
let res = await conn.query("SELECT token FROM users WHERE idUser = ?;", [newUser.id]);
if (res[0]) {
axios = Axios.create({
headers: {
'Authorization': "Bearer " + res[0].token
}
})
}
}
if (axios != null) {
let data = await axios.post("/game/character/update", {
username: newUser.tag,
avatar: oldUser.avatar != newUser.avatar ? newUser.avatar : null,
});
if (data.data.error != null) {
console.log("Axios Existing.. hd5d6589d");
console.log(data.data);
}
} else {
// console.log("Axios not existing.. c89d6f5c2");
// console.log(oldUser.tag + " vs " + newUser.tag);
// console.log(axios);
}
}
});