-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.js
4747 lines (4426 loc) · 171 KB
/
utils.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
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
var fs = require("fs"),
https = require("https"),
request = require("request"),
imgur = require("imgur"),
images = require("images"),
cheerio = require("cheerio"),
bigInt = require("big-integer"),
config = require("./config");
module.exports = {
createEmbed: createEmbed,
processHelpCommand: processHelpCommand,
getWeekOfYear: getWeekOfYear,
// Processes sound command
processSoundCommand: function(message, sound) {
// Check if command was typed in #bonobot-bonanza channel
if (
message.channel.name !== "bonobot-bonanza" &&
message.channel.name !== "announcements" &&
message.channel.name !== "snax-bonobot"
) {
// if (message.channel.name !== 'snax-bonobot') {
//Send error message
message.reply(
createEmbed([
":warning: Please run my sound commands in #bonobot-bonanza channel to avoid spam."
])
);
} else {
if (sound.indexOf("help") !== -1) {
processHelpCommand(message, "sounds");
return;
} else if (config.sounds.indexOf(sound) !== -1) {
// Check if user is in a voice channel
if (typeof message.member.voiceChannel !== "undefined") {
var channel = message.member.voiceChannel;
if (config.botAvailable) {
//Join user channel and play sound
channel
.join()
.then(connection => {
config.botAvailable = false;
var dispatcher = connection.playFile(
"public/sound/" + sound + ".mp3"
);
dispatcher.on("end", reason => {
channel.leave();
config.botAvailable = true;
});
})
.catch(console.error);
} else {
message.reply(
createEmbed([
":warning: I am currently busy playing another sound :notes:, please wait!"
])
);
}
} else {
//Send random sound error message
message.reply(createEmbed(config.soundErrorDescriptions));
}
}
}
},
// Stop playing sound
stopPlayingSound: function(message) {
// Check if command was typed in #bonobot-bonanza channel
if (
message.channel.name !== "bonobot-bonanza" &&
message.channel.name !== "announcements" &&
message.channel.name !== "snax-bonobot"
) {
// if (message.channel.name !== 'snax-bonobot') {
//Send error message
message.reply(
createEmbed([
":warning: Please run my commands in #bonobot-bonanza channel to avoid spam."
])
);
} else {
// Check if user is in a voice channel
if (typeof message.member.voiceChannel !== "undefined") {
var channel = message.member.voiceChannel;
if (!config.botAvailable) {
channel.leave();
config.botAvailable = true;
}
}
message.delete(1000);
}
},
// Processes stats command
// (!snax stats discordID||@mention||username all_time||month||week||last_week)
processStatsCommand: function(message, command, pool, richEmbed) {
var queryLabel = "month"; // Default query label
var queryParams = [];
var query = "";
var pointsType = "";
var globalMembers = false;
var top20 = false;
// Removes 'stats' at the start and whitespaces at the start and end
command = command.substring(5).trim();
if (command.indexOf("help") !== -1) {
if (
message.channel.name === "bonobot-bonanza" ||
message.channel.name === "announcements" ||
message.channel.name === "snax-bonobot"
) {
// if (message.channel.name === 'snax-bonobot') {
processHelpCommand(message, "stats");
return;
}
//Send error message
message.reply(
createEmbed([
":warning: Please run help commands in #bonobot-bonanza channel to avoid spam."
])
);
return;
}
if (command.indexOf("global") !== -1) {
globalMembers = true;
command = command.replace("global", "").trim();
}
if (command.indexOf("top20") !== -1) {
top20 = true;
command = command.replace("top20", "").trim();
}
// Split paramsValues
var paramsValues = command.split(" ");
// First parameter has to be a query label or if empty uses default label (month)
if (paramsValues.length !== 0) {
if (paramsValues[0] !== -1) {
if (
["month", "all_time", "week", "last_week"].indexOf(
paramsValues[0]
) !== -1
) {
queryLabel = paramsValues[0];
} else if (
["text", "voice", "dailies", "rep"].indexOf(
paramsValues[0]
) !== -1
) {
pointsType = paramsValues[0];
}
}
if (paramsValues[1] !== -1) {
if (
["month", "all_time", "week", "last_week"].indexOf(
paramsValues[1]
) !== -1
) {
queryLabel = paramsValues[1];
} else if (
["text", "voice", "dailies", "rep"].indexOf(
paramsValues[1]
) !== -1
) {
pointsType = paramsValues[1];
}
}
}
var query =
"SELECT discord_id, username, SUM(valid_messages_count) as valid_messages_count, SUM(valid_characters_count) as valid_characters_count, " +
"SUM(seconds_muted) as seconds_muted, SUM(seconds_unmuted) as seconds_unmuted, SUM(voice_points) as voice_points, " +
"SUM(dailies) as dailies, SUM(reputation) as reputation " +
"FROM users WHERE";
var queryParams = [];
if (queryLabel === "month") {
// Month (last 4 weeks)
var where = getLast4WeeksQuery();
query += where + " GROUP BY discord_id, username ";
} else if (queryLabel === "all_time") {
queryParams.push(2017); // Year
query += " year >= $1 GROUP BY discord_id, username ";
} else if (queryLabel === "week") {
queryParams.push(getWeekOfYear(new Date())); // Week
query += " week = $1 GROUP BY discord_id, username ";
} else if (queryLabel === "last_week") {
queryParams.push(
getWeekOfYear(new Date()) - 1 < 1
? getISOWeeks(new Date().getFullYear())
: getWeekOfYear(new Date()) - 1
); // Last Week
query += " week = $1 GROUP BY discord_id, username ";
}
pool.query(query, queryParams, (err, res) => {
if (err) {
console.log(err);
message.reply(createEmbed([":boom: An error occurred!"]));
} else {
if (res.rows.length === 0) {
message.reply(createEmbed([":x: No stats returned!"]));
} else {
// Remove champion members from stats
if (!globalMembers) {
// Remove champion members from stats
res.rows = res.rows.filter(function(user) {
var member = guild.members.get(
user.discord_id.toString()
);
if (typeof member !== "undefined") {
var userRole = module.exports.getMemberRole(
member
);
return (
userRole.name != "Champion" &&
userRole.name != "Officer"
);
}
return false;
});
}
// Iterate through users from query result and calculate points and sort array after
if (pointsType != "dailies" && pointsType != "rep") {
res.rows.forEach(function(user) {
if (pointsType == "text") {
user.points = calculateTextPoints(
user.valid_messages_count,
user.valid_characters_count,
user.dailies
);
} else if (pointsType == "voice") {
user.points = calculateVoicePoints(
user.seconds_unmuted,
user.seconds_muted,
user.voice_points,
user.dailies
);
} else {
user.points =
parseInt(
calculateTextPoints(
user.valid_messages_count,
user.valid_characters_count,
user.dailies
)
) +
parseInt(
calculateVoicePoints(
user.seconds_unmuted,
user.seconds_muted,
user.voice_points,
user.dailies
)
) -
user.dailies;
}
});
// Order array by points descending
res.rows.sort(function(a, b) {
return parseInt(b.points) - parseInt(a.points);
});
} else {
if (pointsType == "dailies") {
// Order array by dailies descending
res.rows.sort(function(a, b) {
return (
parseInt(b.dailies) - parseInt(a.dailies)
);
});
} else if (pointsType == "rep") {
// Order array by rep descending
res.rows.sort(function(a, b) {
return (
parseInt(b.reputation) -
parseInt(a.reputation)
);
});
}
}
if (top20) {
res.rows = res.rows.slice(0, 20);
} else {
res.rows = res.rows.slice(0, 9);
}
var embed = createStatsEmbed(
richEmbed,
res.rows,
queryLabel,
pointsType
);
message.channel.send({
embed
});
}
}
});
},
// Processes profile command (!snax profile all_time||month||week||last_week discordID||@mention||username)
processProfileCommand: function(message, command, pool, guild, richEmbed) {
var queryLabel = "month"; // Show month stats by default in profile (last 4 weeks)
var params = {
discordID: false,
username: false
};
var discordID = "";
var username = "";
var member = "";
var author = false;
var firstProfile = false;
// Removes 'profile' at the start and whitespaces at the start and end
command = command.substring(7).trim();
if (command.indexOf("help") !== -1) {
if (
message.channel.name === "bonobot-bonanza" ||
message.channel.name === "announcements" ||
message.channel.name === "snax-bonobot"
) {
// if (message.channel.name === 'snax-bonobot') {
processHelpCommand(message, "profile");
return;
}
//Send error message
message.reply(
createEmbed([
":warning: Please run help commands in #bonobot-bonanza channel to avoid spam."
])
);
} else if (command.startsWith("all_time")) {
queryLabel = "all_time";
command = command.replace("all_time", "").trim();
} else if (command.startsWith("month")) {
queryLabel = "month";
command = command.replace("month", "").trim();
} else if (command.startsWith("week")) {
queryLabel = "week";
command = command.replace("week", "").trim();
} else if (command.startsWith("last_week")) {
queryLabel = "last_week";
command = command.replace("last_week", "").trim();
}
if (command !== "") {
discordID = command;
username = command;
}
// This block of code is to help to build the query
// Display profile of message author
if (typeof message.mentions.users.first() === "undefined") {
// No mention made
if (command === "") {
discordID = message.author.id;
params["discordID"] = true;
author = true;
} // Confirm if discordID is really a number and search by discord_id or username
else if (
typeof parseInt(discordID) === "number" &&
parseInt(discordID) % 1 === 0
) {
params["discordID"] = true;
} else {
// It has to be a username
params["username"] = true;
}
} else {
discordID = message.mentions.users.first().id;
params["discordID"] = true;
}
var query =
"SELECT discord_id, username, SUM(messages_count) as messages_count, SUM(valid_messages_count) as valid_messages_count, " +
"SUM(characters_count) as characters_count, SUM(valid_characters_count) as valid_characters_count, " +
"SUM(seconds_muted) as seconds_muted, SUM(seconds_unmuted) as seconds_unmuted, SUM(voice_points) as voice_points, " +
"SUM(dailies) as dailies, SUM(reputation) as reputation " +
"FROM users WHERE ";
var queryParams = [];
if (queryLabel === "month") {
// Month (last 4 weeks)
var where = getLast4WeeksQuery();
query += where;
} else if (queryLabel === "all_time") {
queryParams.push(2017); // Year
query += " year >= $1 ";
} else if (queryLabel === "week") {
queryParams.push(getWeekOfYear(new Date())); // Week
query += " week = $1 ";
} else if (queryLabel === "last_week") {
var lastWeek =
getWeekOfYear(new Date()) - 1 < 1
? getISOWeeks(new Date().getFullYear())
: getWeekOfYear(new Date()) - 1;
queryParams.push(lastWeek); // Last Week
query += " week = $1 ";
}
if (params["discordID"]) {
queryParams.push(discordID);
query +=
" AND discord_id = " + (queryLabel !== "month" ? "$2" : "$1");
} else if (params["username"]) {
queryParams.push(username);
query +=
" AND LOWER(username) iLIKE " +
(queryLabel !== "month" ? "$2" : "$1");
}
query += " GROUP BY discord_id, username ";
console.log(query);
pool.connect((err, client, done) => {
const shouldAbort = err => {
if (err) {
console.error("Error in profile transaction", err.stack);
client.query("ROLLBACK", err => {
if (err) {
console.error(
"Error rolling back client",
err.stack
);
}
// Release the client back to the pool
done();
});
}
return !!err;
};
client.query("BEGIN", err => {
if (shouldAbort(err)) {
return;
}
client.query(query, queryParams, (err, res) => {
if (shouldAbort(err)) {
message.reply(
createEmbed([":boom: An error occurred!"])
);
return;
} else if (res.rows.length === 0) {
if (author) {
var user = {
username: message.author.username,
avatar: message.author.displayAvatarURL.replace(
"size=2048",
"width=60&height=60"
),
messages_count: 0,
valid_messages_count: 0,
characters_count: 0,
valid_characters_count: 0,
seconds_unmuted: 0,
seconds_muted: 0,
member: guild.members.get(message.author.id),
voice_points: 0,
dailies: 0,
reputation: 0
};
var embed = createProfileEmbed(
richEmbed,
user,
queryLabel
);
message.channel
.send({
embed
})
.catch(err => console.log(err));
return;
}
message.reply(
createEmbed([
":x: Profile not found for this user!"
])
);
return;
} else {
var user = res.rows[0];
user["member"] = guild.members.get(user.discord_id); // Add member object
}
// Get latest user avatar
client.query(
"SELECT avatar FROM users WHERE LOWER(username) iLIKE $1 ORDER BY (year, week) DESC LIMIT 1",
[user.username],
(err, res) => {
if (shouldAbort(err)) {
return;
} else if (res.rows.length !== 0) {
user["avatar"] = res.rows[0].avatar;
} else {
user["avatar"] = "";
}
var embed = createProfileEmbed(
richEmbed,
user,
queryLabel
);
message.channel
.send({
embed
})
.catch(err => console.log(err));
client.query("COMMIT", err => {
if (err) {
console.error(
"Error committing transaction",
err.stack
);
}
done();
});
}
);
});
});
});
},
// Processes role command (.role_name)
processRoleCommand: function(message, guild) {
let newRole = message.content
.trim()
.substring(1)
.toLowerCase();
let member = message.member;
if (config.availableRoles.indexOf(newRole) === -1) {
return;
}
// Check if command was typed in #bonobot-bonanza channel
if (
message.channel.name === "bonobot-bonanza" ||
message.channel.name === "snax-bonobot"
) {
if (!newRole.length) {
return;
}
// Check if guild has this role
let foundRole = guild.roles.find(
role => role.name.toLowerCase() == newRole
);
if (foundRole) {
if (config.availableRoles.indexOf(newRole) === -1) {
message.reply(
"you can't add **" +
foundRole.name +
"** role to yourself! :thinking:"
);
} else {
// Check if guild member already has this role
let memberRole = member.roles.find(
role => role.name.toLowerCase() == newRole
);
if (memberRole) {
message.reply(
"you already have **" + foundRole.name + "** role!"
);
} else {
member.addRole(foundRole);
message.reply(
"you now have **" + foundRole.name + "** role!"
);
}
}
}
} else {
message.reply(
createEmbed([
":warning: Please run role commands in #bonobot-bonanza channel to avoid spam."
])
);
}
},
// Processes dailies command
processDailiesCommand: function(message, pool) {
if (
message.channel.name !== "bonobot-bonanza" &&
message.channel.name !== "snax-bonobot"
) {
//Send error message
message.reply(
createEmbed([
":warning: Please run dailies command in #bonobot-bonanza channel to avoid spam."
])
);
return;
} else if (message.content.trim().indexOf("help") !== -1) {
processHelpCommand(message, "dailies");
return;
}
var verifyTimestamp = true;
var date = new Date();
var dateUTC = new Date(
date.getUTCFullYear(),
date.getUTCMonth(),
date.getUTCDate(),
date.getUTCHours(),
date.getUTCMinutes(),
date.getUTCSeconds()
);
var queryParams = [
message.author.id, // discordID
message.author.username, // username
message.author.discriminator, // discriminator
0, // characters_count
getWeekOfYear(dateUTC), // week of the year
dateUTC.getFullYear(), // year
message.author.displayAvatarURL.replace(
"size=2048",
"width=60&height=60"
), // avatar
20 // Default number of dailies
];
var time = {
hours: 0,
minutes: 0,
seconds: 0
};
pool.connect((err, client, done) => {
const shouldAbort = err => {
if (err) {
console.error(
"Error in profile transaction in dailies",
err.stack
);
client.query("ROLLBACK", err => {
if (err) {
console.error(
"Error rolling back client in dailies",
err.stack
);
}
// Release the client back to the pool
done();
});
}
return !!err;
};
client.query("BEGIN", err => {
if (shouldAbort(err)) {
return;
}
client.query(
"SELECT dailies_timestamp::timestamp " +
"FROM users WHERE discord_id = $1 AND dailies_timestamp " +
"IS NOT NULL ORDER BY (year, week) DESC LIMIT 1",
[queryParams[0]],
(err, res) => {
if (shouldAbort(err)) {
message.reply(
createEmbed([":boom: An error occurred!"])
);
return;
} else if (res.rows.length === 0) {
verifyTimestamp = false;
} else {
// dailies_timestamp + 24 hours
var dailiesTimestamp = new Date(
new Date(
res.rows[0].dailies_timestamp + ""
).getTime() +
60 * 60 * 24 * 1000
);
var totalSeconds = Math.floor(
(dailiesTimestamp - dateUTC) / 1000
);
time.hours = Math.floor(totalSeconds / 3600);
totalSeconds -= (time.hours % 24) * 3600;
time.minutes = Math.floor(totalSeconds / 60) % 60;
totalSeconds -= time.minutes * 60;
time.seconds = totalSeconds % 60;
}
if (verifyTimestamp && time.hours >= 0) {
message.channel.send(
"**<:snax:230458568497692673> | " +
message.author.username +
", your daily <:kfc:296050563374776320> SNAX points refreshes in " +
time.hours +
(time.hours != 1 ? " hours" : " hour") +
", " +
time.minutes +
(time.minutes != 1
? " minutes "
: " minute ") +
"and " +
time.seconds +
(time.seconds != 1
? " seconds "
: " second") +
"! Nice try :robot:**"
);
client.query("COMMIT", err => {
if (err) {
console.error(
"Error committing transaction",
err.stack
);
}
done();
});
} else {
// Get latest user avatar
client.query(
"INSERT INTO users (discord_id, username, discriminator, characters_count, week, year, avatar, dailies, dailies_timestamp) " +
"VALUES ($1, $2, $3, $4, $5, $6, $7, $8, timezone('utc'::text, now())) " +
"ON CONFLICT (discord_id, week, year) DO UPDATE SET " +
"dailies = users.dailies + $8, " +
"dailies_timestamp = timezone('utc'::text, now()) " +
"WHERE (timezone('utc'::text, now()) >= users.dailies_timestamp + interval '24 hours' OR users.dailies_timestamp IS NULL) AND " +
"users.discord_id = $1 AND users.week = $5 AND users.year = $6 ",
queryParams,
(err, res) => {
if (shouldAbort(err)) {
return;
}
client.query(
"INSERT INTO users_bananas " +
"VALUES ($1, $2) " +
"ON CONFLICT (discord_id) DO UPDATE SET " +
"bananas = users_bananas.bananas + $2",
[queryParams[0], 5],
(err, res) => {
if (shouldAbort(err)) {
return;
}
message.channel.send(
"**<:snax:230458568497692673> | " +
message.author.username +
", you received your <:kfc:296050563374776320> 20 daily SNAX points!**\n" +
"**Here is 🍌 5 bananas to help you conquer this community of bonobos!**"
);
client.query("COMMIT", err => {
if (err) {
console.error(
"Error committing transaction",
err.stack
);
}
done();
});
}
);
}
);
}
}
);
});
});
},
// Processes rep command
processRepCommand: function(message, pool) {
if (
message.channel.name !== "bonobot-bonanza" &&
message.channel.name !== "snax-bonobot"
) {
//Send error message
message.reply(
createEmbed([
":warning: Please run rep command in #bonobot-bonanza channel to avoid spam."
])
);
return;
} else if (message.content.trim().indexOf("help") !== -1) {
processHelpCommand(message, "rep");
return;
}
var verifyTimestamp = true;
var date = new Date();
var dateUTC = new Date(
date.getUTCFullYear(),
date.getUTCMonth(),
date.getUTCDate(),
date.getUTCHours(),
date.getUTCMinutes(),
date.getUTCSeconds()
);
var queryParams = [
message.author.id, // discordID
message.author.username, // username
message.author.discriminator, // discriminator
0, // characters_count
getWeekOfYear(dateUTC), // week of the year
dateUTC.getFullYear(), // year
message.author.displayAvatarURL.replace(
"size=2048",
"width=60&height=60"
) // avatar
];
var time = {
hours: 0,
minutes: 0,
seconds: 0
};
var reputationSent = [];
var repLimit =
config.reputationLimit[
module.exports.getMemberRole(message.member).name
];
var responseMessage = "";
pool.connect((err, client, done) => {
const shouldAbort = err => {
if (err) {
console.error(
"Error in transaction in processRepCommand",
err.stack
);
client.query("ROLLBACK", err => {
if (err) {
console.error(
"Error in rolling back client in processRepCommand",
err.stack
);
}
// Release the client back to the pool
done();
});
}
return !!err;
};
client.query("BEGIN", err => {
if (shouldAbort(err)) {
return;
}
client.query(
"SELECT reputation_sent::json, reputation_timestamp " +
"FROM users WHERE discord_id = $1 AND reputation_timestamp " +
"IS NOT NULL ORDER BY (year, week) DESC LIMIT 1",
[queryParams[0]],
(err, res) => {
if (shouldAbort(err)) {
message.reply(
createEmbed([":boom: An error occurred!"])
);
return;
} else if (res.rows.length === 0) {
verifyTimestamp = false;
} else {
reputationSent = res.rows[0].reputation_sent;
// reputation_timestamp + 24 hours
var dailiesTimestamp = new Date(
new Date(
res.rows[0].reputation_timestamp + ""
).getTime() +
60 * 60 * 24 * 1000
);
var totalSeconds = Math.floor(
(dailiesTimestamp - dateUTC) / 1000
);
time.hours = Math.floor(totalSeconds / 3600);
totalSeconds -= (time.hours % 24) * 3600;
time.minutes = Math.floor(totalSeconds / 60) % 60;
totalSeconds -= time.minutes * 60;
time.seconds = totalSeconds % 60;
}
// If user row exists where reputation_timestamp is not null and 24 have passed => reset reputation
if (verifyTimestamp && time.hours < 0) {
client.query(
"UPDATE users SET reputation_sent = '[]'::json " +
"WHERE discord_id = $1 ",
[queryParams[0]],
(err, res) => {
if (shouldAbort(err)) {
message.reply(
createEmbed([
":boom: An error occurred on resetting reputation!"
])
);
return;
}
}
);
reputationSent = [];
}
// USer doesn't have more reputation to give
if (
reputationSent.length >= repLimit &&
verifyTimestamp &&
time.hours >= 0
) {
message.channel.send(
"**<:snax:230458568497692673> | " +
message.author.username +
", you can award more <:cookie:285277471094472716> reputation in " +
time.hours +
(time.hours != 1 ? " hours" : " hour") +
", " +
time.minutes +
(time.minutes != 1
? " minutes "
: " minute ") +
"and " +
time.seconds +
(time.seconds != 1
? " seconds "
: " second") +
"!**"
);
client.query("COMMIT", err => {
if (err) {
console.error(
"Error committing transaction",
err.stack
);
}
done();
});
return;
} else {
// User has reputation to give
if (
typeof message.mentions.users.first() ===
"undefined"
) {
//If no mention was made
message.channel.send(
"**<:snax:230458568497692673> | " +
message.author.username +
", you need to mention at least one user to award him with <:cookie:285277471094472716> reputation!** (type: `.rep help` for help)"
);
client.query("COMMIT", err => {
if (err) {
console.error(
"Error committing transaction",
err.stack
);
}
done();
});
return;
}
var errorMessages = ["", "", ""];
var users = message.mentions.users.array();
users = users.filter(function(user) {
// User can't give rep to himself
if (user.id == message.author.id) {
errorMessages[0] =
"**<:snax:230458568497692673> | " +
message.author.username +
", did you really expect to be able give <:cookie:285277471094472716> reputation to yourself?! :bell: Shame! :bell:**\n";
} else if (user.bot) {
// Can't give rep to bots
if (user.id == "352554272065585152") {
//snax-bonobot ID
errorMessages[1] =
"**<:snax:230458568497692673> | " +
message.author.username +
", I know you love me but my <:cookie:285277471094472716> reputation is already at max level! :kissing_heart:**\n";
} else {
errorMessages[2] =
"**<:snax:230458568497692673> | " +
message.author.username +
", you can't give <:cookie:285277471094472716> reputation to bots... but they still love you anyway! <:snaxhearts:296063806432608266>**\n";