-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathchatot.js
467 lines (446 loc) · 16.9 KB
/
chatot.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
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
const {
Client,
GatewayIntentBits,
Partials,
Collection,
Permissions,
ActionRowBuilder,
SelectMenuBuilder,
MessageButton,
EmbedBuilder,
ButtonBuilder,
ButtonStyle,
InteractionType,
ChannelType,
} = require('discord.js');
const client = new Client({
intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildEmojisAndStickers, GatewayIntentBits.GuildMembers, GatewayIntentBits.GuildMessageReactions, GatewayIntentBits.GuildMessages, GatewayIntentBits.MessageContent, GatewayIntentBits.GuildScheduledEvents, GatewayIntentBits.DirectMessages],
partials: [Partials.Message, Partials.Channel, Partials.Reaction],
});
const fs = require('fs');
const request = require('request');
const superagent = require('superagent');
var config = require('./config.json');
const SlashRegistry = require('./functions/slashRegistry.js');
const Area = require('./functions/area.js');
const Profile = require('./functions/profile.js');
const Track = require('./functions/track.js');
const Raid = require('./functions/raid.js');
const Incident = require('./functions/incident.js');
const Quest = require('./functions/quest.js');
const Lure = require('./functions/lure.js');
const Remove = require('./functions/remove.js');
var util = require('./util.json');
var pokemonList = [];
var templateList = {};
var incidentList = {};
var questList = {};
var master = "";
client.on('ready', async () => {
console.log("Chatot Logged In");
//Update masterfile
request("https://raw.githubusercontent.com/WatWowMap/Masterfile-Generator/master/master-latest-react-map.json", {
json: true
}, (error, res, body) => {
if (error) {
return console.log(error)
};
if (!error && res.statusCode == 200) {
master = body;
//Update lists
createPokemonList();
createTemplateList();
createIncidentList();
createQuestList();
updateConfigRegisterCommands(client, config);
}
});
}); //End of ready()
//Buttons
client.on('interactionCreate', async interaction => {
if (interaction.type !== InteractionType.MessageComponent) {
return;
}
//Verify interaction
if (!interaction.customId.startsWith('chatot~')) {
return;
}
let user = interaction.member;
var interactionID = interaction.customId.replace('chatot~', '');
//Delete message
if (interactionID == 'delete') {
try {
setTimeout(() => interaction.message.delete().catch(err => console.log("Failed to delete message:", err)), 1);
} catch (err) {
console.log("Failed to delete message:", err);
}
}
//Add pokemon
else if (interactionID == 'track~verify') {
Track.addTrackCommand(client, interaction, config, util, master);
}
//Edit areas
else if (interactionID.startsWith('area~edit')) {
Area.editAreas(client, interaction, config, util);
}
//Show area
else if (interactionID.startsWith('area~show')) {
Area.showArea(client, interaction, config, util);
}
//Add area
else if (interactionID.startsWith('area~add~')) {
Area.editAreaButton(client, interaction, config, util, 'add', interactionID.replace('area~add~', ''));
}
//Remove area
else if (interactionID.startsWith('area~remove~')) {
Area.editAreaButton(client, interaction, config, util, 'remove', interactionID.replace('area~remove~', ''));
}
//Change profile
else if (interactionID.startsWith('profile~change')) {
Profile.changeProfile(client, interaction, config, util);
}
//Add raid
else if (interactionID.startsWith('raid~verify')) {
Raid.addRaid(client, interaction, config, util, master);
}
//Add incident
else if (interactionID.startsWith('incident~verify')) {
Incident.addIncident(client, interaction, config, util, incidentList);
delete require.cache[Incident];
}
//Add quest
else if (interactionID.startsWith('quest~verify')) {
Quest.addQuest(client, interaction, config, util, questList);
}
//Add lure
else if (interactionID.startsWith('lure~verify')) {
Lure.addLure(client, interaction, config, util);
}
//Remove tracking
else if (interactionID.startsWith('remove~verify')) {
let splitId = interactionID.replace('remove~verify~', '').split('~');
Remove.removeTracking(client, interaction, config, util, splitId[0].replace('incident', 'invasion'), splitId[1]);
}
}); //End of buttons
//Slash commands
client.on('interactionCreate', async interaction => {
if (interaction.type !== InteractionType.ApplicationCommand) {
return;
}
let user = interaction.user;
if (user.bot == true) {
return;
}
const command = await interaction.client.commands.get(interaction.commandName);
if (!command) {
return;
}
//Check for user
superagent
.get(util.api.humanInfo.replace('{{host}}', config.poracle.host).replace('{{port}}', config.poracle.port).replace('{{id}}', interaction.user.id))
.set('X-Poracle-Secret', config.poracle.secret)
.end((error, response) => {
if (error) {
console.log('Api error:', error);
} else {
let humanInfo = JSON.parse(response.text);
if (humanInfo.status != 'ok') {
console.log(`User: ${interaction.user.id} | Command: ${interaction.commandName} | Error: ${humanInfo}`);
return;
}
}
}); //End of superagent
try {
let slashReturn = await command.execute(client, interaction, config, util);
} catch (error) {
console.error(error);
await interaction.reply({
content: 'There was an error while executing this command!',
ephemeral: true
}).catch(console.error);
}
}); //End of slash commands
//AutoComplete
client.on('interactionCreate', async interaction => {
if (!interaction.isAutocomplete()) return;
let focusedValue = await interaction.options.getFocused();
for (var i in interaction.options._hoistedOptions) {
if (!interaction.options._hoistedOptions[i]['focused'] == true) {
continue;
}
let optionName = interaction.options._hoistedOptions[i]['name'];
//Pokemon
if (optionName == 'pokemon') {
let filteredList = pokemonList.filter(choice => choice.includes(focusedValue)).slice(0, 25);
sendAutoResponse(filteredList);
}
//Raid
else if (optionName == 'type' && interaction.commandName == config.raidCommand) {
let filteredList = (Object.keys(util.raidLevels).concat(pokemonList)).filter(choice => choice.includes(focusedValue)).slice(0, 25);
sendAutoResponse(filteredList);
}
//Incident
else if (optionName == 'type' && interaction.commandName == config.incidentCommand) {
var incidents = [];
for (const [type, rewards] of Object.entries(incidentList)) {
incidents.push(`${type} (${rewards.join(', ')})`);
} //End of type loop
let filteredList = incidents.filter(choice => choice.includes(focusedValue)).slice(0, 25);
sendAutoResponse(filteredList);
}
//Quest
else if (optionName == 'type' && interaction.commandName == config.questCommand) {
let filteredList = await Object.keys(questList).filter(choice => choice.includes(focusedValue)).slice(0, 25);
//console.log(filteredList)
sendAutoResponse(filteredList);
}
//Templates
else if (optionName == 'template') {
let templateType = interaction.commandName.replace(config.pokemonCommand, 'monster').replace(config.raidCommand, 'raid').replace(config.incidentCommand, 'invasion').replace(config.questCommand, 'quest').replace(config.lureCommand, 'lure');
let allTemplates = templateList[templateType];
var availableTemplates = [];
for (var a in allTemplates){
if (!config.ignoreTemplates.includes(allTemplates[a])){
availableTemplates.push(allTemplates[a]);
}
}
try {
let filteredList = availableTemplates.filter(choice => choice.includes(focusedValue)).slice(0, 25);
if (filteredList.length > 0) {
sendAutoResponse(filteredList);
}
} catch (err) {
console.log("Error getting templates:", err);
}
}
//Profiles
else if (optionName == 'profile') {
createProfileList();
}
//Remove
else if (optionName == 'tracking' && interaction.commandName == config.removeCommand) {
Remove.autoComplete(client, interaction, config, util, questList);
}
} //End of i loop
async function createProfileList() {
superagent
.get(util.api.getProfiles.replace('{{host}}', config.poracle.host).replace('{{port}}', config.poracle.port).replace('{{id}}', interaction.user.id))
.set('X-Poracle-Secret', config.poracle.secret)
.set('accept', 'application/json')
.end((error, response) => {
if (error) {
console.log('Api error:', error);
} else {
let responseText = JSON.parse(response.text);
if (responseText.status == 'ok') {
let apiProfiles = responseText.profile;
if (apiProfiles.length == 0) {
sendAutoResponse(['No profiles']);
} else {
var profileList = [];
for (var p in apiProfiles) {
profileList.push(`${apiProfiles[p]['name']} (${apiProfiles[p]['profile_no']})`)
}
let filteredList = profileList.filter(choice => choice.includes(focusedValue)).slice(0, 25);
sendAutoResponse(filteredList);
}
} else {
console.log("Failed to fetch profiles:", response);
}
}
}); //End of superagent
} //End of createProfileList()
async function sendAutoResponse(filteredList) {
await interaction.respond(
filteredList.map(choice => ({
name: choice,
value: choice
}))
).catch(console.error);
} //End of sendAutoResponse()
}); //End of autoComplete
async function createPokemonList() {
let ignoreForms = [];
for (const [dex, monData] of Object.entries(master.pokemon)) {
pokemonList.push(monData.name.toLowerCase());
if (monData.forms['0'] == {} || Object.keys(monData.forms).length == 1) {
continue;
}
for (const [form, formData] of Object.entries(monData.forms)) {
if (formData.name) {
pokemonList.push(`${monData.name.toLowerCase()} (${formData.name.toLowerCase()})`);
}
}
}
} //End of createPokemonList()
async function createQuestList() {
//Pokemon
for (const [dex, monData] of Object.entries(master.pokemon)) {
questList[monData.name.toLowerCase()] = {
reward: monData.pokedexId,
type: 7,
form: 0
}
if (monData.tempEvolutions) {
questList[`energy_${monData.name.toLowerCase()}`] = {
reward: monData.pokedexId,
type: 12,
form: 0
}
}
if (monData.forms['0'] == {} || Object.keys(monData.forms).length == 1) {
continue;
}
for (const [form, formData] of Object.entries(monData.forms)) {
if (formData.name) {
questList[`${monData.name.toLowerCase()} (${formData.name.toLowerCase()})`] = {
reward: monData.pokedexId,
type: 7,
form: form * 1
}
}
}
}
//Energy
questList['energy'] = {
reward: 0,
type: 12,
form: 0
}
//Stardust
questList['stardust'] = {
reward: 0,
type: 3,
form: 0
}
//Candy
questList['candy'] = {
reward: 0,
type: 4,
form: 0
}
//XL candy
questList['xl candy'] = {
reward: 0,
type: 9,
form: 0
}
//Experience
questList['experience'] = {
reward: 0,
type: 1,
form: 0
}
//Items
for (const [itemName, itemNumber] of Object.entries(util.questItems)) {
questList[itemName] = {
reward: itemNumber,
type: 2,
form: 0
}
}
} //End of createQuestList()
async function createTemplateList() {
superagent
.get(util.api.getTemplates.replace('{{host}}', config.poracle.host).replace('{{port}}', config.poracle.port))
.set('X-Poracle-Secret', config.poracle.secret)
.set('accept', 'application/json')
.end((error, response) => {
if (error) {
console.log('Api error:', error);
} else {
let responseText = JSON.parse(response.text);
if (responseText.status == 'ok') {
var templates = {};
//Each type (monster/raid/lure/etc)
for (const [type, langInfo] of Object.entries(responseText.discord)) {
var typeTemplates = [];
//Each language
for (const [langName, temps] of Object.entries(langInfo)) {
typeTemplates.push(Object.values(temps));
} //End of language loop
typeTemplates.sort();
typeTemplates = [...new Set(typeTemplates)];
var cleanTemplates = [];
for (var t in typeTemplates[0]) {
if (!config.ignoreTemplates.includes(typeTemplates[0][t])) {
if (typeTemplates[0][t].toString() == config.defaultTemplateName) {
cleanTemplates.push(`${typeTemplates[0][t].toString()} (Default)`);
} else {
cleanTemplates.push(typeTemplates[0][t].toString());
}
}
} //End of t loop
templates[type] = cleanTemplates.slice(0, 25);
} //End of type loop
templateList = templates;
} else {
console.log('Failed to fetch templates:', response);
}
}
}); //End of superagent
} //End of createTemplateList()
async function createIncidentList() {
request("https://rocket.malte.im/api/characters", {
json: true
}, (error, res, body) => {
if (error) {
return console.log(error)
};
if (!error && res.statusCode == 200) {
//Kecleon
incidentList['kecleon'] = ['encounter'];
//Showcase
incidentList['showcase'] = ['contest'];
for (var i in body.characters) {
let rewardsApi = body.characters[i]['rewards'];
var characterRewards = [];
for (var r in rewardsApi) {
var monName = rewardsApi[r]['pokemon']['name'].toLowerCase();
if (rewardsApi[r]['form']['name'] != "FORM_UNSET") {
monName = rewardsApi[r]['form']['name'].replaceAll('_', ' ').toLowerCase();
}
if (rewardsApi[r]['shinies']) {
let shinyOdds = Math.round(100 / (rewardsApi[r]['shinies'] / rewardsApi[r]['total'] * 100));
monName = monName.concat(`✨ (1:${shinyOdds})`);
}
characterRewards.push(monName);
} //End of r loop
//Leaders
if (body.characters[i]['character']['name'].includes('_EXECUTIVE_')) {
incidentList[body.characters[i]['character']['name'].replace('CHARACTER_EXECUTIVE_', '').toLowerCase()] = characterRewards;
}
//Grunts
else {
let gruntName = body.characters[i]['character']['name'].replace('CHARACTER_GRUNT_FEMALE', 'mixed_female').replace('CHARACTER_GRUNT_MALE', 'mixed_male').replace('CHARACTER_', '').replace('_GRUNT_', '_').toLowerCase();
incidentList[gruntName] = characterRewards;
}
} //End of i loop
};
});
} //End of createIncidentList()
async function updateConfigRegisterCommands(client, config) {
superagent
.get(`http://${config.poracle.host}:${config.poracle.port}/api/config/poracleWeb`)
.set('X-Poracle-Secret', config.poracle.secret)
.set('accept', 'application/json')
.end((error, response) => {
if (error) {
console.log('Api error:', error);
} else {
let body = JSON.parse(response.text);
config.pvpFilterMaxRank = body.pvpFilterMaxRank;
config.pvpFilterGreatMinCP = body.pvpFilterGreatMinCP;
config.pvpFilterUltraMinCP = body.pvpFilterUltraMinCP;
config.pvpFilterLittleMinCP = body.pvpFilterLittleMinCP;
config.maxDistance = body.maxDistance;
config.defaultTemplateName = body.defaultTemplateName;
fs.writeFileSync("./config.json", JSON.stringify(config));
//Register Slash Commands
SlashRegistry.registerCommands(client, config);
}
});
} //End of updateConfigRegisterCommands()
client.on("error", (e) => console.error(e));
client.on("warn", (e) => console.warn(e));
client.login(config.token);