-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwishbot.js
More file actions
1825 lines (1691 loc) · 68.9 KB
/
wishbot.js
File metadata and controls
1825 lines (1691 loc) · 68.9 KB
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
#!/usr/bin/env node
const PlugAPI = require('plugapi');
const https = require('https');
var Datastore = require('nedb');
const moment = require('moment');
const Discord = require('discord.js');
const cheerio = require('cheerio');
const client = new Discord.Client();
var login = require('./login.json')
const bot = new PlugAPI({
email: login.email,
password: login.password
});
var key = login.youtube_api_key;
var botid = login.botid;
bot.deleteAllChat = true;
bot.deleteCommands = false;
bot.deleteMessageBlocks = false;
bot.mutedTriggerNormalEvents = false;
bot.multiLine = true;
bot.multiLineLimit = 5;
var limitTimer;
var autoskipTimer;
var specialInterval;
var wishgameArray = {};
var mainPlaylistID = 12265017; //change to your playlist id
var specialPlaylistID = 12469688; //change to your playlist id
var jukeboxPlaylistID = 12469689; //change to your playlist id
var jukeboxPlayed = null;
var mark = null;
var mark2 = null;
var playedSongs = [];
var playedAds = [];
var jukeboxActive = false;
var specialTimer = false;
var loadAdsFirstTime = true;
var specialTrack = false;
var rouletteGame = [];
var roulette = false;
var rouletteTimer;
var songhistory = [];
var adshistory = [];
var jukebox = [];
var messagingBot = {};
var summoningHost = {};
var wisdomArray = {};
var discord_connected = false;
var reconnected = true;
var channel;
var time_limit = 600;
client.on('ready', () => {
discord_connected = true;
channel = client.channels.cache.find(ch => ch.name === 'summon');
});
client.on('error', (err) => {
console.log(err.message);
});
client.login(login.discord);
//default playlist db
var db = new Datastore({
filename: 'playlist'
});
db.loadDatabase();
//ads playlist db
var db2 = new Datastore({
filename: 'playlist-ads'
});
db2.loadDatabase();
//blacklist playlist db
var db3 = new Datastore({
filename: 'blacklist'
});
db3.loadDatabase();
//userdb
var userdb = new Datastore({
filename: 'userdb'
});
userdb.loadDatabase();
const staff = [6025558, 51935849];
bot.connect(login.room); //room
bot.on(PlugAPI.events.ROOM_JOIN, (room) => {
bot.sendChat(`/me WishBot активирован в ${room}.`); //greeting
var url = bot.getSocketURL();
console.log(url)
var song = bot.getMedia();
if (song != null) {
bot.woot();
var time = bot.getTimeRemaining();
var dj = bot.getDJ();
if (time == 0) {
bot.moderateForceSkip(() => {
bot.sendChat(`/me ${dj.username}Скип из-за зависания трека.`); //says skip due to song hanging bug
});
}
}
});
bot.on(PlugAPI.events.USER_JOIN, (user) => {
console.log(user);
if (staff.includes(user.id)) {
userdb.find({
id: user.id
}).limit(1).exec(function (err, docs) {
if (!err && docs.length == 0) {
user.lastvisit = Date.now();
userdb.insert(user);
setTimeout(function () {
bot.sendChat(`С возвращением, @${user.username}. Добро пожаловать домой!`);
}, 5000);
} else {
if (Math.floor((Date.now() - docs[0].lastvisit) / 1000) > 10800) {
setTimeout(function () {
bot.sendChat(`С возвращением, @${user.username}. Добро пожаловать домой!`);
}, 5000);
}
user.lastvisit = Date.now();
userdb.update({
id: user.id
}, user, {});
}
});
} else if (user.guest != true && user.id != botid) {
currentStaff = bot.getStaff();
var hosts = currentStaff.filter(member => member.role >= 4000);
if (hosts.length > 0) {
userdb.find({
id: user.id
}).limit(1).exec(function (err, docs) {
if (!err && docs.length == 0) {
user.lastvisit = Date.now();
userdb.insert(user);
setTimeout(function () {
bot.sendChat(`@${user.username} Привет, я робот WishBot. Узнать больше - !help, !info.`);
}, 5000);
} else {
if (Math.floor((Date.now() - docs[0].lastvisit) / 1000) > 10800) {
setTimeout(function () {
bot.sendChat(`@${user.username} Привет, снова.`);
}, 5000);
}
user.lastvisit = Date.now();
userdb.update({
id: user.id
}, user, {});
}
});
} else {
userdb.find({
id: user.id
}).limit(1).exec(function (err, docs) {
if (!err && docs.length == 0) {
user.lastvisit = Date.now();
userdb.insert(user);
setTimeout(function () {
bot.sendChat(`@${user.username} Привет, я робот WishBot. Узнать больше - !help, !info. Хостов нет на месте, их можно призвать командой !summon.`);
}, 5000);
} else {
if (Math.floor((Date.now() - docs[0].lastvisit) / 1000) > 10800) {
setTimeout(function () {
bot.sendChat(`@${user.username} Привет, снова. Хостов нет на месте, их можно призвать написав в чат !summon.`);
}, 5000);
}
user.lastvisit = Date.now();
userdb.update({
id: user.id
}, user, {});
}
});
}
}
});
bot.on(PlugAPI.events.USER_LEAVE, (user) => {
userdb.find({
id: user.id
}).limit(1).exec(function (err, docs) {
if (!err && docs.length != 0) {
var time = Date.now();
userdb.update({
id: user.id
}, {
$set: {
lastvisit: time
}
}, {});
}
});
});
//annonce
var annonceInterval = setInterval(annonce, 900000);
function annonce() {
bot.sendChat('@everyone Пиши \!wish в чат, чтобы испытать удачу. Узнать больше - !help, !info. Наш дискорд https://discord.gg/3y3tBYV'); //says write !wish to chat to try your luck
}
function special() {
console.log('Special time!');
specialTimer = true;
}
function skip() {
var song = bot.getMedia();
if (song != null && currentSong.cid == song.cid) {
bot.moderateForceSkip();
}
}
function checkPlaying() {
var song = bot.getMedia();
if (song != null) {
var dj = bot.getDJ();
var time = bot.getTimeRemaining();
if (time == 0 && currentSong.cid == song.cid) {
bot.moderateForceSkip(() => {
bot.sendChat(`/me @${dj.username} Скип из-за зависания трека.`); //says skip due to song hanging bug
});
}
}
}
//history clear interval
var historyInterval = setInterval(historyClear, 604800000);
var historyAdsInterval = setInterval(adsHistoryClear, 86400000);
function historyClear() {
songhistory = songhistory.slice(Math.max(songhistory.length - 200, 0));
}
function adsHistoryClear() {
adshistory = adshistory.slice(Math.max(adshistory.length - 50, 0));
}
function rouletteRoll() {
console.log('Roulette Roll!')
roulette = false;
clearInterval(rouletteInterval);
if (rouletteGame.length == 0) {
rouletteGame = [];
bot.sendChat(`@everyone Розыгрыш окончен. Победителя нет. Никто не участвовал в розыгрыше.`);
} else {
var userid = rouletteGame[Math.floor(Math.random() * rouletteGame.length)];
var user = bot.getUser(userid);
if (user == null) {
rouletteGame = [];
bot.sendChat(`@everyone Розыгрыш окончен. К сожалению, победитель скрылся с места преступления...`);
} else {
var position = bot.getWaitListPosition(userid);
if (position != -1 && position != 0) {
var waitlist = bot.getWaitList();
//var max = waitlist.length - (waitlist.length - position)
var max = waitlist.length;
var min = 1;
var newposition = Math.floor(Math.random() * (max - min + 1)) + min;
if (newposition != position) {
bot.moderateMoveDJ(userid, newposition, () => {
rouletteGame = [];
bot.sendChat(`@everyone Розыгрыш окончен. И у нас есть победитель! Это ${user.username}, который выигрывает ${newposition} место в очереди!`);
});
} else {
rouletteGame = [];
bot.sendChat(`@everyone Розыгрыш окончен. И у нас есть победитель! Это ${user.username}, который выигрывает ${newposition} место в очереди!`);
}
} else if (position == 0) {
rouletteGame = [];
bot.sendChat(`@everyone Розыгрыш окончен. Победитель ${user.username} уже у пульта. В любом случае ему повезло :laughing:`);
} else {
rouletteGame = [];
bot.sendChat(`@everyone Розыгрыш окончен. Победитель ${user.username} забыл вступить в очередь, эх...`);
}
}
}
}
function delay(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function checkYoutubeTracks(cids, callback) {
if (!Array.isArray(cids)) {
cids = [cids];
}
var getData = function (ids) {
return new Promise((resolve, reject) => {
const request = https.get(`https://www.googleapis.com/youtube/v3/videos?part=snippet,status,contentDetails&id=${ids}&key=${key}`, (response) => {
let data = '';
response.on('data', (chunk) => {
data += chunk;
});
response.on('end', () => resolve(data));
response.on('error', (err) => reject(err));
});
});
}
var index = 0;
var arrayLength = cids.length;
var items = [];
var regionblocked = [];
var blocked = [];
var all = [];
var removeIndexes = [];
for (index = 0; index < arrayLength; index += 50) {
ArrChunk = cids.slice(index, index + 50);
var ids = ArrChunk.join(',');
var data = await getData(ids);
if (data != undefined) {
data = JSON.parse(data);
items = items.concat(data.items);
} else {
console.log('Youtube API unreachable.');
}
}
if (items.length == 0) {
blocked = cids;
} else {
items.forEach(function (val, i) {
all.push(val.id)
if (val.status.embeddable == false || val.status.privacyStatus != "public" && val.status.privacyStatus != "unlisted") {
blocked.push(val.id)
removeIndexes.push(i)
} else if (val.contentDetails.hasOwnProperty('regionRestriction')) {
if (val.contentDetails.regionRestriction.hasOwnProperty('blocked')) {
if (val.contentDetails.regionRestriction.blocked.includes('RU')) {
regionblocked.push(val.id)
removeIndexes.push(i)
}
} else if (val.contentDetails.regionRestriction.hasOwnProperty('allowed')) {
if (!val.contentDetails.regionRestriction.allowed.includes('RU')) {
regionblocked.push(val.id)
removeIndexes.push(i)
}
}
}
});
cids.forEach(function (id, i) {
if (!all.includes(id)) {
blocked.push(id);
}
});
for (var i = removeIndexes.length - 1; i >= 0; i--) {
items.splice(removeIndexes[i], 1);
}
}
var result = [blocked, regionblocked, items]
if (typeof callback == 'function') {
callback(result);
} else {
return result;
}
}
function skipSwitch(skiprecent, skipblacklisted, metadata, dj, song) {
var ok = 1;
if (metadata[0].includes(song.cid)) {
var skipblocked = 1;
} else {
var skipblocked = 0;
}
if (metadata[1].includes(song.cid)) {
var skipregionblocked = 1;
} else {
var skipregionblocked = 0;
}
switch (1) {
case skipblacklisted:
setTimeout(function () {
var song2 = bot.getMedia();
if (song.cid === song2.cid) {
bot.moderateForceSkip(() => {
bot.sendChat(`/me @${dj.username} Скип, трек в черном списке.`); //says skip, track blacklisted
});
}
}, 2000);
break;
case skiprecent:
setTimeout(function () {
var song2 = bot.getMedia();
if (song.cid === song2.cid) {
bot.moderateForceSkip(() => {
bot.sendChat(`/me @${dj.username} Скип, трек недавно играл.`); //says skip, track recently played
});
}
}, 2000);
break;
case skipblocked:
setTimeout(function () {
var song2 = bot.getMedia();
if (song.cid === song2.cid) {
bot.moderateForceSkip(() => {
bot.sendChat(`/me @${dj.username} Скип удаленного или заблокированного трека.`); //says skip of deleted or blocked track
});
}
}, 2000);
break;
case skipregionblocked:
setTimeout(function () {
var song2 = bot.getMedia();
if (song.cid === song2.cid) {
bot.moderateForceSkip(() => {
bot.sendChat(`/me @${dj.username} Скип заблокированного в России трека.`); //says skip track blocked in region RU
});
}
}, 2000);
break;
case ok:
setTimeout(function () {
bot.woot();
}, 2000);
var time = bot.getTimeRemaining();
if (time > time_limit && time_limit != 0) {
if (dj.id == 6025558 || dj.id == botid) { //exception for host and bot to play long tracks. Сhange first dj.id to yours.
console.log(`${dj.username} plays a long track`);
} else {
setTimeout(function () {
bot.sendChat(`/me @${dj.username} Треки дольше 10 минут скипаются автоматически.`); //says tracks longer than 10 minutes skip automatically
}, 2000);
let skiptime = time_limit * 1000;
limitTimer = setTimeout(skip, skiptime);
}
} else {
time = (time + 5) * 1000;
autoskipTimer = setTimeout(checkPlaying, time);
}
break;
}
}
function wordEnding(mes, value) {
var ending = '';
var lastdigits = +value.toString().slice(-2);
if (mes === 'mins') {
if (lastdigits == 1) {
ending = 'у';
} else if (lastdigits == 0) {
ending = '';
} else if (lastdigits <= 4) {
ending = 'ы';
} else if (lastdigits > 20) {
lastdigits = +lastdigits.toString().slice(-1);
if (lastdigits == 1) {
ending = 'у';
} else if (lastdigits == 0) {
ending = '';
} else if (lastdigits <= 4) {
ending = 'ы';
} else {
ending = '';
}
} else {
ending = '';
}
} else if (mes === 'hours') {
if (lastdigits == 1) {
ending = '';
} else if (lastdigits == 0) {
ending = 'ов';
} else if (lastdigits <= 4) {
ending = 'а';
} else if (lastdigits > 20) {
lastdigits = +lastdigits.toString().slice(-1);
if (lastdigits == 1) {
ending = '';
} else if (lastdigits == 0) {
ending = 'ов';
} else if (lastdigits <= 4) {
ending = 'а';
} else {
ending = 'ов';
}
} else {
ending = 'ов';
}
}
return ending;
}
async function wisdom(sendWisdom) {
let promise = new Promise((resolve, reject) => {
const request = https.get(`https://randstuff.ru/saying/`, (response) => {
let data = '';
response.on('data', (chunk) => {
data += chunk;
});
response.on('end', () => resolve(data));
response.on('error', (err) => reject(err));
});
});
let data = await promise;
if (data != undefined) {
var $ = cheerio.load(data);
var saying = $('#saying .text tbody tr td').text();
console.log(saying);
sendWisdom(saying)
} else {
var saying = false;
sendWisdom(saying)
}
};
// very smart retrying function(found in plugapi issues)
function Promisify(call, autoretry, timeout) {
if (timeout == undefined) {
timeout = 2000;
}
let resolved = false;
return new Promise(
(resolve, reject) => {
var caller = () => {
let retry = null;
if (autoretry) {
let doRetry = () => {
console.log('PlugAPI call timed out, retrying..');
caller();
};
retry = setTimeout(doRetry, timeout);
}
call((err, data) => {
if (retry) clearTimeout(retry);
if (resolved) return;
resolved = true;
if (err) {
console.log('PlugAPI error: ' + err);
reject(err);
} else
resolve(data)
});
};
caller();
}
);
}
async function addSongs(pl_name, amount) {
var recently_played = [];
if (pl_name === 'main') {
var playlist = db;
var h = songhistory;
} else if (pl_name === 'ads') {
var playlist = db2;
var h = adshistory;
}
var history = bot.getHistory();
history.forEach((track, i) => {
recently_played.push(track.media.cid)
});
var countSongs = function () {
return new Promise((resolve, reject) => {
playlist.count({
$and: [{
unavailable: "no"
},
{
songid: {
$nin: h
}
},
{
songid: {
$nin: recently_played
}
},
{
songid: {
$nin: ids
}
}
]
}, function (err, count) {
if (err) {
console.log(err);
reject();
} else {
resolve(count);
}
});
});
}
var songs = [];
var getRandomSong = function () {
return new Promise((resolve, reject) => {
countSongs().then((count) => {
var randomNumber = Math.floor(Math.random() * (count - 1 + 1)) + 1;
var skipCount = randomNumber - 1;
playlist.find({
$and: [{
unavailable: "no"
},
{
songid: {
$nin: h
}
},
{
songid: {
$nin: recently_played
}
},
{
songid: {
$nin: ids
}
}
]
}).skip(skipCount).limit(1).exec(function (err, docs) {
if (err) {
console.log(err);
reject();
} else {
resolve(docs);
}
});
})
});
}
var updateBlocked = function (blocked) {
return new Promise((resolve, reject) => {
playlist.update({
songid: {
$in: blocked
}
}, {
$set: {
unavailable: "yes"
}
}, {
multi: true
}, function (err, rep) {
if (err) {
console.log(err);
reject();
} else
resolve(rep);
});
});
}
var items = [];
var ids = [];
var toUpdate = [];
while (items.length < amount) {
var ids2 = []
var a = amount - items.length;
for (var i = 0; i < a; i++) {
var docs = await getRandomSong();
ids2.push(docs[0].songid);
ids.push(docs[0].songid);
}
var metadata = await checkYoutubeTracks(ids2);
var blocked = metadata[0]
var regionblocked = metadata[1]
var allblocked = blocked.concat(regionblocked);
toUpdate = toUpdate.concat(allblocked);
var items = items.concat(metadata[2]);
}
var updated = await updateBlocked(toUpdate);
console.log(updated + ' updated as unavailable');
var songs = [];
for (var item of items) {
if (pl_name === 'main') {
songhistory.push(item.id);
} else if (pl_name === 'ads') {
adshistory.push(item.id);
}
var title = item.snippet.title;
var author = item.snippet.channelTitle;
var image = item.snippet.thumbnails.default.url;
var yf_duration = moment.duration(item.contentDetails.duration, moment.ISO_8601);
var duration = yf_duration.asSeconds()
var sdata = {
cid: item.id,
format: 1,
image: image,
duration: duration,
title: title,
author: author
}
songs.push(sdata);
}
return songs;
}
function clearPlaylist(pid) {
return new Promise((resolve, reject) => {
Promisify((callback) => bot.getPlaylistMedias(pid, callback), true, 10000).then((songs) => {
console.log('Songs to clear: ', songs.length);
var delsongs = [];
songs.forEach(function (song, i) {
delsongs.push(song.id);
});
if (delsongs.length > 0) {
bot.removeSongFromPlaylist(pid, delsongs, (err, data) => {
if (err) {
console.log(err);
reject();
} else {
console.log("Deleted all tracks");
resolve();
}
});
} else {
console.log("Playlist is empty");
resolve();
}
});
});
}
function startPlaying() {
return new Promise((resolve, reject) => {
Promisify((callback) => bot.joinBooth(callback), true).then(resolve());
});
}
function stopPlaying() {
return new Promise((resolve, reject) => {
Promisify((callback) => bot.leaveBooth(callback), true).then(resolve());
});
}
function checkBlacklist(cid) {
return new Promise(
(resolve, reject) => {
db3.find({
songid: cid
}).limit(1).exec(function (err, docs) {
if (docs.length > 0) {
console.log(docs);
var skipblacklisted = 1;
resolve(skipblacklisted);
} else if (docs.length == 0) {
var skipblacklisted = 0;
resolve(skipblacklisted);
} else if (err) {
console.log(err);
reject();
}
});
});
}
//what to do on song change
bot.on(PlugAPI.events.ADVANCE, (data) => {
clearTimeout(autoskipTimer);
clearTimeout(limitTimer);
var position = bot.getWaitListPosition(botid);
var song = bot.getMedia();
var dj = bot.getDJ();
if (song != null && reconnected == false) {
var checkForSpecialtrack = function () {
return new Promise(
(resolve, reject) => {
if (specialTrack === false && position == 0) {
if (!jukebox.includes(song.cid)) {
if (!playedSongs.includes(song.cid)) {
playedSongs.push(song.id);
}
resolve();
} else {
resolve();
}
} else if (specialTrack === true && jukeboxActive === false && position == 0) {
bot.activatePlaylist(mainPlaylistID, (err, pl) => {
if (err) {
console.log(err);
reject();
} else {
if (!playedAds.includes(song.cid)) {
playedAds.push(song.id);
}
specialTrack = false;
specialInterval = setInterval(special, 3600000);
bot.sendChat('/me @everyone Рекламная пауза.');
resolve();
}
});
} else {
resolve();
}
});
}
var removeJukeboxLastTrack = function () {
return new Promise(
(resolve, reject) => {
if (jukeboxPlayed !== null) {
bot.removeSongFromPlaylist(jukeboxPlaylistID, jukeboxPlayed, (err, rem) => {
if (err) {
console.log(err);
reject();
} else {
console.log("Deleted jukebox track: " + jukeboxPlayed);
jukeboxPlayed = null;
resolve();
}
});
} else {
resolve();
}
});
}
var JukeboxIteration = function () {
return new Promise(
(resolve, reject) => {
if (jukebox.includes(song.cid) && position == 0) {
var index = jukebox.indexOf(song.cid);
jukebox.splice(index, 1);
jukeboxPlayed = song.id;
if (jukebox.length == 0) {
if (specialTrack === true) {
bot.activatePlaylist(specialPlaylistID, (err, pl) => {
if (err) {
console.log(err);
reject();
} else {
console.log('Switch from jukebox to ads.')
jukeboxActive = false;
resolve();
}
});
} else {
bot.activatePlaylist(mainPlaylistID, (err, pl) => {
if (err) {
console.log(err);
reject();
} else {
console.log('Switch from jukebox to default.')
jukeboxActive = false;
resolve();
}
});
}
} else {
resolve();
}
} else {
resolve();
}
});
}
var checkForSpecialTimer = function () {
return new Promise(
(resolve, reject) => {
if (specialTimer === true && loadAdsFirstTime === false && mark !== song.cid && jukeboxActive === false) {
clearInterval(specialInterval);
bot.activatePlaylist(specialPlaylistID, (err, pl) => {
if (err) {
console.log(err);
reject();
} else {
specialTrack = true;
specialTimer = false;
resolve();
}
});
} else if (specialTimer === true && loadAdsFirstTime === true && mark !== song.cid && jukeboxActive === false) {
clearInterval(specialInterval);
specialTimer = false;
loadAdsFirstTime = false;
addSongs('ads', 50).then((songs) => {
console.log('Ads: ' + songs.length);
mark2 = songs[25].cid;
Promisify((callback) => bot.addSongToPlaylist(specialPlaylistID, songs, callback), true, 20000).then(() => {
bot.activatePlaylist(specialPlaylistID, (err, pl) => {
if (err) {
console.log(err);
reject();
} else {
specialTrack = true;
resolve();
}
});
});
});
} else {
resolve();
}
});
}
var checkForMarkTrack = function () {
return new Promise(
(resolve, reject) => {
if (mark == song.cid && position == 0) {
var toDelete = playedSongs.slice(0);
toDelete.pop();
bot.removeSongFromPlaylist(mainPlaylistID, toDelete, (err, rem) => {
if (err) {
console.log(err);
reject();
} else {
console.log('Deleted: ' + toDelete.length);
playedSongs.splice(0, toDelete.length);
addSongs('main', 100).then((songs) => {
console.log('Songs: ' + songs.length);
mark = songs[0].cid;
Promisify((callback) => bot.addSongToPlaylist(mainPlaylistID, songs, callback), true, 20000).then(() => {
console.log('Mark track maintenance completed');
resolve()
});
});
}
});
} else if (mark2 == song.cid && position == 0) {
var toDelete = playedAds.slice(0);
toDelete.pop();
bot.removeSongFromPlaylist(specialPlaylistID, toDelete, (err, rem) => {
if (err) {
console.log(err);
reject();
} else {
console.log('Deleted: ' + toDelete.length);
playedAds.splice(0, toDelete.length);
addSongs('ads', 25).then((songs) => {
console.log('Ads: ' + songs.length);
mark2 = songs[0].cid;
Promisify((callback) => bot.addSongToPlaylist(specialPlaylistID, songs, callback), true, 20000).then(() => {
console.log('Mark2 track maintenance completed');
resolve()
});
});
}
});
} else {
resolve();
}
});
}
checkForSpecialtrack().then(() => {
removeJukeboxLastTrack().then(() => {
JukeboxIteration().then(() => {
checkForSpecialTimer().then(() => {
checkForMarkTrack();
});
});
});
});
}
reconnected = false;
if (song != null) {
currentSong = song;
if (position == 0) {
lastSong = currentSong;
}
var skiprecent = 0;
delay(4000).then(() => {
bot.getHistory((history) => {