-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
511 lines (480 loc) Β· 18.8 KB
/
server.js
File metadata and controls
511 lines (480 loc) Β· 18.8 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
const { Client, Util, MessageEmbed } = require("discord.js");
const YouTube = require("simple-youtube-api");
const ytdl = require("ytdl-core");
require("dotenv").config();
require("./server.js");
const bot = new Client({
disableMentions: "all"
});
const PREFIX = process.env.PREFIX;
const youtube = new YouTube(process.env.YTAPI_KEY);
const queue = new Map();
bot.on("warn", console.warn);
bot.on("error", console.error);
bot.on("ready", () => console.log(`[READY] ${bot.user.tag} has been successfully booted up!`));
bot.on("shardDisconnect", (event, id) => console.log(`[SHARD] Shard ${id} disconnected (${event.code}) ${event}, trying to reconnect...`));
bot.on("shardReconnecting", (id) => console.log(`[SHARD] Shard ${id} reconnecting...`));
// prevent force disconnect affecting to guild queue
bot.on("voiceStateUpdate", (mold, mnew) => {
if( !mold.channelID) return;
if( !mnew.channelID && bot.user.id == mold.id ) {
const serverQueue = queue.get(mold.guild.id);
if(serverQueue) queue.delete(mold.guild.id);
} ;
})
bot.on("message", async (message) => { // eslint-disable-line
if (message.author.bot) return;
if (!message.content.startsWith(PREFIX)) return;
const args = message.content.split(" ");
const searchString = args.slice(1).join(" ");
const url = args[1] ? args[1].replace(/<(.+)>/g, "$1") : "";
const serverQueue = queue.get(message.guild.id);
let command = message.content.toLowerCase().split(" ")[0];
command = command.slice(PREFIX.length);
if (command === "help" || command === "cmd") {
const helpembed = new MessageEmbed()
.setColor("BLUE")
.setAuthor(bot.user.tag, bot.user.displayAvatarURL())
.setDescription(`
__**Command list**__
> \`play\` > **\`play [title/url]\`**
> \`search\` > **\`search [title]\`**
> \`skip\`, \`stop\`, \`pause\`, \`resume\`
> \`nowplaying\`, \`queue\`, \`volume\``)
.setFooter("Β©οΈ 2020 Zhycorp Nation", "https://api.zhycorp.xyz/assets/images/icon.jpg");
message.channel.send(helpembed);
}
if (command === "play" || command === "p") {
const voiceChannel = message.member.voice.channel;
if (!voiceChannel) return message.channel.send({
embed: {
color: "RED",
description: "I'm sorry, but you need to be in a voice channel to play a music!"
}
});
const permissions = voiceChannel.permissionsFor(message.client.user);
if (!permissions.has("CONNECT")) {
return message.channel.send({
embed: {
color: "RED",
description: "Sorry, but I need a **`CONNECT`** permission to proceed!"
}
});
}
if (!permissions.has("SPEAK")) {
return message.channel.send({
embed: {
color: "RED",
description: "Sorry, but I need a **`SPEAK`** permission to proceed!"
}
});
}
if (!url || !searchString) return message.channel.send({
embed: {
color: "RED",
description: "Please input link/title to play music"
}
});
if (url.match(/^https?:\/\/(www.youtube.com|youtube.com)\/playlist(.*)$/)) {
const playlist = await youtube.getPlaylist(url);
const videos = await playlist.getVideos();
for (const video of Object.values(videos)) {
const video2 = await youtube.getVideoByID(video.id); // eslint-disable-line no-await-in-loop
await handleVideo(video2, message, voiceChannel, true); // eslint-disable-line no-await-in-loop
}
return message.channel.send({
embed: {
color: "GREEN",
description: `β
**|** Playlist: **\`${playlist.title}\`** has been added to the queue`
}
});
} else {
try {
var video = await youtube.getVideo(url);
} catch (error) {
try {
var videos = await youtube.searchVideos(searchString, 10);
var video = await youtube.getVideoByID(videos[0].id);
if (!video) return message.channel.send({
embed: {
color: "RED",
description: "π **|** I could not obtain any search results"
}
});
} catch (err) {
console.error(err);
return message.channel.send({
embed: {
color: "RED",
description: "π **|** I could not obtain any search results"
}
});
}
}
return handleVideo(video, message, voiceChannel);
}
}
if (command === "search" || command === "sc") {
const voiceChannel = message.member.voice.channel;
if (!voiceChannel) return message.channel.send({
embed: {
color: "RED",
description: "I'm sorry, but you need to be in a voice channel to play a music!"
}
});
const permissions = voiceChannel.permissionsFor(message.client.user);
if (!permissions.has("CONNECT")) {
return message.channel.send({
embed: {
color: "RED",
description: "Sorry, but I need a **`CONNECT`** permission to proceed!"
}
});
}
if (!permissions.has("SPEAK")) {
return message.channel.send({
embed: {
color: "RED",
description: "Sorry, but I need a **`SPEAK`** permission to proceed!"
}
});
}
if (!url || !searchString) return message.channel.send({
embed: {
color: "RED",
description: "Please input link/title to search music"
}
});
if (url.match(/^https?:\/\/(www.youtube.com|youtube.com)\/playlist(.*)$/)) {
const playlist = await youtube.getPlaylist(url);
const videos = await playlist.getVideos();
for (const video of Object.values(videos)) {
const video2 = await youtube.getVideoByID(video.id); // eslint-disable-line no-await-in-loop
await handleVideo(video2, message, voiceChannel, true); // eslint-disable-line no-await-in-loop
}
return message.channel.send({
embed: {
color: "GREEN",
description: `β
**|** Playlist: **\`${playlist.title}\`** has been added to the queue`
}
});
} else {
try {
var video = await youtube.getVideo(url);
} catch (error) {
try {
var videos = await youtube.searchVideos(searchString, 10);
let index = 0;
let embedPlay = new MessageEmbed()
.setColor("BLUE")
.setAuthor("Search results", message.author.displayAvatarURL())
.setDescription(`${videos.map(video2 => `**\`${++index}\` |** ${video2.title}`).join("\n")}`)
.setFooter("Please choose one of the following 10 results, this embed will auto-deleted in 15 seconds");
// eslint-disable-next-line max-depth
message.channel.send(embedPlay).then(m => m.delete({
timeout: 15000
}))
try {
var response = await message.channel.awaitMessages(message2 => message2.content > 0 && message2.content < 11, {
max: 1,
time: 15000,
errors: ["time"]
});
} catch (err) {
console.error(err);
return message.channel.send({
embed: {
color: "RED",
description: "The song selection time has expired in 15 seconds, the request has been canceled."
}
});
}
const videoIndex = parseInt(response.first().content);
var video = await youtube.getVideoByID(videos[videoIndex - 1].id);
} catch (err) {
console.error(err);
return message.channel.send({
embed: {
color: "RED",
description: "π **|** I could not obtain any search results"
}
});
}
}
response.delete();
return handleVideo(video, message, voiceChannel);
}
} else if (command === "skip") {
if (!message.member.voice.channel) return message.channel.send({
embed: {
color: "RED",
description: "I'm sorry, but you need to be in a voice channel to skip a music!"
}
});
if (!serverQueue) return message.channel.send({
embed: {
color: "RED",
description: "There is nothing playing that I could skip for you"
}
});
serverQueue.connection.dispatcher.end("[runCmd] Skip command has been used");
return message.channel.send({
embed: {
color: "GREEN",
description: "βοΈ **|** I skipped the song for you"
}
});
} else if (command === "stop") {
if (!message.member.voice.channel) return message.channel.send({
embed: {
color: "RED",
description: "I'm sorry but you need to be in a voice channel to play music!"
}
});
if (!serverQueue) return message.channel.send({
embed: {
color: "RED",
description: "There is nothing playing that I could stop for you"
}
});
serverQueue.songs = [];
serverQueue.connection.dispatcher.end("[runCmd] Stop command has been used");
return message.channel.send({
embed: {
color: "GREEN",
description: "βΉοΈ **|** Deleting queues and leaving voice channel..."
}
});
} else if (command === "volume" || command === "vol") {
if (!message.member.voice.channel) return message.channel.send({
embed: {
color: "RED",
description: "I'm sorry, but you need to be in a voice channel to set a volume!"
}
});
if (!serverQueue) return message.channel.send({
embed: {
color: "RED",
description: "There is nothing playing"
}
});
if (!args[1]) return message.channel.send({
embed: {
color: "BLUE",
description: `The current volume is: **\`${serverQueue.volume}%\`**`
}
});
if (isNaN(args[1]) || args[1] > 100) return message.channel.send({
embed: {
color: "RED",
description: "Volume only can be set in a range of **\`1\`** - **\`100\`**"
}
});
serverQueue.volume = args[1];
serverQueue.connection.dispatcher.setVolume(args[1] / 100);
return message.channel.send({
embed: {
color: "GREEN",
description: `I set the volume to: **\`${args[1]}%\`**`
}
});
} else if (command === "nowplaying" || command === "np") {
if (!serverQueue) return message.channel.send({
embed: {
color: "RED",
description: "There is nothing playing"
}
});
return message.channel.send({
embed: {
color: "BLUE",
description: `πΆ **|** Now Playing: **\`${serverQueue.songs[0].title}\`**`
}
});
} else if (command === "queue" || command === "q") {
let songsss = serverQueue.songs.slice(1)
let number = songsss.map(
(x, i) => `${i + 1} - ${x.title}`
);
number = chunk(number, 5);
let index = 0;
if (!serverQueue) return message.channel.send({
embed: {
color: "RED",
description: "There is nothing playing"
}
});
let embedQueue = new MessageEmbed()
.setColor("BLUE")
.setAuthor("Song queue", message.author.displayAvatarURL())
.setDescription(number[index].join("\n"))
.setFooter(`β’ Now Playing: ${serverQueue.songs[0].title} | Page ${index + 1} of ${number.length}`);
const m = await message.channel.send(embedQueue);
if (number.length !== 1) {
await m.react("β¬
");
await m.react("π");
await m.react("β‘");
async function awaitReaction() {
const filter = (rect, usr) => ["β¬
", "π", "β‘"].includes(rect.emoji.name) &&
usr.id === message.author.id;
const response = await m.awaitReactions(filter, {
max: 1,
time: 30000
});
if (!response.size) {
return undefined;
}
const emoji = response.first().emoji.name;
if (emoji === "β¬
") index--;
if (emoji === "π") m.delete();
if (emoji === "β‘") index++;
if (emoji !== "π") {
index = ((index % number.length) + number.length) % number.length;
embedQueue.setDescription(number[index].join("\n"));
embedQueue.setFooter(`Page ${index + 1} of ${number.length}`);
await m.edit(embedQueue);
return awaitReaction();
}
}
return awaitReaction();
}
} else if (command === "pause") {
if (serverQueue && serverQueue.playing) {
serverQueue.playing = false;
serverQueue.connection.dispatcher.pause();
return message.channel.send({
embed: {
color: "GREEN",
description: "βΈ **|** Paused the music for you"
}
});
}
return message.channel.send({
embed: {
color: "RED",
description: "There is nothing playing"
}
});
} else if (command === "resume") {
if (serverQueue && !serverQueue.playing) {
serverQueue.playing = true;
serverQueue.connection.dispatcher.resume();
return message.channel.send({
embed: {
color: "GREEN",
description: "βΆ **|** Resumed the music for you"
}
});
}
return message.channel.send({
embed: {
color: "RED",
description: "There is nothing playing"
}
});
} else if (command === "loop") {
if (serverQueue) {
serverQueue.loop = !serverQueue.loop;
return message.channel.send({
embed: {
color: "GREEN",
description: `π **|** Loop is **\`${serverQueue.loop === true ? "enabled" : "disabled"}\`**`
}
});
};
return message.channel.send({
embed: {
color: "RED",
description: "There is nothing playing"
}
});
}
});
async function handleVideo(video, message, voiceChannel, playlist = false) {
const serverQueue = queue.get(message.guild.id);
const song = {
id: video.id,
title: Util.escapeMarkdown(video.title),
url: `https://www.youtube.com/watch?v=${video.id}`
};
if (!serverQueue) {
const queueConstruct = {
textChannel: message.channel,
voiceChannel: voiceChannel,
connection: null,
songs: [],
volume: 100,
playing: true,
loop: false
};
queue.set(message.guild.id, queueConstruct);
queueConstruct.songs.push(song);
try {
var connection = await voiceChannel.join();
queueConstruct.connection = connection;
play(message.guild, queueConstruct.songs[0]);
} catch (error) {
console.error(`[ERROR] I could not join the voice channel, because: ${error}`);
queue.delete(message.guild.id);
return message.channel.send({
embed: {
color: "RED",
description: `I could not join the voice channel, because: **\`${error}\`**`
}
});
}
} else {
serverQueue.songs.push(song);
if (playlist) return;
else return message.channel.send({
embed: {
color: "GREEN",
description: `β
**|** **\`${song.title}\`** has been added to the queue`
}
});
}
return;
}
function chunk(array, chunkSize) {
const temp = [];
for (let i = 0; i < array.length; i += chunkSize) {
temp.push(array.slice(i, i + chunkSize));
}
return temp;
}
function play(guild, song) {
const serverQueue = queue.get(guild.id);
if (!song) {
serverQueue.voiceChannel.leave();
return queue.delete(guild.id);
}
const dispatcher = serverQueue.connection.play(ytdl(song.url))
.on("finish", () => {
const shiffed = serverQueue.songs.shift();
if (serverQueue.loop === true) {
serverQueue.songs.push(shiffed);
};
play(guild, serverQueue.songs[0]);
})
.on("error", error => console.error(error));
dispatcher.setVolume(serverQueue.volume / 100);
serverQueue.textChannel.send({
embed: {
color: "BLUE",
description: `πΆ **|** Start Playing: **\`${song.title}\`**`
}
});
}
bot.login(process.env.BOT_TOKEN);
process.on("unhandledRejection", (reason, promise) => {
try {
console.error("Unhandled Rejection at: ", promise, "reason: ", reason.stack || reason);
} catch {
console.error(reason);
}
});
process.on("uncaughtException", err => {
console.error(`Caught exception: ${err}`);
process.exit(1);
});
client.login("NzcwMzM5NjQzNzMyMTMxODcz.X5cIsw.7uVtu7vZXf24KEqtr7P-_cTpYNo")