forked from OKEPlazmA/DripBot2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
music_bot.js
470 lines (414 loc) · 14 KB
/
music_bot.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
const YoutubeDL = require('youtube-dl');
const ytdl = require('ytdl-core');
var YouTube = require('youtube-node');
var config = require('./config.json');
var youTube = new YouTube();
youTube.setKey(config.youtube_api_key);
var volum = 50;
/**
* Takes a discord.js client and turns it into a music bot.
* Thanks to 'derekmartinez18' for helping.
*
* @param {Client} client - The discord.js client.
* @param {object} options - (Optional) Options to configure the music bot. Acceptable options are:
* prefix: The prefix to use for the commands (default '!').
* global: Whether to use a global queue instead of a server-specific queue (default false).
* maxQueueSize: The maximum queue size (default 20).
* anyoneCanSkip: Allow anybody to skip the song.
* clearInvoker: Clear the command message.
* volume: The default volume of the player.
* channel: Name of default voice channel to join.
*/
module.exports = function (client, options) {
// Get all options.
let PREFIX = (options && options.prefix) || '!';
let GLOBAL = (options && options.global) || false;
let MAX_QUEUE_SIZE = (options && options.maxQueueSize) || 20;
let DEFAULT_VOLUME = (options && options.volume) || 50;
let ALLOW_ALL_SKIP = (options && options.anyoneCanSkip) || false;
let CLEAR_INVOKER = (options && options.clearInvoker) || false;
let CHANNEL = (options && options.channel) || false;
// Create an object of queues.
let queues = {};
// Catch message events.
client.on('message', msg => {
if (typeof msg.channel.guild == 'undefined') {
return;
}
if (config.bot_channel.enabled) {
if (msg.channel.name !== config.bot_channel.channel && !serverAdmin(msg)) {
return; //not in proper channel
}
}
const message = msg.content.trim();
// Check if the message is a command.
if (message.toLowerCase().startsWith(PREFIX.toLowerCase())) {
// Get the command and suffix.
const command = message.substring(PREFIX.length).split(/[ \n]/)[0].toLowerCase().trim();
const suffix = message.substring(PREFIX.length + command.length).trim();
// Process the commands.
switch (command) {
case 'play':
return play(msg, suffix);
case 'skip':
return skip(msg, suffix);
case 'queue':
return queue(msg, suffix);
case 'pause':
return pause(msg, suffix);
case 'resume':
return resume(msg, suffix);
case 'volume':
return volume(msg, suffix);
case 'leave':
return leave(msg, suffix);
case 'clearqueue':
return clearqueue(msg, suffix);
}
}
});
/**
* Checks if a user is an admin.
*
* @param {GuildMember} member - The guild member
* @returns {boolean} -
*/
function isAdmin(member) {
return member.hasPermission("ADMINISTRATOR");
}
function serverAdmin(msg) {
if (typeof msg.channel.guild == 'undefined') {
return true; //pm so allow
}
if (!msg.member.hasPermission("ADMINISTRATOR")) {
return false;
} else {
return true;
}
}
/**
* Checks if the user can skip the song.
*
* @param {GuildMember} member - The guild member
* @param {array} queue - The current queue
* @returns {boolean} - If the user can skip
*/
function canSkip(member, queue) {
if (ALLOW_ALL_SKIP) return true;
else if (queue[0].requester === member.id) return true;
else if (isAdmin(member)) return true;
else return false;
}
/**
* Gets the song queue of the server.
*
* @param {integer} server - The server id.
* @returns {object} - The song queue.
*/
function getQueue(server) {
// Check if global queues are enabled.
if (GLOBAL) server = '_'; // Change to global queue.
// Return the queue.
if (!queues[server]) queues[server] = [];
return queues[server];
}
/**
* The command for adding a song to the queue.
*
* @param {Message} msg - Original message.
* @param {string} suffix - Command suffix.
* @returns {<promise>} - The response edit.
*/
function play(msg, suffix) {
// Make sure the user is in a voice channel.
if (!CHANNEL && msg.member.voiceChannel === undefined) return msg.channel.send(wrap('You\'re not in a voice channel.'));
// Make sure the suffix exists.
if (!suffix) return msg.channel.send(wrap('No video specified!'));
// Get the queue.
const queue = getQueue(msg.guild.id);
// Check if the queue has reached its maximum size.
if (queue.length >= MAX_QUEUE_SIZE) {
return msg.channel.send(wrap('Maximum queue size reached!'));
}
// Get the video information.
msg.channel.send(wrap('Searching...')).then(response => {
var searchstring = suffix
if (!suffix.toLowerCase().startsWith('http')) {
searchstring = 'gvsearch1:' + suffix;
}
// YoutubeDL.getInfo(searchstring, ['-q', '--no-warnings', '--force-ipv4'], (err, info) => {
// // Verify the info.
// if (err || info.format_id === undefined || info.format_id.startsWith('0')) {
// return response.edit(wrap('Invalid video!'));
// }
//
// info.requester = msg.author.id;
//
// // Queue the video.
// response.edit(wrap('Queued: ' + info.title)).then(() => {
// queue.push(info);
// // Play if only one element in the queue.
// if (queue.length === 1) executeQueue(msg, queue);
// }).catch(console.log);
// });
youTube.search(suffix, 1, function(error, res) {
if (error) {
msg.channel.send("¯\\_(ツ)_/¯");
}
else {
if (!res || !res.items || res.items.length < 1) {
response.edit(wrap('No results ¯\\_(ツ)_/¯')).then(() => {
});
} else {
var info = new Object();
info.requester = msg.author.id;
info.format_id = res.items[0].id.videoId;
info.title = res.items[0].snippet.title;
info.webpage_url = "https://www.youtube.com/view?v="+info.format_id;
// queue.push(info);
response.edit(wrap('Queued: ' + info.title)).then(() => {
queue.push(info);
// Play if only one element in the queue.
if (queue.length === 1) executeQueue(msg, queue);
}).catch(console.log);
//msg.channel.send("http://www.youtube.com/watch?v=" + info.items[0].id.videoId );
}
}
});
}).catch(console.log);
}
/**
* The command for skipping a song.
*
* @param {Message} msg - Original message.
* @param {string} suffix - Command suffix.
* @returns {<promise>} - The response message.
*/
function skip(msg, suffix) {
// Get the voice connection.
const voiceConnection = client.voiceConnections.find(val => val.channel.guild.id == msg.guild.id);
if (voiceConnection === null) return msg.channel.send(wrap('No music being played.'));
// Get the queue.
const queue = getQueue(msg.guild.id);
if (!canSkip(msg.member, queue)) return msg.channel.send(wrap('You cannot skip this as you didn\'t queue it.')).then((response) => {
response.delete(5000);
});
// Get the number to skip.
let toSkip = 1; // Default 1.
if (!isNaN(suffix) && parseInt(suffix) > 0) {
toSkip = parseInt(suffix);
}
toSkip = Math.min(toSkip, queue.length);
// Skip.
queue.splice(0, toSkip - 1);
// Resume and stop playing.
const dispatcher = voiceConnection.player.dispatcher;
if (voiceConnection.paused) dispatcher.resume();
dispatcher.end();
msg.channel.send(wrap('Skipped ' + toSkip + '!'));
}
/**
* The command for listing the queue.
*
* @param {Message} msg - Original message.
* @param {string} suffix - Command suffix.
*/
function queue(msg, suffix) {
// Get the queue.
const queue = getQueue(msg.guild.id);
// Get the queue text.
const text = queue.map((video, index) => (
(index + 1) + ': ' + video.title
)).join('\n');
// Get the status of the queue.
let queueStatus = 'Stopped';
const voiceConnection = client.voiceConnections.find(val => val.channel.guild.id == msg.guild.id);
if (voiceConnection !== null) {
const dispatcher = voiceConnection.player.dispatcher;
queueStatus = dispatcher.paused ? 'Paused' : 'Playing';
}
// Send the queue and status.
msg.channel.send(wrap('Queue (' + queueStatus + '):\n' + text));
}
/**
* The command for pausing the current song.
*
* @param {Message} msg - Original message.
* @param {string} suffix - Command suffix.
* @returns {<promise>} - The response message.
*/
function pause(msg, suffix) {
// Get the voice connection.
const voiceConnection = client.voiceConnections.find(val => val.channel.guild.id == msg.guild.id);
if (voiceConnection === null) return msg.channel.send(wrap('No music being played.'));
if (!isAdmin(msg.member))
return msg.channel.send(wrap('You are not authorized to use this.'));
// Pause.
msg.channel.send(wrap('Playback paused.'));
const dispatcher = voiceConnection.player.dispatcher;
if (!dispatcher.paused) dispatcher.pause();
}
/**
* The command for leaving the channel and clearing the queue.
*
* @param {Message} msg - Original message.
* @param {string} suffix - Command suffix.
* @returns {<promise>} - The response message.
*/
function leave(msg, suffix) {
if (isAdmin(msg.member)) {
const voiceConnection = client.voiceConnections.find(val => val.channel.guild.id == msg.guild.id);
if (voiceConnection === null) return msg.channel.send(wrap('I\'m not in any channel!.'));
// Clear the queue.
const queue = getQueue(msg.guild.id);
queue.splice(0, queue.length);
// End the stream and disconnect.
voiceConnection.player.dispatcher.end();
voiceConnection.disconnect();
} else {
msg.channel.send(wrap('You don\'t have permission to use that command!'));
}
}
/**
* The command for clearing the song queue.
*
* @param {Message} msg - Original message.
* @param {string} suffix - Command suffix.
*/
function clearqueue(msg, suffix) {
if (isAdmin(msg.member)) {
const queue = getQueue(msg.guild.id);
queue.splice(0, queue.length);
msg.channel.send(wrap('Queue cleared!'));
} else {
msg.channel.send(wrap('You don\'t have permission to use that command!'));
}
}
/**
* The command for resuming the current song.
*
* @param {Message} msg - Original message.
* @param {string} suffix - Command suffix.
* @returns {<promise>} - The response message.
*/
function resume(msg, suffix) {
// Get the voice connection.
const voiceConnection = client.voiceConnections.find(val => val.channel.guild.id == msg.guild.id);
if (voiceConnection === null) return msg.channel.send(wrap('No music being played.'));
if (!isAdmin(msg.member))
return msg.channel.send(wrap('You are not authorized to use this.'));
// Resume.
msg.channel.send(wrap('Playback resumed.'));
const dispatcher = voiceConnection.player.dispatcher;
if (dispatcher.paused) dispatcher.resume();
}
/**
* The command for changing the song volume.
*
* @param {Message} msg - Original message.
* @param {string} suffix - Command suffix.
* @returns {<promise>} - The response message.
*/
function volume(msg, suffix) {
// Get the voice connection.
const voiceConnection = client.voiceConnections.find(val => val.channel.guild.id == msg.guild.id);
if (voiceConnection === null) return msg.channel.send(wrap('No music being played.'));
if (!isAdmin(msg.member))
return msg.channel.send(wrap('You are not authorized to use this.'));
// Get the dispatcher
const dispatcher = voiceConnection.player.dispatcher;
if (suffix > 200 || suffix < 0) return msg.channel.send(wrap('Volume out of range!')).then((response) => {
response.delete(5000);
});
msg.channel.send(wrap("Volume set to " + suffix));
dispatcher.setVolume((suffix/100));
volum = suffix;
}
/**
* Executes the next song in the queue.
*
* @param {Message} msg - Original message.
* @param {object} queue - The song queue for this server.
* @returns {<promise>} - The voice channel.
*/
function executeQueue(msg, queue) {
// If the queue is empty, finish.
if (queue.length === 0) {
msg.channel.send(wrap('Playback finished.'));
// Leave the voice channel.
const voiceConnection = client.voiceConnections.find(val => val.channel.guild.id == msg.guild.id);
if (voiceConnection !== null) return voiceConnection.disconnect();
}
new Promise((resolve, reject) => {
// Join the voice channel if not already in one.
const voiceConnection = client.voiceConnections.find(val => val.channel.guild.id == msg.guild.id);
if (voiceConnection === null) {
if (CHANNEL) {
msg.guild.channels.find('name', CHANNEL).join().then(connection => {
resolve(connection);
}).catch((error) => {
console.log(error);
});
// Check if the user is in a voice channel.
} else if (msg.member.voiceChannel) {
msg.member.voiceChannel.join().then(connection => {
resolve(connection);
}).catch((error) => {
console.log(error);
});
} else {
// Otherwise, clear the queue and do nothing.
queue.splice(0, queue.length);
reject();
}
} else {
resolve(voiceConnection);
}
}).then(connection => {
// Get the first item in the queue.
const video = queue[0];
console.log(video.webpage_url);
// Play the video.
msg.channel.send(wrap('Now Playing: ' + video.title)).then(() => {
let dispatcher = connection.playStream(ytdl(video.webpage_url, {filter: 'audioonly'}), {seek: 0, volume: (DEFAULT_VOLUME/100)});
dispatcher.setVolume((volum/100));
connection.on('error', (error) => {
// Skip to the next song.
console.log(error);
queue.shift();
executeQueue(msg, queue);
});
dispatcher.on('error', (error) => {
// Skip to the next song.
console.log(error);
queue.shift();
executeQueue(msg, queue);
});
dispatcher.on('end', () => {
// Wait a second.
setTimeout(() => {
if (queue.length > 0) {
// Remove the song from the queue.
queue.shift();
// Play the next song in the queue.
executeQueue(msg, queue);
}
}, 1000);
});
}).catch((error) => {
console.log(error);
});
}).catch((error) => {
console.log(error);
});
}
}
/**
* Wrap text in a code block and escape grave characters.
*
* @param {string} text - The input text.
* @returns {string} - The wrapped text.
*/
function wrap(text) {
return '```\n' + text.replace(/`/g, '`' + String.fromCharCode(8203)) + '\n```';
}