-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
379 lines (321 loc) · 10.8 KB
/
index.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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
const dotenv = require('dotenv');
const fs = require('fs');
const { Client, Collection, GatewayIntentBits, Partials, EmbedBuilder, InteractionType, ChannelType, CommandInteractionOptionResolver, GuildMember } = require('discord.js');
const sqlite3 = require("sqlite3");
const { guildService } = require("./src/services/guild");
const { sqlLite3DatabaseService } = require("./src/database/sqlite");
const { getActiveCharacterIndex, getXp, getRoleMultiplier, getLevelInfo, getTier, logCommand, logError } = require("./src/utils");
const { Some_BioAndroid_COLOR, Some_BioAndroid_ICON_URL, CLIENT_ID } = require("./src/config.json")
/*
-----------------------
LOADING ENV VARS (.env)
-----------------------
*/
dotenv.config();
/*
---------------------------
LOADING DISCORD PERMISSIONS
---------------------------
*/
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
GatewayIntentBits.DirectMessages],
partials: [Partials.Channel]
});
client.commands = new Collection();
/*
----------------
LOADING COMMANDS
----------------
*/
const commandsPath = [
"everyone",
"mod",
"owner",
];
for (const path of commandsPath) {
const commandCollection = fs.readdirSync(`./src/commands/${path}`).filter(file => file.endsWith('.js'));
for (const file of commandCollection) {
const command = require(`./src/commands/${path}/${file}`);
client.commands.set(command.data.name, command);
}
}
/*
------------
BOT COMMANDS
------------
*/
client.once('ready', () => {
//clearGuildCache();
console.log("ready");
});
const POSSIBILITIES = [
".set1",
".set2",
".set3",
".set4",
".set5",
".set6",
".set7",
".set8",
".set9",
".set10",
];
function parsing(message) {
// Remove spaces and convert to lowercase
// console.log(message)
const x = message.content.replace(/\s+/g, '').toLowerCase();
// Check if x is not an empty string and is included in POSSIBILITIES
if (x !== '' && POSSIBILITIES.includes(x)) {
const index = POSSIBILITIES.indexOf(x);
console.log("Here at index:", index);
executeInteraction(index, message);
}
}
async function executeInteraction(index, message) {
try {
const gService = new guildService(
await new sqlLite3DatabaseService(sqlite3, `./guilds/${message.guildId}.db`)
);
await gService.init();
if (!await gService.isRegistered() && command.data.name != "register") {
try {
await message.reply({
content: `Sorry, but your server is not registered, please contact <@${message.guild.ownerId}> and ask them to do \`/register\`.`,
ephemeral: true
});
} catch (error) {
console.error('Failed to send registration reply:', error);
}
return;
}
// Simulated interaction object
let interaction = {
type: 'APPLICATION_COMMAND',
commandName: 'set',
client,
message: message,
member: await message.guild.members.fetch(message.author.id),
user: message.author,
guildId: message.guildId,
applicationId: CLIENT_ID,
channelId: message.channelId,
guild: message.guild,
options: new CommandInteractionOptionResolver(client, [
{
name: 'character',
type: 4, // INTEGER option type
value: index + 1, // Convert index to 1-based indexing
},
]),
reply: async (content) => {
try {
const sentMessage = await message.reply(content);
return sentMessage;
} catch (error) {
console.error('Failed to send reply:', error);
}
},
// editReply: async (newContent) => {
// try {
// const messages = await message.channel.messages.fetch({ limit: 100 }); // Fetch a larger number of messages
// const botMessage = messages.find(msg => msg.author.id === client.user.id && msg.reference?.messageId === message.id);
// if (botMessage) {
// await botMessage.edit(newContent);
// } else {
// console.warn('Bot message not found for editing.');
// // If the bot's message is not found, try to send a new message
// await interaction.reply(newContent);
// }
// } catch (error) {
// console.error('Failed to edit reply:', error);
// }
// }
};
const command = client.commands.get(interaction.commandName);
await command.execute(gService, interaction);
} catch (error) {
console.error('Error executing interaction:', error);
}
}
client.on('interactionCreate', async interaction => {
/*
-------------------------------------
VALIDATIONS FOR INTERACTION EXECUTION
-------------------------------------
*/
if (!interaction.isCommand() ||
!interaction.inGuild()) return;
const command = client.commands.get(interaction.commandName);
if (!command) return;
const guildId = `${interaction.guildId}`;
// LOADING GUILD SERVICE
const gService = new guildService(
await new sqlLite3DatabaseService(sqlite3, `./guilds/${guildId}.db`)
)
await gService.init();
if (!await gService.isRegistered() && command.data.name != "register") {
// Try Catch on the reply, because this is a restful call, and errors can be found
try {
await interaction.editReply({
content: `Sorry, but your server is not registered, please contact <@${interaction.guild.ownerId}> and ask them todo \`/register\`.`,
ephemeral: true
});
} catch (error) { };
return;
}
/*
-----------------
EXECUTING COMMAND
-----------------
*/
try {
logCommand(interaction);
} catch (error) {
console.log(error);
}
try {
let is_public = !interaction.options.getBoolean("public");
await interaction.deferReply({ ephemeral: is_public });
await command.execute(gService, interaction);
} catch (error) {
try {
logError(interaction, error);
} catch (error) {
console.log(error);
}
console.log(error);
}
});
/*
-----------
XP PER POST
-----------
*/
client.on('messageCreate', async message => {
try {
parsing(message);
let IS_COMBAT = false;
/*
----------
VALIDATION
----------
*/
if (message.content[0] == '>' && message.content[1] != ' '){
console.log(message.channelId)
}
if (message.content[0] == '>' && message.content[1] != ' ' && message.channelId == 1242965566495522856) {
return message.channel.send({ content: "AWAKEN MY MASTER" })
}
if (!message.inGuild()) { return; }
if (message.author.bot) { return; }
if ((message.content.split(/\s+/).length <= 10) && !message.content.startsWith('!')) { return; }
if ((message.content.length < 2) && message.content.startsWith('!')) { return; } // if has ! at start, length needs to be bigger than 2
if (message.content.startsWith('!')) { IS_COMBAT = true }
// if (!message.content.startsWith('!')) { IS_COMBAT = false }
/*
--------------------------------
LOADING GUILD INTO CACHED GUILDS
--------------------------------
*/
const guildId = `${message.guildId}`;
if (!fs.existsSync(`./guilds/${guildId}.db`)) {
return;
}
const gService = new guildService(
await new sqlLite3DatabaseService(sqlite3, `./guilds/${guildId}.db`)
)
await gService.init();
if (!await gService.isRegistered()) { return; }
/*
--------------
INITIALIZE
--------------
*/
const messageCount = message.content.split(/\s+/).length;
const guild = await client.guilds.fetch(guildId);
const player = await guild.members.fetch(message.author.id);
const roleBonus = getRoleMultiplier(gService.config["roleBonus"], gService.roles, player._roles);
const characterIndex = getActiveCharacterIndex(gService.config, player._roles);
const character = await gService.getCharacter(`${player.id}-${characterIndex}`)
if (!character) { return; }
// --------------------------
//#region Channel check
// --------------------------
let channel = await guild.channels.fetch(message.channelId);
while (channel) {
if (channel.id in gService.channels) { break; }
channel = await guild.channels.fetch(channel.parentId);
}
if (!channel) { return; }
if (gService.channels[channel.id] == 0) { return; }
//#end region Channel check
// --------------------------
//#region EXP / XP Calculations
// --------------------------
// Code to execute if the author's global name includes the ice cube character
if (message.member.nickname != '' && message.member.nickname.includes('\u{1F9CA}')) {
// Code to execute if the author's global name includes the ice cube character
return
}
const xp = getXp(messageCount, roleBonus, gService.channels[channel.id], gService.config["xpPerPostDivisor"], gService.config["xpPerPostFormula"], IS_COMBAT);
//#end region EXP / XP Calculations
if (player._roles.includes(gService.config["xpShareRoleId"])) {
const playerCharacters = await gService.getAllCharacters(player.id);
for (let subCharacter of playerCharacters) {
await updateCharacterXpAndMessage(guild, gService, subCharacter, xp / playerCharacters.length, player)
}
} else {
await updateCharacterXpAndMessage(guild, gService, character, xp, player)
}
} catch (error) { console.log(error); }
});
async function updateCharacterXpAndMessage(guild, gService, character, xp, player) {
try {
await gService.updateCharacterXP(character, xp);
const oldLevelInfo = getLevelInfo(gService.levels, character["xp"]);
const newLevelInfo = getLevelInfo(gService.levels, character["xp"] + xp);
if (oldLevelInfo["level"] != newLevelInfo["level"]) {
const newTier = getTier(newLevelInfo["level"]);
const tierRoles = []
for (let tierIndex = 1; tierIndex <= 4; tierIndex++) {
if (tierIndex == newTier["tier"]) { continue; }
tierRoles.push(await guild.roles.fetch(gService.config[`tier${tierIndex}RoleId`]));
}
const newTierRole = await guild.roles.fetch(gService.config[`tier${newTier["tier"]}RoleId`]);
try {
const updatedPlayer = await player.roles.remove(tierRoles);
await updatedPlayer.roles.add(newTierRole);
} catch (error) {
console.log(error);
}
let awardChannel;
try {
awardChannel = await guild.channels.fetch(gService.config["levelUpChannelId"]);
} catch (error) { return; }
let levelUpEmbed = new EmbedBuilder()
.setTitle(`${character["name"]} Leveled Up`)
.setFields(
{ name: "Level Up!", value: `${oldLevelInfo["level"]} --> **${newLevelInfo["level"]}**`, inline: true },
{ name: "Total Character XP", value: `${Math.floor(character["xp"] + xp)}`, inline: true },
{ name: "Tier", value: `<@&${gService.config[`tier${newTier["tier"]}RoleId`]}>`, inline: true }
)
.setThumbnail((character["picture_url"] != "" && character["picture_url"] !== "null") ? character["picture_url"] : Some_BioAndroid_ICON_URL)
.setColor(Some_BioAndroid_COLOR)
.setFooter({ text: "You can view your characters with /xp" })
if (character["sheet_url"] != "") {
levelUpEmbed.setURL(character["sheet_url"]);
}
awardChannel.send({ content: `${player}`, embeds: [levelUpEmbed] });
}
} catch (error) { console.log(error) }
}
/*
---------------------
LOGGING THE BOT ONLINE
---------------------
*/
client.login(process.env.DISCORD_TOKEN);