-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathlilybot.js
More file actions
1659 lines (1536 loc) · 47.3 KB
/
Copy pathlilybot.js
File metadata and controls
1659 lines (1536 loc) · 47.3 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
// todo:
// make a github.io page :3
// percussion support
// MULTIPAGE/LONGPAGE MIDI
// changing key/time/clef/tempo/instrument mid staff
// update examples... make them sheet worthy
// command args
// invite and github for others
// join specific channels
// add tune bot specific error messages to help people know whats wrong!!
// different language options OVERHAUL!!!
// actually just make a tunebot2ly compiler????????
// and encorporate all kinds of xxx2ly things????
// tunebots language
// different lilypond templates
// clean up all that duplicate code in the requesting different things back.. with attachments esp.
// make the sheet out better while ur at it
// make files only be converted as they are needed..........
// have a web of conversion paths based on the compilers available...
// redo the CONVERSION system alltogethr.......
// inputs: file, in chat code
// outputs: file, in chat (text voice or file)
// input formats...... various frontends
// output formats....... various backends
// server specific config
// permissions based on server roles?
// save tunes from users
// more elegant javascript in general :3 async ?? promises? ? i got lot to learn
// style
// fix those file rename callbacks?
// more elegant logging system?? use console objects features??
// figure out why sometimes playing doesnt work???????
// it outputs pdf, png, and midi all at once.. so get rid of duplicate code for that
// redo help, tutorial, examples, and personality
// use discord emoji yo
// merge lambot into lilybot?? with lilypond scheme??
// give mogrify out a small border ?? ?
// cache???
// play/request wavs/mp3s?
// watch out for dos'ing somehow?
// tuner?? jam sessions? record from voice and convert to midi/sheets?
// lyrics????? and speech synth??????
// multi page out support ? ?
// soundfont selection??
// pretty things up with embeds??
// transposition
// letter names rendering
// fix badly formated key commands so they dont crash
// AND ADD SYNTAX ERROR REPORTS ? ?
// pickup
// key / tempso /time changes
// be safe on checking for GUILD.ID
// easy one measure rests
// transpose
// something better than delaying a set delay for waiting til files are available and done with???
// libraries
const { spawn } = require("child_process");
const fs = require("fs");
const https = require("https");
const discord = require("discord.js");
const snekfetch = require("snekfetch")
// config
const config = require("./config");
// timers are for leaving voice channels when not used for a while
const playingStatus = {};
const dispatchers = {};
const timers = {};
/* LANGUAGE INTERFACES */
// lilypond templates...
// template to output score and midi both
function makeLilyPondScore(code, sheetTitle, composer)
{
return `
\\version "2.18.2"
\\header {
tagline = ""
title = "${sheetTitle}"
composer = "${composer}"
}
\\score {
${code}
\\layout { }
\\midi { \\tempo 4 = 90 }
}`
}
// make a lilypond score from tune bot code!!
function tuneBotExpression2LilyPondScore(expression)
{
// might wanna add a relative mode sometime
var output = "<<\n";
// start a staff
output += "\\new Staff { ";
var newStaffPending = false;
// default values
var unitValue = 16;
var instrument = "acoustic piano";
var tempo = "tempo 4 = 90";
// title stuff
var sheetTitle = "";
var composer = "";
// split the parts
const parts = expression.split(":");
for(var part of parts)
{
const p = part.trim();
if(!p) continue;
// make a new staff if requested
if(newStaffPending) output += `}\n\\new Staff { \\set Staff.midiInstrument = #"${instrument}" \\${tempo} `;
newStaffPending = false;
if(p.toLowerCase() in config.programs)
{
const i = config.instrumentNames[config.programs[p.toLowerCase()]];
output += `\\set Staff.midiInstrument = #"${i}" `;
instrument = i;
}
else if(p.startsWith("by"))
{
const words = p.split(" ");
composer = words.slice(1).join(" ");
}
else if(p.startsWith("title"))
{
const words = p.split(" ");
sheetTitle = words.slice(1).join(" ");
}
else if(p.startsWith("key"))
{
const args = p.split(" ").filter((v) => {
return v.length;
});
if(args.length > 1)
{
const key = args[1].replace(/\#/g, "is").replace(/\&/g, "es");
output += `\\${args[0]} ${key} \\${args[2]} `;
}
}
else if(p.startsWith("tempo"))
{
output += `\\${p} `;
tempo = p;
}
else if(p.startsWith("time"))
{
output += `\\${p} `;
}
else if(p === "loud")
{
output += `\\set Staff.midiMinimumVolume = #0.7 `;
output += `\\set Staff.midiMaximumVolume = #0.9 `;
}
else if(p === "quiet")
{
output += `\\set Staff.midiMinimumVolume = #0.1 `;
output += `\\set Staff.midiMaximumVolume = #0.3 `;
}
else if(p === "half")
{
unitValue /= 2;
}
else if(p === "double")
{
unitValue *= 2;
}
else if(p in config.tempos)
{
const t = config.tempos[p];
tempo = `tempo 4 = ${t}`;
output += `\\${tempo} `;
}
else if(p in config.clefs)
{
output += `\\clef ${config.clefs[p]} `;
}
else if(p in config.values)
{
unitValue = config.values[p];
}
else
{
var noteBuffer = "";
var lengthBuffer = 1;
var octaveBuffer = 4;
var last = {};
last.chord = false;
last.buffer = "";
var chordBuffer = "";
var inChord = false;
var pendingChord = false;
var dynamic = "";
var suffix = "";
// logarithmic floor
function floorLog(n, e=2)
{
return Math.pow(e, Math.floor(Math.log(n) / Math.log(e)));
}
// convert tunebot length to lilypond length
function convertLength(len, buffer)
{
// basic length value
const baseValue = floorLog(len);
var remainder = len % baseValue;
var base = baseValue;
var dots = 0;
while(remainder && remainder >= base / 2)
{
base = floorLog(remainder);
remainder %= base;
dots++;
}
// whole number
var converted = unitValue / baseValue;
if(converted == 0.5) converted = "\\breve";
else if(converted == 0.25) converted = "\\longa";
return converted.toString() + ".".repeat(dots) + (remainder ? ("~ " + buffer) + convertLength(remainder, buffer) : "");
}
// convert tunebot octave to lilypond octave
function convertOctave(noteBuffer, octave)
{
if(noteBuffer.startsWith("r")) return "";
const count = octave - 3;
if(count > 0) return "'".repeat(count);
else if(count < 0) return ",".repeat(-count);
return "";
}
// add the note buffer to the lilypond output
function flush()
{
if(pendingChord)
{
const appendage = `${chordBuffer}${convertLength(lengthBuffer, chordBuffer)}${suffix}`;
last.chord = true;
last.buffer = chordBuffer;
output += appendage;
pendingChord = false;
if(dynamic) output += `\\${dynamic}`;
output += " ";
dynamic = "";
suffix = "";
}
else if(noteBuffer)
{
const preAppendage = `${noteBuffer}${convertOctave(noteBuffer, octaveBuffer)}`;
const appendage = `${preAppendage}${inChord ? "" : convertLength(lengthBuffer, preAppendage)}${suffix}`;
if(!noteBuffer.startsWith("r"))
{
last.chord = false;
last.buffer = noteBuffer;
}
noteBuffer = "";
if(inChord)
{
chordBuffer += appendage;
if(dynamic) chordBuffer += `\\${dynamic}`;
chordBuffer += " ";
}
else
{
output += appendage;
if(dynamic) output += `\\${dynamic}`;
output += " ";
}
dynamic = "";
suffix = "";
}
}
// go through each input char
for(var c of p)
{
if("abcdefg".indexOf(c.toLowerCase()) != -1)
{
flush();
noteBuffer = c;
lengthBuffer = 1;
}
else if(c == '~')
{
suffix += "~";
}
else if(c == '#')
{
noteBuffer += "is";
}
else if(c == '&')
{
noteBuffer += "es";
}
else if(c == ',')
{
flush();
pendingChord = last.chord;
if(last.chord) chordBuffer = last.buffer;
else noteBuffer = last.buffer;
lengthBuffer = 1;
}
else if(c == '{')
{
flush();
output += "\\repeat unfold 2 { ";
}
else if(c == '}')
{
flush();
output += "} ";
}
else if(c == '(')
{
flush();
output += "\\tuplet 3/2 { ";
}
else if(c == ')')
{
flush();
output += "} ";
}
else if(c == 'U')
{
flush();
unitValue *= 2;
}
else if(c == 'u')
{
flush();
unitValue /= 2;
}
else if(c == '[')
{
flush();
chordBuffer = "<";
inChord = true;
}
else if(c == ']')
{
flush();
chordBuffer += ">";
inChord = false;
pendingChord = true;
lengthBuffer = 1;
}
else if(c == '-')
{
if(!inChord) lengthBuffer++;
}
else if(c == 'r')
{
if(inChord) continue;
if(!pendingChord && noteBuffer.startsWith("r")) lengthBuffer += 4;
else
{
flush();
noteBuffer = "r";
lengthBuffer = 4;
}
}
else if(c == '.')
{
if(inChord) continue;
if(!pendingChord && noteBuffer.startsWith("r")) lengthBuffer++;
else
{
flush();
noteBuffer = "r";
lengthBuffer = 1;
}
}
else if(c == '|')
{
flush();
output += "| ";
}
else if(c == 'z')
{
flush();
suffix += "^\"pizz.\"";
}
else if(c == '^')
{
flush();
suffix += "->";
}
else if(c == 'p')
{
flush();
dynamic += "p";
}
else if(c == 'l')
{
flush();
dynamic += "f";
}
else if(c == 'm')
{
flush();
dynamic = "mp";
}
else if(c == '>')
{
flush();
octaveBuffer++;
}
else if(c == '<')
{
flush();
octaveBuffer--;
}
else if("0123456789".indexOf(c) != -1)
{
flush();
octaveBuffer = c;
}
}
// flush
flush();
// request new staff
newStaffPending = true;
}
}
// finish up
output += "}\n>>";
const lily = makeLilyPondScore(output, sheetTitle, composer);
if(config.testing) console.log(lily);
return lily;
}
/* EXTERNAL COMMANDS */
// run an external command
function runCommand(cmd, args, callback, errorCallback, stdoutCallback)
{
const child = spawn(cmd, args);
child.failed = false;
child.stdout.on("data", (data) => {
if(config.testing) console.log(`${cmd}: ${data}`);
if(stdoutCallback) stdoutCallback(data, child);
});
child.stderr.on("data", (data) => {
if(config.testing) console.error(`${cmd}: ${data}`);
if(stdoutCallback) stdoutCallback(data, child);
});
child.on("close", (code) => {
if((code || child.failed) && errorCallback) errorCallback(`${cmd} exit status: ${code}`);
else if(callback) callback(errorCallback);
});
}
// rm a file or two lol
function removeFiles(paths, callback)
{
if(paths.length) runCommand("rm", paths, callback, console.error);
else callback();
}
// make sure a directory exists in file system
function assertPath(path, callback)
{
runCommand("mkdir", ["-p", path], callback, console.error);
}
// render a midi file to a wav file with timidity
function renderMidi(inFile, outFile, callback, errorCallback)
{
runCommand("timidity", [inFile, "-Ow", "-o", outFile], callback, errorCallback, (data, child) =>
{
if(data.toString().indexOf("Not a MIDI file!") != -1) child.failed = true;
});
}
// convert midi to lilypond
function midi2ly(inFile, outFile, callback, errorCallback)
{
runCommand("which", ["midi2ly"], undefined, errorCallback, (path, child) => {
runCommand("python2.6", [path.toString().trim(), "-i", "header.ly", inFile, "-o", outFile], callback, errorCallback);
}, errorCallback);
}
// render sheet music png and pdf with lilypond
// also use to output midi
function convertLilyPond(inFile, outFile, callback, errorCallback)
{
runCommand("lilypond", ["-dsafe", "-fpdf", "-fpng", "-o", `${trimFileExtension(outFile)}`, inFile], () => setTimeout(() => {
const path = outFile.replace(/[^\/]*$/, "");
getPngFiles(path, (files) => {
runCommand("mogrify", ["-trim"].concat(files), () => setTimeout(callback, config.delay), errorCallback);
});
}, config.delay), errorCallback);
}
/* BOT UTILITY FUNCTIONS */
// post server count and stuff to discordbots.org
function postStats()
{
// ignore for test bot
if(!config.testing) snekfetch.post(`https://discordbots.org/api/bots/${client.user.id}/stats`)
.set("Authorization", config.discordBotsToken)
.send({ server_count: client.guilds.size })
.then(() => console.log("Updated discordbots.org stats."))
.catch(err => console.error(`Error updating stats: ${err.body}`));
}
// take TUNEBOT code and convert it to LILYPOND code and then save the lilypond scratch file
function saveLilyPondFile(code, user, guild, callback, errorCallback)
{
if(code)
{
if(guild)
{
getGuildScratchFile(guild, "ly", (file) => {
fs.writeFile(file, tuneBotExpression2LilyPondScore(code), "utf8", (error) => {
if(error) errorCallback(error);
else callback(errorCallback);
});
});
}
else
{
getUserScratchFile(user, "ly", (file) => {
fs.writeFile(file, tuneBotExpression2LilyPondScore(code), "utf8", (error) => {
if(error) errorCallback(error);
else callback(errorCallback);
});
});
}
}
else callback();
}
// download the scratch midi file from the attachment url
function saveScratchMidi(attachment, user, guild, callback, errorCallback)
{
if(guild)
{
getGuildScratchFile(guild, "midi", (file) => {
downloadFile(attachment.url, file, callback, errorCallback);
});
}
else
{
getUserScratchFile(user, "midi", (file) => {
downloadFile(attachment.url, file, callback, errorCallback);
});
}
}
// download the scratch lilypond file from the attachment url
function saveAttachedLilyPondFile(attachment, user, guild, callback, errorCallback)
{
if(guild)
{
getGuildScratchFile(guild, "ly", (file) => {
downloadFile(attachment.url, file, callback, errorCallback);
});
}
else
{
getUserScratchFile(user, "ly", (file) => {
downloadFile(attachment.url, file, callback, errorCallback);
});
}
}
// convert a scratch midi to lilypond file
function convertScratchMidiToLilyPondFile(user, guild, callback, errorCallback)
{
if(guild)
{
getGuildScratchFile(guild, "ly", (lilyFile) => {
getGuildScratchFile(guild, "midi", (midiFile) => {
midi2ly(midiFile, lilyFile, callback, errorCallback);
});
});
}
else
{
getUserScratchFile(user, "ly", (lilyFile) => {
getUserScratchFile(user, "midi", (midiFile) => {
midi2ly(midiFile, lilyFile, callback, errorCallback);
});
});
}
}
// render the scratch lilypond file to the scratch midi file with lilypond
function convertToScratchMidi(user, guild, callback, errorCallback)
{
if(guild)
{
getGuildScratchFile(guild, "ly", (lilyFile) => {
getGuildScratchFile(guild, "png", (imageFile) => {
convertLilyPond(lilyFile, imageFile, callback, errorCallback);
});
});
}
else
{
getUserScratchFile(user, "ly", (lilyFile) => {
getUserScratchFile(user, "png", (imageFile) => {
convertLilyPond(lilyFile, imageFile, callback, errorCallback);
});
});
}
}
// render the scratch midi file to the scratch wav file with timidity
function renderScratchMidi(user, guild, callback, errorCallback)
{
if(guild)
{
getGuildScratchFile(guild, "midi", (midiFile) => {
getGuildScratchFile(guild, "wav", (waveFile) => {
renderMidi(midiFile, waveFile, callback, errorCallback);
});
});
}
else
{
getUserScratchFile(user, "midi", (midiFile) => {
getUserScratchFile(user, "wav", (waveFile) => {
renderMidi(midiFile, waveFile, callback, errorCallback);
});
});
}
}
// render the scratch lilypond file to scratch sheet music file with lilypond
function renderScratchSheetMusic(user, guild, callback, errorCallback)
{
if(guild)
{
getGuildPngFiles(guild, (files) => removeFiles(files, () => {
getGuildScratchFile(guild, "ly", (lilyFile) => {
getGuildScratchFile(guild, "png", (imageFile) => {
convertLilyPond(lilyFile, imageFile, callback, errorCallback);
});
});
}));
}
else
{
getUserPngFiles(user, (files) => removeFiles(files, () => {
getUserScratchFile(user, "ly", (lilyFile) => {
getUserScratchFile(user, "png", (imageFile) => {
convertLilyPond(lilyFile, imageFile, callback, errorCallback);
});
});
}));
}
}
// download a file from a url
function downloadFile(url, path, callback, errorCallback)
{
const file = fs.createWriteStream(path);
const request = https.get(url, (response) => {
response.pipe(file);
file.on("finish", () => {
file.close(() => {
callback(errorCallback);
});
});
}).on("error", (error) => {
fs.unlink(path);
if(errorCallback) errorCallback(error.message);
});
}
// does this filename have any of these extensions?
function hasExtension(filename, extensions)
{
return extensions.indexOf(getFileExtension(filename)) != -1;
}
// get the file extension of a filename
function getFileExtension(filename)
{
const re = /(?:\.([^.]+))?$/;
return re.exec(filename)[1];
}
// trim the file extension off a filename
function trimFileExtension(filename)
{
return filename.replace(/\.[^/.]+$/, "");
}
// get all of the png files in a scratch directory
function getPngFiles(scratchPath, callback)
{
// the list of scratch png files
const ls = [];
// add all of them to the list
// and call callback when the list is populated
forEachPng(scratchPath, (file) => ls.push(file), () => callback(ls));
}
// get a list of png files in a user scratch directory
function getUserPngFiles(user, callback)
{
const scratchPath = getUserScratchPath(user);
getPngFiles(scratchPath, callback);
}
// get a list of png files in a guild scratch directory
function getGuildPngFiles(guild, callback)
{
const scratchPath = getGuildScratchPath(guild);
getPngFiles(scratchPath, callback);
}
// do something for each png file in a scratch directory
// call callback after done f for all
function forEachPng(scratchPath, f, endCallback)
{
// do f if file exists
function doIfExists(path, f, cont, endCallback)
{
fs.access(path, fs.constants.R_OK, (error) => {
// if it exists
if(!error)
{
// do the thing for it
f(path);
// and continuation function
if(cont) cont();
}
// call this when the chain is finished
else if(endCallback) endCallback();
});
}
// the file of a single page output
const singleFile = `${scratchPath}/${config.scratchFileName}.png`;
doIfExists(singleFile, f);
// get a page file from the page number
function getPageFile(i)
{
return `${scratchPath}/${config.scratchFileName}-page${i}.png`;
}
// go through possible multipage outputs
function doPageFile(i)
{
const pageFile = getPageFile(i);
doIfExists(pageFile, f, () => {
doPageFile(i + 1);
}, endCallback);
}
doPageFile(1);
}
// do something fro each png in a user scratch directory
function forEachUserPng(user, f, callback)
{
const scratchPath = getUserScratchPath(user);
forEachPng(scratchPath, f, callback);
}
// do something fro each png in a guild scratch directory
function forEachGuildPng(guild, f, callback)
{
const scratchPath = getGuildScratchPath(guild);
forEachPng(scratchPath, f, callback);
}
// get the scratch directory for a user
function getUserScratchPath(user)
{
return `${config.scratchDirectory}/user_${user.id}`;
}
// get the scratch directory for a guild
function getGuildScratchPath(guild)
{
return `${config.scratchDirectory}/guild_${guild.id}`;
}
// get the scratch file of an extension for a user
function getUserScratchFile(user, extension, callback)
{
const path = getUserScratchPath(user);
assertPath(path, () => {
callback(`${path}/${config.scratchFileName}.${extension}`);
});
}
// get the scratch file of an extension for a guild
function getGuildScratchFile(guild, extension, callback)
{
const path = getGuildScratchPath(guild);
assertPath(path, () => {
callback(`${path}/${config.scratchFileName}.${extension}`);
});
}
// get the voice connection (if connected) of a guild
function getVoiceConnection(guild)
{
return client.voiceConnections.filter((connection) => {
return guild.id === connection.channel.guild.id;
}).first();
}
// is the bot playing in this guild?
function isPlaying(guild)
{
return playingStatus[guild.id];
}
// id like play sound and stop sound to be CHANNEL dependant, not guild
// play a sound file in a guild in response to message
function playSound(file, guild)
{
const voiceConnection = getVoiceConnection(guild);
dispatchers[guild.id] = voiceConnection.playFile(file);
playingStatus[guild.id] = true;
dispatchers[guild.id].on("end", () => {
stopSound(guild);
});
dispatchers[guild.id].on("error", error => {
console.log(`\t->Error playing file:\n${error}`);
});
}
// stop playing in a guild if it is
// return false if wasn't playing
function stopSound(guild)
{
if(!playingStatus[guild.id]) return false;
dispatchers[guild.id].end();
playingStatus[guild.id] = false;
return true;
}
// reset the auto leave timer for this guild because it was used
function voiceEvent(guild)
{
clearTimer(guild);
timers[guild.id] = setTimeout(() => {
const voiceConnection = getVoiceConnection(guild);
if(voiceConnection)
{
voiceConnection.disconnect();
sendBotString("onAutoLeaveVoiceChannel", (msg) => {
const botChannel = getBotChannel(guild);
if(botChannel) botChannel.send(msg);
});
}
}, config.autoLeaveTimout * 1000);
}
// clear the voice auto leave timer for a guild
function clearTimer(guild)
{
if(timers[guild.id]) clearTimeout(timers[guild.id]);
}
// get the designated bot channel for the guild
// for now just the first channel with the name specified in the config
function getBotChannel(guild)
{
return guild.channels.filter((channel) => {
return channel.name === config.botChannel;
}).first();
}
// send discord messages safely
// and properly split up messages longer than _limit_ characters
// callback is the send function for the first chunk
// tail is for the rest
function safeSend(msg, callback, callbackTail, chunkDelimiter="\n", charLimit=1800, doneCallback)
{
if(!msg.trim().length)
{
if(doneCallback) doneCallback();
return;
}
var first = msg;
var rest = "";
// make this safer so it aborts if something can't be split small enough
while(first.length > charLimit)
{
if(first.indexOf(chunkDelimiter) == -1)
{
console.log("\t-> Can't split message into small enough pieces:");
console.log(`{${first}}\n`);
console.log("\t<-!!");
return;
}
rest = first.split(chunkDelimiter).slice(-1).concat([rest]).join(chunkDelimiter);
first = first.split(chunkDelimiter).slice(0, -1).join(chunkDelimiter);
}
callback(first);
safeSend(rest, callbackTail || callback, callbackTail || callback, chunkDelimiter, charLimit, doneCallback);
}
// send a bot string from config file
// with optional stuff after it (arg)
function sendBotString(string, headSendFunction, tailSendFunction, arg="", chunkDelimiter, charLimit, doneCallback)
{
const stringObj = config.botStrings[string];
const msg = stringObj.string + arg;
if(stringObj.enabled) safeSend(msg, headSendFunction, tailSendFunction, chunkDelimiter, charLimit, doneCallback);
}
// reply to a message with msg
// mentions the user unless its private
function reply(message, msg, options)
{
if(config.replyMention && message.guild) return message.reply(msg, options);
else return message.channel.send(msg, options);
}
/* BOT SUBCOMMANDS */
// send a file in response to message
function doSend(file, message, callback)
{
doSends([file], message, callback);
}
// send as many files as you like in response to a message
function doSends(files, message, callback, first=true)
{
// send 10 at a time
if(files.length)
{
// 10 is max discord file send
const filesHead = files.slice(0, 10);
const filesRest = files.slice(10);
if(first)
{
sendBotString("onSendFile", (msg) => {
reply(message, msg, {
files: filesHead
}).then(() => doSends(filesRest, message, callback, false)).catch(console.error);
});
}
else
{
message.channel.send("", {
files: filesHead
}).then(() => doSends(filesRest, message, callback, false)).catch(console.error);
}
}
else callback();
// no more renaming, its messy
/* fs.access(file, fs.constants.R_OK, (error) => {
if(error)
{
console.log(error);
sendBotString("onSendFail", (msg) => reply(message, msg));
}
else
{
const movedFile = file.replace(/(.*)\/.*(\..*$)/, "$1/" + config.scratchFileName + "$2");
fs.rename(file, movedFile, () => {
sendBotString("onSendFile", (msg) => {
reply(message, msg, {
files: [movedFile]
}).then(() => {
fs.rename(movedFile, file, callback);
}).catch(console.error);
});
});
}
});*/
}
// subcommand to post the png sheet music scratch file
function giveSheets(message, callback)
{
// send all the generated png files
if(message.guild) getGuildPngFiles(message.guild, (files) => doSends(files, message, callback));
else getUserPngFiles(message.author, (files) => doSends(files, message, callback));
}