-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcommands.js
929 lines (802 loc) · 33.7 KB
/
commands.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
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
const cheerio = require('cheerio');
const axios = require('axios');
const convertUnits = require('convert-units');
const mathjs = require('mathjs');
const xkcd = require('relevant-xkcd');
const util = require('./util');
const transactions = require('./modules/transactions');
const scv = require('./modules/scv');
const cconvert = require('./modules/cconvert');
const Timer = require('./classes/Timer');
const Hangman = require('./classes/Hangman');
const config = require('./config.json');
const commandDesc = require('./data/commands.json');
const cyrillicMap = require('./data/cyrillic.json');
const NUMBERS = require('./data/numbers.json');
const UNITSPACE = '\u202F';
const sourceCodeURL = 'https://github.com/Bluefire2/bloo-bot';
const uptimeTimer = new Timer();
const polls = {},
hangmen = {},
hmPMListeners = {},
hmPMTimeouts = {};
/**
* Outputs the descstring for a command.
*
* @param channelID The channel ID.
* @param cmdName The command name.
* @returns {Array} The descstring as an array, line by line.
*/
const descString = async (channelID, cmdName) => {
let prefix = await scv.get(channelID, 'prefix');
// output the command docstring
let currCmd = commandDesc[cmdName],
outText = [];
// signature and descstring
const cmdParams = typeof currCmd.params === 'undefined' ? {} : currCmd.params; // huh
let admin = false,
me = false;
if (typeof currCmd.permissions !== 'undefined') {
if (currCmd.permissions === 'me') {
me = true;
} else if (currCmd.permissions === 'admin') {
admin = true;
}
}
let usageStr = prefix + cmdName;
if (Object.keys(cmdParams).length !== 0) {
const defaults = typeof currCmd.defaults === 'undefined' ? 0 : currCmd.defaults,
numParams = Object.keys(cmdParams).length;
const pDocs = Object.keys(cmdParams).map(key => {
const parameter = cmdParams[key];
let pString = `${key}`;
if (typeof parameter.default !== 'undefined') {
// a default parameter
pString += `=${parameter.default}`;
}
pString += ` (${Array.isArray(parameter.type) ? parameter.type.join(', ') : parameter.type})`;
return pString;
});
usageStr += " <" + pDocs.join("> <") + ">";
}
outText.push(usageStr);
if (me) {
outText.push(currCmd.desc + ' (bot admin only)');
} else if (admin) {
outText.push(currCmd.desc + ' (requires channel admin privileges)');
} else {
outText.push(currCmd.desc);
}
outText.push('\n');
// parameters
if (!util.objectIsEmpty(cmdParams)) {
outText.push('Parameters:');
Object.keys(cmdParams).forEach(key => {
let parameter = cmdParams[key];
outText.push(key + ": " + parameter.desc);
});
}
// aliases
let allAliases = [];
// default aliases
let aliases = currCmd.aliases;
if (Array.isArray(aliases)) {
allAliases = aliases.slice(0);
}
// custom aliases
let customAliases = await transactions.aliasesForCommand(channelID, cmdName);
allAliases = allAliases.concat(customAliases);
if (allAliases.length > 0) {
// command has one or more aliases
outText.push(`\nAlias(es): ${allAliases.join(', ')}`);
}
return outText;
};
/**
* Maps the aura tier name to its slayer kill multiplier. Used in the `slayer` command.
*
* @param tier The name of the aura tier.
* @returns {*} The multiplier for the tier, or false if no such tier exists.
*/
const slayerAuraChance = (tier) => {
let auraToTier = {
"none": 1.0,
"dedicated": 1.03,
"greater": 1.05,
"master": 1.07,
"supreme": 1.1,
"legendary": 1.15
}, multiplier;
if (tier > 5 || tier < 0 || (typeof tier !== 'number' && auraToTier[tier] === 'undefined')) {
return false;
}
let index = typeof tier === 'string' ? tier : Object.keys(auraToTier)[tier];
multiplier = auraToTier[index];
return 1 / (2 - multiplier); // expected value of geometric distribution
};
// Store the current math variables. These will expire on restart but will persist if the bot is kicked and then reinvited.
const mathVariables = {},
mathConstants = {
pi: Math.PI,
e: Math.E
};
/*
* The object that stores all the commands. Command functions must take at least one param, msg, which is the message
* that triggered the command. If the command is documented to take parameters in commmands.json, then the function
* should take those parameters, in the order that they're documented in.
*/
const commands = {
listcmd: (client, msg, sendMsg) => {
let outText = 'Available commands:\n\n',
commandsArray = [],
cmdNames = Object.keys(commandDesc);
for (let i in cmdNames) {
let commandName = cmdNames[i],
commandEntry = '',
aliasesArray = commandDesc[commandName].aliases,
admin = typeof commandDesc[commandName].permissions === 'undefined' ? false : commandDesc[commandName].permissions;
if (admin === 'me') {
continue; // don't display the command if it's bot admin only
} else if (admin === 'admin') {
commandEntry += commandName.toUpperCase();
} else {
commandEntry += commandName;
}
if (Array.isArray(aliasesArray)) {
commandEntry += ' (' + aliasesArray.join(', ') + ')';
}
commandsArray.push(commandEntry);
}
outText += commandsArray.join(', ');
return outText;
},
help: async (client, msg, sendMsg, cmdName) => {
if (typeof commandDesc[cmdName] === 'undefined') {
sendMsg('**Undefined command name** "' + cmdName + '"');
} else {
let desc = await descString(msg.channel.id, cmdName);
sendMsg('```' + desc.join('\n') + '```');
}
},
uptime: (client, msg, sendMsg) => {
const timeOnline = uptimeTimer.timeElapsedDhms();
sendMsg(`Online for ${timeOnline.days} days, ${timeOnline.hours} hours, ${timeOnline.minutes} minutes and ${timeOnline.seconds} seconds.`);
},
ping: (client, msg, sendMsg) => {
console.log(Date.now(), msg.createdTimestamp);
let pingTime = (Date.now() - msg.createdTimestamp);
sendMsg('Pong! ' + pingTime + 'ms');
},
source: (client, msg, sendMsg) => {
sendMsg(`**Source code at** ${sourceCodeURL}`);
},
restart: async (client, msg, sendMsg) => {
await sendMsg('Restarting bot.');
process.exit(1); // pm2 will restart if the exit code is not 0
},
eval_js: (client, msg, sendMsg, code) => {
const e = eval(code);
if (typeof e === 'undefined') {
sendMsg('No returned value');
} else {
console.log(e.toString());
sendMsg(e.toString());
}
},
roll: (client, msg, sendMsg, sides, dice = 1) => {
let rolls = [];
for (let i = 0; i < dice; i++) {
rolls.push(util.randomInRange(1, sides));
}
let data = {
variance: mathjs.var,
std: mathjs.std,
mean: mathjs.mean,
median: mathjs.median,
mode: mathjs.mode,
max: mathjs.max,
min: mathjs.min,
sum: mathjs.sum
};
let rollsString = rolls.join(' '),
dataString = Object.keys(data).map(key => {
let func = val => {
if (key === 'mode') {
return `[${data[key](val)}]`;
}
return util.roundTo(data[key](val), 3);
};
return `${key}: ${func(rolls)}`;
}).join(', ');
return `${rollsString};\n\n${dataString}`;
},
flipcoin: (client, msg, sendMsg) => {
let HorT = util.randomInRange(0, 1) === 1 ? 'heads' : 'tails';
msg.reply(HorT);
},
pasta: async (client, msg, sendMsg, pastaName) => {
let channelID = msg.channel.id,
pastaData = require("./data/pastas.json"),
customPastaNames = await transactions.pastaNamesForChannel(channelID);
// TODO: implement subcommands instead of doing this
if (pastaName === 'list') {
return Object.keys(pastaData).concat(customPastaNames);
} else {
if (pastaName in pastaData) {
let pastaText = pastaData[pastaName];
sendMsg(pastaText);
} else if (customPastaNames.includes(pastaName)) {
let pastaText = await transactions.pastaForChannelWithName(channelID, pastaName);
sendMsg(pastaText);
} else {
sendMsg(`No pasta with name ${pastaName}.`);
}
}
},
// TODO: ditto, make this a subcommand of pasta
addpasta: async (client, msg, sendMsg, name, text) => {
let channelID = msg.channel.id,
pastaData = require("./data/pastas.json");
// check if this pasta already exists by default
if (name in pastaData) {
sendMsg(`Pasta with name ${name} is a default pasta and cannot be overwritten.`);
} else {
await transactions.addPastaForChannel(channelID, name, text);
sendMsg(`Pasta added successfully.`);
}
},
priceCheck: async (client, msg, sendMsg, item, amount = 1) => {
const baseUrl = 'http://runescape.wikia.com/wiki/Exchange:';
try {
let response = await axios.get(baseUrl + item);
let $ = cheerio.load(response.data),
price = parseInt($('#GEPrice').text().replace(/,/g, '')),
totalPrice = util.numberWithCommas(price * amount);
sendMsg(item + ' x ' + amount + ': ' + totalPrice + 'gp');
} catch (error) {
console.log(error);
}
},
slayer: async (client, msg, sendMsg, monster, amount = 1, aura = 0) => {
const baseUrl = 'http://runescape.wikia.com/wiki/';
let auraMultiplier = slayerAuraChance(aura),
expectedAmount;
if (!auraMultiplier) {
sendMsg('**Invalid aura tier **' + aura);
return;
}
expectedAmount = parseInt(amount * auraMultiplier);
// get the monster id
try {
console.log(baseUrl + monster);
let response = await axios.get(baseUrl + monster);
const processXpText = (text) => {
return Math.floor(parseFloat(text.replace(/,/g, '')) * expectedAmount);
};
let $ = cheerio.load(response.data),
monsterName = $('.page-header__title').text(),
xpCombat = processXpText($('.mob-cb-xp').text()),
xpHp = processXpText($('.mob-hp-xp').text()),
xpSlayer = processXpText($('.mob-slay-xp').text());
sendMsg(monsterName + ' x ' + expectedAmount + ': ' + xpSlayer
+ ' slayer xp, ' + xpCombat + ' combat xp and ' + xpHp + ' hp xp.');
} catch (error) {
//console.log(error);
sendMsg(`An error was encountered while fetching slayer data. Does a monster with name "${monster}" exist?`);
}
},
wikipedia: async (client, msg, sendMsg, article, lang = 'en') => {
let baseUrl = 'https://' + lang + '.wikipedia.org/w/api.php?action=query&list=search&format=json&srsearch=',
baseLinkUrl = 'https://' + lang + '.wikipedia.org/wiki/';
try {
let response = await axios.get(baseUrl + article);
if (response.data.query.search.length !== 0) {
let firstResult = response.data.query.search[0],
firstResultTitle = firstResult.title.replace(/ /g, '_');
sendMsg('Wikipedia link: ' + baseLinkUrl + firstResultTitle);
} else {
sendMsg('No search results found for "' + article + '"');
}
} catch (error) {
console.log(error);
if (error.code === 'ENOTFOUND') {
sendMsg('**Invalid language code** "' + lang + '"');
}
};
},
convert: (client, msg, sendMsg, number, unitsFrom, unitsTo, dp = 2) => {
let converted;
try {
converted = util.roundTo(convertUnits(number).from(unitsFrom).to(unitsTo), dp);
sendMsg('**' + number + UNITSPACE + unitsFrom + '** is **' + converted + UNITSPACE + unitsTo + '**');
} catch (e) {
sendMsg('**Error**: ' + e.message);
}
},
b: (client, msg, sendMsg) => {
sendMsg(':b:');
},
youtube: async (client, msg, sendMsg, query) => {
console.log('a');
let baseYoutubeUrl = 'https://www.googleapis.com/youtube/v3/search';
try {
let response = await axios.get(baseYoutubeUrl, {
params: {
key: config.googleAPIKey,
part: 'snippet',
order: 'viewCount',
type: 'video',
q: query
}
});
let items = response.data.items,
firstResult = items[0],
firstVideoID;
try {
firstVideoID = firstResult.id.videoId;
} catch (e) {
return `**No results found for** "${query}"`;
}
sendMsg(util.youtubeIDToLink(firstVideoID));
} catch (error) {
console.log(error);
}
},
prettify: (client, msg, sendMsg, text) => {
let prettifiedText = (text + '').split(' ').map((word) => {
return word.split('').map((char) => {
if (util.isLetter(char)) {
return ':regional_indicator_' + char.toLowerCase() + ':';
} else if (typeof NUMBERS[char] !== 'undefined') {
return ':' + NUMBERS[char] + ':';
} else {
return char;
}
}).join('');
}).join(' ');
sendMsg(prettifiedText);
},
cyrillify: (client, msg, sendMsg, text) => {
let cyrillifiedText = text.split('').map((elem) => {
let mappedChar = cyrillicMap[elem];
if (typeof mappedChar === 'undefined') {
return elem;
} else {
return mappedChar;
}
}).join('');
sendMsg(cyrillifiedText);
},
setPrefix: async (client, msg, sendMsg, value) => {
let channelID = msg.channel.id;
console.log('setting for ' + channelID);
try {
let newPrefix = await scv.set(channelID, 'prefix', value);
sendMsg("**Prefix set to**: " + newPrefix);
console.log(`prefix set to ${newPrefix}`);
scv.listTable();
} catch(err) {
console.log(err);
sendMsg("Failed to set prefix value.");
};
},
addCustomAlias: async (client, msg, sendMsg, command, alias) => {
// validate input - make sure `command` is a valid command
if (Object.keys(commandDesc).indexOf(command) === -1) {
sendMsg(`Undefined command "${command}".`);
} else {
await transactions.addAliasForCommand(msg.channel.id, command, alias);
sendMsg(`Alias set successfully: ${alias} -> ${command}.`)
}
},
eval: (client, msg, sendMsg, expression) => {
let channelID = msg.channel.id,
context = mathVariables[channelID + ''];
if (typeof context === 'undefined') {
context = {};
}
try {
let result = mathjs.eval(expression, context);
sendMsg(`Expression value: ${result}`);
} catch (e) {
sendMsg('Bad expression. Make sure all variables are defined!');
}
},
setvar: (client, msg, sendMsg, varname, varvalue) => {
if (Object.keys(mathConstants).indexOf(varname) !== -1) {
sendMsg(`**Unable to set as variable name** ${varname} **is reserved.**`);
} else {
let varvalueParsed,
channelID = msg.channel.id,
channelMathVariables = mathVariables[channelID + ''];
if (typeof channelMathVariables === 'undefined') {
mathVariables[channelID + ''] = {};
channelMathVariables = mathVariables[channelID + ''];
}
let context = Object.assign({}, channelMathVariables, mathConstants);
// parse expression if we need to
if (typeof varvalue === 'number') {
varvalueParsed = varvalue;
} else {
varvalueParsed = mathjs.eval(varvalue, context);
}
if (typeof channelMathVariables[varname] === 'undefined') {
sendMsg(`**Variable** ${varname} **created and set to** ${varvalueParsed}`);
} else {
sendMsg(`**Variable** ${varname} **changed from** ${mathVariables[varname]} **to** ${varvalueParsed}`);
}
channelMathVariables[varname] = varvalueParsed;
}
},
setvars: (client, msg, sendMsg, varnames, varvalues) => {
const varnamesArray = util.removeWhitespace(varnames).split(','),
varvaluesArray = util.removeWhitespace(varvalues).split(',');
varnamesArray.forEach((elem, index) => {
let value = varvaluesArray[index];
if (Object.keys(mathConstants).indexOf(elem) !== -1) {
// do nothing since we don't want to overwrite global constants
} else {
let valueParsed,
channelID = msg.channel.id,
channelMathVariables = mathVariables[channelID + ''];
if (typeof channelMathVariables === 'undefined') {
mathVariables[channelID + ''] = {};
channelMathVariables = mathVariables[channelID + ''];
}
let context = Object.assign({}, channelMathVariables, mathConstants);
// parse expression if we need to
if (typeof value === 'number') {
valueParsed = value;
} else {
valueParsed = mathjs.eval(value, context);
}
channelMathVariables[elem] = valueParsed;
}
});
},
ree: (client, msg, sendMsg, i) => {
let eeee = "",
reeee;
if (i >= 0) {
for (let j = 0; j < i; j++) {
eeee += "E";
}
reeee = "R" + eeee;
} else {
for (let j = i; j < 0; j++) {
eeee += "E";
}
reeee = eeee + "R";
}
if (!util.safeSendMsg(msg.channel, reeee)) {
sendMsg("Too long!");
}
},
currconvert: async (client, msg, sendMsg, amount, currFrom, currTo, dp = 2) => {
const currFromTemp = currFrom.toUpperCase(),
currToTemp = currTo.toUpperCase();
try {
let val = await cconvert.convert(amount, currFromTemp, currToTemp)
if (isNaN(val)) {
sendMsg("Oops, something went wrong. Check that your currencies are both valid!");
} else {
sendMsg(`${currFromTemp} ${amount} is ${currToTemp} ${util.roundTo(val, dp)}.`);
}
} catch(err) {
sendMsg("Oops, something went wrong. Check that your currencies are both valid!");
};
},
poll: (client, msg, sendMsg, action, optionsStr = '') => {
const channelID = msg.channel.id;
const pollExists = () => {
return typeof polls[channelID] !== 'undefined';
};
const createPoll = () => {
polls[channelID] = {};
return polls[channelID];
};
const deletePoll = () => {
delete polls[channelID];
};
const pollOpen = () => {
polls[channelID].open = true;
};
const openPoll = () => {
polls[channelID].open = true;
};
const closePoll = () => {
polls[channelID].open = false;
};
if (action === 'open') {
if (util.sentByAdminOrMe(msg)) {
if (pollExists()) {
openPoll();
sendMsg('**Poll opened.**');
} else {
sendMsg('No poll to open!');
}
} else {
sendMsg('Must be admin to open, close or delete a poll.');
}
} else if (action === 'close') {
if (util.sentByAdminOrMe(msg)) {
if (pollExists()) {
closePoll();
sendMsg('**Poll closed.**');
} else {
sendMsg('No poll to close!');
}
} else {
sendMsg('Must be admin to open, close or delete a poll.');
}
} else if (action === 'create') {
if (!pollExists()) {
// validate input:
if (optionsStr === '') {
sendMsg('Must specify poll options!');
}
const options = optionsStr.split(';').map(string => string.trim());
if (!Array.isArray(options) || options.length < 2) {
sendMsg('Must have more than one option!');
return;
}
// do stuff
polls[channelID] = {
open: true,
votes: {},
options: options
};
sendMsg('**New poll created and opened.**');
} else {
sendMsg('Delete the current poll before creating a new one!');
}
} else if (action === 'delete') {
if (util.sentByAdminOrMe(msg)) {
if (pollExists()) {
deletePoll();
sendMsg('**Current poll deleted.**');
} else {
sendMsg('No poll to delete!');
}
} else {
sendMsg('Must be admin to open, close or delete a poll.');
}
} else if (action === 'tally' || action === 'show') {
if (pollExists()) {
const currPoll = polls[channelID],
votes = currPoll.votes,
options = currPoll.options,
tally = {},
outText = [];
let totalVotes = 0;
options.forEach(elem => {
tally[elem] = 0;
});
Object.keys(votes).forEach(key => {
const vote = votes[key],
optionSelected = options[vote - 1];
tally[optionSelected]++;
totalVotes++;
});
outText.push('Poll results so far:\n');
console.log(tally);
Object.keys(tally).forEach(key => {
const count = tally[key],
percentage = util.roundTo(count / totalVotes * 100, 2);
let currentCountString = `${options.indexOf(key) + 1}. ${key}: ${count} votes`;
if (!isNaN(percentage)) {
// if no votes have been case, percentage gets evaluated to NaN
currentCountString += ' ' + `(${percentage}%)`;
}
outText.push(currentCountString);
});
return outText;
} else {
sendMsg('No poll active.');
}
} else {
sendMsg(`Invalid poll action "${action}"`);
}
},
vote: (client, msg, sendMsg, option) => {
const channelID = msg.channel.id;
const pollExists = () => {
return typeof polls[channelID] !== 'undefined';
};
const userID = msg.author.id,
userName = msg.author.username;
if (pollExists()) {
const poll = polls[channelID],
i = poll.options.indexOf(option);
if (i !== -1) {
commands.votei(msg, i + 1);
} else {
sendMsg(`No such option "${option}".`);
}
} else {
// delegate and let votei raise the error
commands.votei(msg, -1);
}
},
votei: (client, msg, sendMsg, optionIndex) => {
const channelID = msg.channel.id;
const pollExists = () => {
return typeof polls[channelID] !== 'undefined';
};
const pollOpen = () => {
return polls[channelID].open;
};
const userID = msg.author.id,
userName = msg.author.username;
if (pollExists()) {
if (pollOpen()) {
const poll = polls[channelID];
if (0 < optionIndex && optionIndex <= poll.options.length) {
if (typeof poll.votes === 'undefined') {
poll.votes = {};
}
poll.votes[userID] = optionIndex;
sendMsg(`**Successfully voted for**: "${poll.options[optionIndex - 1]}".`);
} else {
sendMsg('Invalid option index.');
}
} else {
sendMsg('Current poll is closed.');
}
} else {
sendMsg('No poll active!');
}
},
xkcd: async (client, msg, sendMsg, keywords) => {
let response = await xkcd.fetchRelevant(keywords);
let outString = '';
outString += `Relevant XKCD found: **${response.safeTitle}**\n\n`;
outString += response.imageURL;
//outString += response.altText;
sendMsg(outString);
},
hangman: (client, msg, sendMsg, action, guessLetter = '') => {
const channelID = msg.channel.id,
hm = hangmen[channelID];
if (action === 'start') {
// current pm listener
const hmPMListener = hmPMListeners[channelID],
hmPMTimeout = hmPMTimeouts[channelID],
user = msg.author,
MAX_PHRASE_LENGTH = 100;
sendMsg(`${util.tagUser(user)}, check your PMs!`);
new Promise((resolve, reject) => {
// remove any present listeners
if(typeof hmPMListener !== 'undefined') {
client.removeListener('message', hmPMListener);
}
// timeout the listener after 60s
if(typeof hmPMTimeout !== 'undefined') {
clearTimeout(hmPMTimeout);
}
hmPMTimeouts[channelID] = setTimeout(reject, 60000);
// send the user instructions
user.send('Message me the game settings for the game, like so:');
user.send('[phrase], [max_guesses]');
user.send('[phrase] is the phrase/word (letters only) to guess, and [max_guesses] is the amount of wrong guesses allowed.');
user.send('Don\'t include the [], and remember to separate the two with a comma.');
// this is the function that we use as our onmessage listener
// it looks for a PM from the user and checks that it's the right format
hmPMListeners[channelID] = initMsg => {
if (util.isPM(initMsg) && initMsg.author.id === msg.author.id) {
// we got a PM, and it's from the correct user
// verify that it's valid input
const initMsgSplit = initMsg.content.split(',');
if (initMsgSplit.length === 2 && util.TypeCheck.int(initMsgSplit[1].trim())) {
const phrase = initMsgSplit[0].trim(),
limit = parseInt(initMsgSplit[1].trim());
if (!util.isPhrase(phrase)) {
initMsg.channel.send('Phrase must consist of only letters and spaces.');
} else if(phrase.length > MAX_PHRASE_LENGTH) {
initMsg.channel.send(`Phrase cannot be longer than ${MAX_PHRASE_LENGTH} characters, currently ${phrase.length} characters.`);
} else {
initMsg.channel.send(`Starting hangman with phrase "${phrase}" and ${limit} wrong guesses.`);
clearTimeout(hmPMTimeouts[channelID]);
resolve({phrase: phrase, max_score: limit});
}
} else {
initMsg.channel.send('Please specify the parameters in the correct format: "phrase, max_guesses".');
}
}
};
client.on('message', hmPMListeners[channelID]);
}).then(hmArgs => {
sendMsg(`Hangman game started, with ${hmArgs.max_score} wrong guesses.`);
const h = new Hangman();
h.init(hmArgs);
hangmen[channelID] = h;
sendMsg(`Current phrase: \`${h.action('hint', [])}\``);
}).catch(err => {
sendMsg(`${util.tagUser(user)}, you took too long to send the PM :( Try again if you want to start.`);
}).finally(() => {
// clear the listener; this used to cause a bug where all the previous listeners would accumulate
client.removeListener('message', hmPMListeners[channelID]);
clearTimeout(hmPMTimeouts[channelID]);
});
} else if (typeof hm !== 'undefined') {
// check game is not over
if (!hm.isFinished()) {
// if not, then do the thing
if (action === 'guess') {
if (guessLetter === '') {
sendMsg('No letter/phrase specified.');
} else {
if (guessLetter.length === 1) {
// if it's a char then we guess one letter:
// verify that it's a letter
if (!util.isLetter(guessLetter)) {
sendMsg('Letter must be... a letter.');
} else {
const result = hm.action('guess', [guessLetter]);
if (result) {
sendMsg('Good guess!');
sendMsg(`Full phrase: \`${hm.action('hint', [])}\``);
// check if we won
if (hm.isWon()) {
sendMsg('Congratulations! You win!');
}
} else {
// check if we lost
if (hm.isLost()) {
sendMsg('Oops... you guessed wrong and that was your last wrong guess. Game over :(');
sendMsg(`The phrase was "${hm.action('phrase', [])}"`);
} else {
sendMsg(`Oops... you guessed wrong. ${hm.remaining()} wrong guesses left!`);
}
}
}
} else {
// if it's a string, we guess the entire phrase:
const guessString = guessLetter;
if (!util.isPhrase(guessString)) {
// one or more characters are not letters or spaces
sendMsg('Guess must only contain letters.');
} else {
const result = hm.action('guessPhrase', [guessString]);
if (result) {
sendMsg(`Well done! You guessed the correct phrase "${guessString}".`);
} else {
if (hm.isLost()) {
sendMsg('Oops... you guessed wrong and that was your last wrong guess. Game over :(');
sendMsg(`The phrase was "${hm.action('phrase', [])}"`);
} else {
console.log(hm.score);
sendMsg(`Oops... you guessed wrong. ${hm.remaining()} wrong guesses left!`);
}
}
}
}
}
} else if (action === 'hint') {
sendMsg(`Current phrase: \`${hm.action('hint', [])}\``);
} else {
sendMsg(`Undefined action ${action}`);
}
} else {
sendMsg('Current game is over, you must start a new one.');
}
} else {
sendMsg('No game initialised, you must first start one.');
}
},
cshift: (client, msg, sendMsg, k, phrase) => {
const key = Number.isInteger(parseInt(k)) ? k : util.letterToIndex(k),
codetext = phrase.split('').map(char => {
if(char === ' ') {
return ' ';
} else {
const i = util.letterToIndex(char);
return util.indexToLetter(i + key);
}
}).join('');
sendMsg(codetext);
}
};
// export stuff
module.exports = commands;
module.exports.descString = descString;