-
Notifications
You must be signed in to change notification settings - Fork 11
/
handlers.js
534 lines (461 loc) · 23 KB
/
handlers.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
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
var parsefuncs = require('./parse.js');
const embeds = require('./embeds.js');
const config = require('./config.js'); // consistency right?
var dbfuncs = require("./dbfuncs.js");
var aliases = require("./aliases.js");
const lists = require('./lists.js');
var https = require('https');
const refinecalc = require('./refinecalc.js');
const commands = {};
// i suppose i should say something here
// lol
commands.handleHelp = function(message, { pwbContent, pwbUser }) {
switch(pwbContent.body) {
case 'misc':
return message.channel.send(embeds.helpMiscCommands);
case 'request':
return message.channel.send(embeds.helpRequestParameters);
case 'example':
case 'examples':
return message.channel.send(embeds.helpRequestExamples);
default:
if(pwbUser.permission > 0)
return message.channel.send(embeds.helpCommandsAdmin);
else if(pwbUser.permission === 0)
return message.channel.send(embeds.helpCommandsBasic);
}
};
commands.handleTagMe = function(message, { pwbContent, pwbUser, pwbChannel }) {
// restricts user if they have higher or equal permission level to channel permission requirements
if(pwbUser.permission < pwbChannel.limitedto)
return message.react('🔒');
if(pwbContent.body === '')
return message.react('❎'); // no reqs found
let pars = parsefuncs.parseReqs(pwbContent.body);
if(pars.message === '')
return message.react('❎'); // no coherent parameters given by user
let targetObj = pwbUser;
if(pars.assign !== undefined) { // handle if -assign
if(!existsInGuild(message.guild, pars.assign) && !parsefuncs.isSpecialMention(pars.assign))
return message.react('❎'); // cannot be assigned because doesn't exist in guild
targetObj = dbfuncs.getDiscokid(pars.assign, message.guild.id); // get permission level of -assign target
if(targetObj === undefined)
targetObj = { permission: 0, discordid: pars.assign };
delete pars.assign; // just in case dbfuncs.addRequirement() messes up
if(pwbUser.permission <= targetObj.permission)
return message.react('🔒'); // user isn't good enough to assign on the other person
}
// if user doesn't exist in database, then add him
if(targetObj.dkidID === undefined)
targetObj.dkidID = dbfuncs.addDiscokid(targetObj.discordid, message.guild.id);
else {
let count = dbfuncs.listUserRequirements(targetObj.discordid, message.guild.id, message.channel.id).length;
let mylimit = targetObj.permission === 0 ? config.peasantlimit : config.limitreqs; // peasant limit vs mod limit
if(count >= mylimit) {
message.react('❎'); // target has reached the limit for reqs to make
return message.reply(`you have reached your limit of ${mylimit} reqs`);
}
}
let info = dbfuncs.addRequirement(targetObj.dkidID, pwbChannel.chID, pars);
if(info.changes === 1) {
//message.react('✅');
message.channel.send('```id: '+info.lastInsertRowid+' | '+pars.message+'```');
} else {
message.react('❎');
}
};
// pwbChannel should be undefined if this isn't under watch yet
commands.handleWatch = function(message, { pwbContent, pwbUser }) {
if(pwbUser.permission === 0) // no peasants allowed
return; // message.react('🔒');
let limitedto = parseInt(pwbContent.body); // parse body for extra parameter
if(isNaN(limitedto)) limitedto = 0;
if(pwbUser.permission < limitedto) // user doesn't have enough permission
return message.react('🔒');
let res = dbfuncs.addChannel(message.channel.id, message.guild.id, limitedto);
if(res !== -1) return message.channel.send('The bot is now watching this channel for snap requests');
else return message.channel.send('Error: this channel is probably already under watch');
};
commands.handleUnwatch = function(message) {
let res = dbfuncs.deleteChannel(message.channel.id);
if(res) return message.channel.send('Removed this channel from bot watch and deleted all snap requests in it');
else return message.channel.send('Error: database error');
};
commands.handleShowUser = function(message, { pwbContent, pwbUser, pwbChannel }) {
let targetID = message.author.id;
if(pwbContent.body !== '' && pwbContent.body !== 'me') { // if there is a person targeted
if(parsefuncs.isSpecialMention(pwbContent.body))
targetID = pwbContent.body;
else
targetID = parsefuncs.parseDiscordID(pwbContent.body);
if(targetID === -1)
return message.react('❎'); // not valid id provided
if(message.author.id === targetID)
return message.channel.send(`don't tag yourself`); // don't tag yourself
if(pwbUser.permission === 0)
return message.react('🔒'); // no peasants allowed past here
let targetObj = dbfuncs.getDiscokid(targetID, message.guild.id);
if(targetObj !== undefined && pwbUser.permission < targetObj.permission)
return message.react('🔒'); // user's permission level isn't high enough
}
let res = dbfuncs.listUserRequirements(targetID, message.guild.id, message.channel.id);
let msg = res.map((r) => { return `id: ${r.reqID} | ${r.message}`; }).join('\n');
return message.channel.send(msg === '' ? '0 reqs' : 'use "!pwb delete [id]" (without square brackets) to delete\n```'+msg+'```');
};
commands.handleShowChannel = function(message) {
};
commands.handleForce = function(message) {
};
// for deleting all requests of a user
commands.handleDeleteAll = function(message, { pwbContent, pwbUser, pwbChannel }) {
let targetID = message.author.id;
if(pwbContent.body !== '' && pwbContent.body !== 'me') { // if there is a person targeted
if(parsefuncs.isSpecialMention(pwbContent.body))
targetID = pwbContent.body;
else
targetID = parsefuncs.parseDiscordID(pwbContent.body);
if(targetID === -1)
return message.react('❎'); // not valid id provided
if(message.author.id === targetID)
return message.channel.send(`don't tag yourself`); // don't tag yourself
if(pwbUser.permission === 0)
return message.react('🔒'); // no peasants allowed past here
let targetObj = dbfuncs.getDiscokid(targetID, message.guild.id);
if(targetObj !== undefined && pwbUser.permission < targetObj.permission)
return message.react('🔒'); // user's permission level isn't high enough
}
let res = dbfuncs.listUserRequirements(targetID, message.guild.id, message.channel.id);
let msg = res.reduce((accum, r) => {
let success = dbfuncs.deleteRequirement(r.reqID);
if(success) {
if(accum !== '') accum += '\n';
accum += `id: ${r.reqID} | ${r.message}`;
}
return accum;
}, '')
if(msg === '') message.channel.send('no requests to delete');
else message.channel.send('deleted the following requests:\n```'+msg+'```');
}
// for deleteing reqs
commands.handleDelete = function(message, { pwbContent, pwbUser, pwbChannel }) {
if(pwbContent.body === 'all') {
pwbContent.body = '';
return commands.handleDeleteAll(message, { pwbContent, pwbUser, pwbChannel });
}
let reqID = parseInt(pwbContent.body);
if(isNaN(reqID)) { // if no reqID provided, then show self
pwbContent.body = '';
return commands.handleShowUser(message, { pwbContent, pwbUser, pwbChannel });
} else { // process delete
let reqObj = dbfuncs.getRequirement(reqID);
if(reqObj === undefined)
return message.react('❎'); // not valid reqID
if(reqObj.discordchid !== message.channel.id)
return message.react('❎'); // can only delete from same channel
if(pwbUser.permission === 0 && pwbUser.discordid !== reqObj.discordid)
return message.react('🔒'); // peasants not allowed to delete someone else's
if(pwbUser.permission < reqObj.permission)
return message.react('🔒'); // permission level is lower than target's permission level
let res = dbfuncs.deleteRequirement(reqID);
return message.react(res ? '✅' : '❎');
}
};
// !pwb budget - deletes the budget for the current user
// !pwb budget [number] - sets the budget for the current user
// !pwb budget [tag] - deletes the budget for targeted user
// !pwb budget [number] [tag] - sets the budget for targeted user
// !pwb budget [tag] [number] - sets the budget for targeted user
commands.handleBudget = function(message, { pwbContent, pwbUser, pwbChannel }) {
let pwbTarget = pwbUser; // default targets the user
let { body, targetID } = parsefuncs.parseTargetID(pwbContent.body);
if(targetID !== undefined) { // target acquired
pwbTarget = dbfuncs.getDiscokid(targetID, message.guild.id);
pwbContent.body = body;
}
if(pwbTarget === undefined) // if target doesn't exist in our database, set defaults
pwbTarget = { permission: 0, discordid: targetID };
if(pwbTarget.dkidID === undefined) // if target doesn't exist in our database, create it
pwbTarget.dkidID = dbfuncs.addDiscokid(pwbTarget.discordid, message.guild.id);
if(pwbUser.permission < pwbTarget.permission)
return message.react('🔒'); // user's permission level is lower than target's permission level
if(pwbContent.body === '' || pwbContent.body === 'delete' || pwbContent.body === 'del') { // delete the budget for the target
let result = dbfuncs.setBudget(pwbTarget.dkidID, pwbChannel.chID);
return message.channel.send(`${result ? 'successfully deleted budget' : "failed to delete budget" + targetID !== undefined ? ' of target' : ''}`);
}
let budget = parsefuncs.parseVerboseNumber(pwbContent.body);
if(isNaN(budget))
return message.channel.send("not a valid number");
let result = dbfuncs.setBudget(pwbTarget.dkidID, pwbChannel.chID, budget);
if(result) return message.channel.send(`successfully set budget ${targetID !== undefined ? 'of target ' : ''}to ${budget}`);
else return message.channel.send("There was an error in the database");
};
// !pwb thanks
// !pwb thank you
// !pwb thank
// !pwb ty
commands.handleThanks = function(message, { pwbContent, pwbUser, pwbChannel }) {
if(pwbContent.command === 'thanks' && pwbContent.body === '' ||
pwbContent.command === 'thank' && pwbContent.body === 'you') {
return message.channel.send('no problem');
} else if(pwbContent.command === 'thank' && pwbContent.body === '') {
return message.channel.send('you');
} else if(pwbContent.command === 'ty' && pwbContent.body === '')
return message.channel.send('np');
};
commands.handleClearCurrentSnaps = function(message) {
};
commands.handlePing = function(message) {
};
// !pwb permit [integer] [tag] - sets the permission level for target
// !pwb permit [tag] [integer] - sets the permission level for target
commands.handlePermit = function(message, { pwbContent, pwbUser, pwbChannel }) {
if(pwbContent.body.split(' ').length !== 2) // check if correct number of parameters
return message.channel.send('Format: !pwb permit [tag] [integer]');
let { body, targetID } = parsefuncs.parseTargetID(pwbContent.body);
if(pwbUser.discordid === targetID)
return message.channel.send('Failed: cannot target yourself'); // cannot target self
pwbContent.body = body;
if(targetID === undefined || !existsInGuild(message.guild, targetID))
return message.channel.send('Failed: invalid tag'); // no valid discord id provided
let perm = pwbContent.body; // permission level to set target to
if(isNaN(perm))
return message.channel.send('Failed: invalid integer'); // no number provided
if(perm > pwbUser.permission)
return message.channel.send('Failed: provided integer was higher than ' + pwbUser.permission); // cannot set higher than your own level
let pwbTarget = dbfuncs.getDiscokid(targetID, message.guild.id);
if(pwbTarget === undefined) { // if target doesn't exist in our database, create it
let result = dbfuncs.addDiscokid(targetID, message.guild.id, perm);
if(result !== -1) return message.channel.send('Success: set permission level to ' + perm);
else return message.channel.send('Failed: internal server error 1');
} else if(pwbTarget.permission <= pwbUser.permission) {
let result = dbfuncs.updateDiscokid(pwbTarget.dkidID, perm);
if(result !== -1) return message.channel.send('Success: set permission level to ' + perm);
else return message.channel.send('Failed: internal server error 2');
} else {
return message.channel.send('Failed: target has a higher permission level than your own'); // the target's permission level is higher than yours
}
};
/**
* @param message - if you pass in this parameter, then { pwbContent } is mandatory.
if message is undefined, then the param bot is mandatory.
* @param { pwbContent } - pass in undefined if you didn't pass in param message
* @param bot - mandatory if param message is undefined
* @param querystring - optional. overridden by pwbContent.body if param message exists
*/
commands.handleSearch = async function(message, { pwbContent }={}, bot=message.client, querystring='') {
try {
if(message !== undefined)
querystring = pwbContent.body;
let snapsCurrent = await pingPoringWorld(querystring);
console.log(`${new Date().toLocaleString()} got response from poring.world q='${querystring}'`);
if(message !== undefined) message.react('✅');
let gon = dbfuncs.clearExpiredSnaps();
let snapsNew = dbfuncs.addSnaps(snapsCurrent);
console.log(`${new Date().toLocaleString()} added ${snapsNew.length} new snaps to db; cleared ${gon} expired snaps to db`);
for(let sr of snapsNew) {
sr.alias = 0;
let fullname = parsefuncs.buildItemFullName(sr);
let foundreqs = dbfuncs.findRequirements(sr);
let res; // add all aliases for this to snapsNew so we can search against requirements
if(sr.category.startsWith('Equipment')) // all equipment aliases
res = aliases.equips[parsefuncs.prepName(sr.name)];
else if(fullname.includes('Mastela'))
res = aliases.mastela[parsefuncs.prepName(sr.name)];
else if(sr.category.includes('Potion/Effect'))
res = aliases.potioneffect[parsefuncs.prepName(sr.name)];
else if(sr.category.startsWith('Card')) // all aliases for mvp cards
res = aliases.bosscards[parsefuncs.prepName(sr.name)];
if(res !== undefined) {
foundreqs = res.reduce((acc, curr) => [
...acc,
...dbfuncs.findRequirements({ ...sr, aliasname: curr, alias: 1, refine: sr.refine + refinecalc.calc(sr.name, curr) })
], foundreqs);
}
if(foundreqs.length === 0) // if nobody cares about this, go next
continue;
let itemembed = embeds.buildSnappingInfo(sr);
let channels = {}; // map with key: channelid and value: discordid pings
for(let req of foundreqs) {
if(channels[req.discordchid] === undefined)
channels[req.discordchid] = `<@${req.discordid}>`;
else
channels[req.discordchid] +=`<@${req.discordid}>`;
}
console.log(channels);
// send bot message to each channel
for(let [chid, pings] of Object.entries(channels)) {
bot.channels.fetch(chid).then((chan) => {
chan.send({ content: fullname+' '+pings, embeds: [itemembed] }).catch(console.error);
}).catch(console.error);
}
}
console.log(`${new Date().toLocaleString()} done notifying users of pings`);
} catch(e) {
if(message !== undefined) message.react('❎');
console.error("ERROR pingPoringWorld: " + e);
}
};
commands.handleCleanupMembers = function(message, { pwbContent, pwbUser, pwbChannel }) {
let discokids = dbfuncs.listDiscokids(message.guild.id);
let waitTime = Math.min(Math.max(discokids.length, 10), 1440);
if(isSpamming('cleanupmembers', message.guild.id, waitTime)) {
return message.channel.send(`You must wait at least ${waitTime} minutes before using this command again.`);
}
let mypromises = [];
let asdf = `going through ${discokids.length} members. DO NOT SPAM.`;
//console.log(asdf);
message.channel.send(asdf);
for(let dkid of discokids) {
if(dkid.discordid === config.owner || parsefuncs.isSpecialMention(dkid.discordid)) continue;
mypromises.push(message.client.guilds.fetch(dkid.guildid).then(guild => {
let mypromise;
if(dkid.discordid.charAt(0) === '&')
mypromise = guild.roles.fetch(dkid.discordid.slice(1));
else
mypromise = guild.members.fetch(dkid.discordid);
return mypromise.catch(err => {
switch(err.code) {
case 500: // Connection error
//console.log("Connection error");
message.channel.send("Connection error");
return;
case 10007: // Unknown member
case 10011: // Unknown role
//case 50001: // Missing access
case 50035: // Invalid string
let changes = dbfuncs.deleteMember(dkid.discordid, dkid.guildid)
let words = `removed requests for member ${dkid.discordid} in guild ${dkid.guildid}`;
//console.log(words);
message.channel.send("`"+words+"`");
return;
default:
console.log("Unknown error");
console.log(dkid);
console.log(err);
message.channel.send("Unknown error. Please check the logs. Id: "+(+new Date()));
}
});
}).catch(err => {
//console.log(`Could not fetch guild ${dkid.guildid} for discokid ${dkid.discordid}`);
//console.log(err);
message.channel.send(`Could not fetch guild ${dkid.guildid} for discokid ${dkid.discordid}`);
}));
}
Promise.all(mypromises).then(() => { console.log("done"); message.channel.send("done"); })
}
commands.handleEstimate = function(message, { pwbContent, pwbUser, pwbChannel }) {
let tmp = pwbContent.body.trim().split(' ');
let refine, base;
let format = 'Format: !pwb estimate +<refine> <base price>';
if(tmp.length < 2) return message.channel.send(format);
if(tmp[0].startsWith('+')) [refine, base] = tmp;
else if(tmp[1].startsWith('+')) [base, refine] = tmp;
else return message.channel.send(format);
refine = parseInt(refine.substring(1));
if(isNaN(refine)) return message.channel.send('Error: refine could not be parsed to integer');
if(refine < 0 || refine > 15) return message.channel.send('Error: refine is out of range 0-15');
base = parsefuncs.parseVerboseNumber(base);
if(isNaN(base)) return message.channel.send('Error: base price could not be parsed');
if(base < 0 || base > 999999999) return message.channel.send('Error: base price is out of allowed range');
return message.channel.send(lists.refineprice[refine](base).toLocaleString());
};
commands.handlePriceCheck = async function(message, { pwbContent, pwbUser, pwbChannel }) {
try {
console.log("handlepricecheck");
let words = '';
let jsonMessage = await pcPoringWorld(pwbContent.body);
words += 'Item name : ' + jsonMessage[0].name + '\n';
words += 'Price : ' + jsonMessage[0].lastRecord.price + '\n';
words += 'Stock : ' + jsonMessage[0].lastRecord.stock;
return message.channel.send('```' + words + '```');
} catch(e) {
console.error("ERROR pricecheck failed: " + e);
}
};
module.exports = commands;
let spamTracker = {};
/**
* @param interval - minutes
* @returns true if
*/
function isSpamming(commandid, identifier, interval) {
if(spamTracker[commandid] === undefined) {
spamTracker[commandid] = { identifier: new Date() };
return false;
}
let lastUsage = spamTracker[commandid][identifier];
if(lastUsage === undefined) {
spamTracker[commandid][identifier] = new Date();
return false;
} else if(((new Date() - lastUsage) / 60000) < interval) {
return true;
} else {
spamTracker[commandid][identifier] = new Date();
return false;
}
}
/**
* Takes an idstring (might have & in front for role)
* and checks if there is a user or role in the guild
* @returns true/false. false if it's a bot
*/
function existsInGuild(guild, idstring) {
if(idstring.charAt(0) === '&') { // idstring is a role
let tmp = guild.roles.cache.get(idstring.substring(1));
if(tmp === undefined || tmp.deleted) return;
} else { // idstring is a member
let tmp = guild.members.cache.get(idstring);
if(tmp === undefined || tmp.deleted || tmp.user.bot) return;
}
return true;
}
/**
* pings poring.world for all snapping information
* irrelevant snaps are discarded
* @returns the array of currently active snaps
*/
function pingPoringWorld(querystring) {
if(querystring === undefined) querystring = '';
querystring.replace('+', '%2B');
return new Promise(function(resolve, reject) {
https.get(`https://poring.world/api/search?order=popularity&inStock=1&q=${querystring}`, (resp) => {
let data = '';
// A chunk of data has been recieved.
resp.on('data', (chunk) => {
data += chunk;
});
resp.on('end', () => {
try {
data = JSON.parse(data);
// remove expired snaps
data = data.filter(snap => snap.lastRecord.snapEnd > new Date()/1000);
resolve(data);
} catch (err) {
reject(err.message);
}
});
}).on("error", (err) => {
console.log("Error: " + err.message);
reject(err.message);
});
});
}
// quick price check for clean/unmodified equip
function pcPoringWorld(itemName) {
return new Promise(function (resolve, reject) {
https.get('https://poring.world/api/search?order=price&rarity=&inStock=&modified=0&category=&endCategory=&q=' + itemName, (resp) => {
let data = '';
// A chunk of data has been recieved.
resp.on('data', (chunk) => {
data += chunk;
});
resp.on('end', () => {
data = JSON.parse(data);
resolve(data);
});
}).on("error", (err) => {
console.log("Error: " + err.message);
reject(err.message);
});
});
};