-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathapp.js
295 lines (275 loc) · 11.2 KB
/
app.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
const Discord = require("discord.js");
const { promisify } = require("util");
const readdir = promisify(require("fs").readdir);
const Enmap = require("enmap");
const EnmapLevel = require("enmap-level");
const client = new Discord.Client();
const db = require('quick.db')
client.config = require("./config.js");
client.logger = require("./util/Logger.js");
require("./modules/functions.js")(client);
client.commands = new Enmap();
client.aliases = new Enmap();
client.settings = new Enmap({provider: new EnmapLevel({name: "settings"})});
const YouTube = require('simple-youtube-api');
const ytdl = require('ytdl-core');
const youtube = new YouTube("Your Youtube Api Key");
const queue = new Map();
var servers = {};
client.on("message", async message => {
// This code has been registered by 『RyansHDs』#4461
// All this code was a modified version of original one with full fixes.
// Thank you for using my code.
const settings = message.settings = client.getGuildSettings(message.guild);
var prefix = settings.prefix
var args = message.content.substring(prefix.length).split(" ");
if (!message.content.startsWith(prefix)) return;
var searchString = args.slice(1).join(' ');
var url = args[1] ? args[1].replace(/<(.+)>/g, '$1') : '';
var serverQueue = queue.get(message.guild.id);
switch (args[0].toLowerCase()) {
case "play":
var voiceChannel = message.member.voiceChannel;
if (!voiceChannel) return message.channel.send('You need to be in voice channel first!');
var permissions = voiceChannel.permissionsFor(message.client.user);
if (!permissions.has('CONNECT')) {
const errorconnect = new Discord.RichEmbed()
.setColor(`RED`)
.setFooter(`This message will be deleted in 10 seconds..`)
.setDescription(`I couldn't connect into your voice channel, Missing **CONNECT** Permission.`)
return message.channel.send(errorconnect).then(message => {
message.delete(10000)
})
}
if (!permissions.has('SPEAK')) {
const errorspeak = new Discord.RichEmbed()
.setColor(`RED`)
.setFooter(`This message will be deleted in 10 seconds..`)
.setDescription(`I couldn't speak at your voice channel, Missing **SPEAK** Permission.`)
return message.channel.send(errorspeak).then(message => {
message.delete(10000)
})
}
if (url.match(/^https?:\/\/(www.youtube.com|youtube.com)\/playlist(.*)$/)) {
var playlist = await youtube.getPlaylist(url);
var videos = await playlist.getVideos();
for (const video of Object.values(videos)) {
var 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
}
const playlistembed = new Discord.RichEmbed()
.setColor(`GREEN`)
.setDescription(`✅ ${playlist.title} has been added to the queue!`)
return message.channel.send(playlistembed);
} else {
try {
var video = await youtube.getVideo(url);
} catch (error) {
try {
var videos = await youtube.searchVideos(searchString, 9);
var index = 0;
let selectionemb = new Discord.RichEmbed()
.setTitle(`<:youtube:469420220688367616> Youtube video selection.`)
.setDescription(`${videos.map(video2 => `**${++index} -** [${video2.title}](${video2.url})`).join('\n')}`)
.setFooter('🔎 Please provide a number to select one of the search results ranging from 1-9.')
.setColor('#0fe709')
message.channel.send(selectionemb).then(message => {
message.delete(11000)
})
// eslint-disable-next-line max-depth
try {
var response = await message.channel.awaitMessages(message2 => message2.content > 0 && message2.content < 10, {
maxMatches: 1,
time: 10000,
errors: ['time']
});
} catch (err) {
console.error(err);
let noinvemb = new Discord.RichEmbed()
.setDescription('No or invalid value entered, cancelling video selection.')
.setColor('#e41016')
return message.channel.send(noinvemb).then(message => {
message.delete(5000)
})
}
var videoIndex = parseInt(response.first().content);
var video = await youtube.getVideoByID(videos[videoIndex - 1].id);
} catch (err) {
console.error(err);
return message.channel.send('Can\'t find the video');
}
}
return handleVideo(video, message, voiceChannel);
}
break;
case "skip":
if (!message.member.voiceChannel) return message.channel.send('You are not in a voice channel!');
if (!serverQueue) return message.channel.send('There is nothing playing.');
serverQueue.connection.dispatcher.end('Skip command has been used!');
message.channel.send(':ok_hand: Skipped!')
return undefined;
break;
case "stop":
if (!message.member.voiceChannel) return message.channel.send('You are not in a voice channel!');
if (!serverQueue) return message.channel.send('There is nothing playing right now');
serverQueue.songs = [];
serverQueue.connection.dispatcher.end('Stop command has been used!');
message.channel.send(':ok_hand: Stopped!')
return undefined;
break;
case "volume":
if (!message.member.voiceChannel) return message.channel.send('You are not in a voice channel.');
if (!serverQueue) return message.channel.send('There is nothing playing.');
let currentvolumeemb = new Discord.RichEmbed()
.setDescription(`The current volume is: **${serverQueue.volume}**`)
.setColor('#27ce12')
if (!args[1]) return message.channel.send(currentvolumeemb);
serverQueue.volume = args[1];
serverQueue.connection.dispatcher.setVolumeLogarithmic(args[1] / 5);
let setvolumeemb = new Discord.RichEmbed()
.setDescription(`I set the volume to: **${args[1]}**`)
.setColor('#27ce12')
return message.channel.send(setvolumeemb);
break;
case "np":
if (!serverQueue) return message.channel.send('There is nothing playing.');
let nowplayingemb = new Discord.RichEmbed()
.setDescription(`🎶 Now playing: **${serverQueue.songs[0].title}**`)
.setColor(`GREEN`)
return message.channel.send(nowplayingemb);
break;
case "queue":
if (!serverQueue) return message.channel.send('No music playing right now.');
let queueemb = new Discord.RichEmbed()
.setAuthor(`${message.guild.name} Queue list `)
.setDescription(`${serverQueue.songs.map(song => `**•** [${song.title}](https://www.youtube.com/watch?v=${song.id}})`).join('\n')}\n\n🎶 **Now playing:** ${serverQueue.songs[0].title}`)
.setColor(`GREEN`)
return message.channel.send(queueemb)
break;
case "pause":
if (serverQueue && serverQueue.playing) {
serverQueue.playing = false;
serverQueue.connection.dispatcher.pause();
return message.channel.send('⏸ Music paused');
}
return message.channel.send('There is nothing playing.');
break;
case "resume":
if (serverQueue && !serverQueue.playing) {
serverQueue.playing = true;
serverQueue.connection.dispatcher.resume();
return message.channel.send('▶ Music resumed');
}
return message.channel.send('There is nothing playing.');
return undefined;
break;
}
async function handleVideo(video, message, voiceChannel, playlist = false) {
var serverQueue = queue.get(message.guild.id);
console.log(video);
var song = {
id: video.id,
title: video.title,
url: `https://www.youtube.com/watch?v=${video.id}`,
channel: video.channel.title,
durationm: video.duration.minutes,
durations: video.duration.seconds,
durationh: video.duration.hours,
publishedAt: video.publishedAt,
};
if (!serverQueue) {
var queueConstruct = {
textChannel: message.channel,
voiceChannel: voiceChannel,
connection: null,
songs: [],
volume: 5,
playing: true
};
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) {
let vcerr = client.channels.get('468793396970913812')
vcerr.send(`I could not join the voice channel: ${error}`);
queue.delete(message.guild.id);
return message.channel.send(`I could not join the voice channel: ${error}`);
}
} else {
serverQueue.songs.push(song);
console.log(serverQueue.songs);
if (playlist) return undefined;
let queueemb = new Discord.RichEmbed()
.setAuthor(`Added to ${message.guild.name} Queue list`, message.author.displayAvatarURL)
.setColor(`#1ace18`)
.addField(`Publisher:`, `${song.channel}`, true)
.addField(`Video ID:`, song.id, true)
.setFooter(`Video Published At ${song.publishedAt}`)
.addField(`Duration:`, `**${song.durationh}** hours, **${song.durationm}** minutes, **${song.durations}** seconds`, true)
.setThumbnail(`https://i.ytimg.com/vi/${song.id}/sddefault.jpg`)
.setDescription(`[${song.title}](https://www.youtube.com/watch?v=${song.id}})`)
.setColor(`GREEN`)
return message.channel.send(queueemb).then(msg => {
message.delete(10000)
})
}
return undefined;
}
function play(guild, song) {
var serverQueue = queue.get(guild.id);
if (!song) {
serverQueue.voiceChannel.leave();
queue.delete(guild.id);
return;
}
console.log(serverQueue.songs);
const dispatcher = serverQueue.connection.playStream(ytdl(song.url))
.on('end', reason => {
if (reason === 'Stream is not generating quickly enough.') console.log('Song ended.');
else console.log(reason);
serverQueue.songs.shift();
play(guild, serverQueue.songs[0]);
})
.on('error', error => console.error(error));
dispatcher.setVolumeLogarithmic(serverQueue.volume / 5);
let playingemb = new Discord.RichEmbed()
.setTitle(`<:youtube:469420220688367616> Now playing`)
.setColor(`GREEN`)
.addField(`Publisher:`, `${song.channel}`, true)
.addField(`Video ID:`, song.id, true)
.setFooter(`Video Published At ${song.publishedAt}`)
.addField(`Duration:`, `**${song.durationh}** hours, **${song.durationm}** minutes, **${song.durations}** seconds`, true)
.setThumbnail(`https://i.ytimg.com/vi/${song.id}/sddefault.jpg`)
.setDescription(`[${song.title}](https://www.youtube.com/watch?v=${song.id}})`)
.setTimestamp()
serverQueue.textChannel.send(playingemb);
}
});
const init = async () => {
const cmdFiles = await readdir("./commands/");
client.logger.log(`Loading a total of ${cmdFiles.length} commands.`);
cmdFiles.forEach(f => {
if (!f.endsWith(".js")) return;
const response = client.loadCommand(f);
if (response) console.log(response);
});
const evtFiles = await readdir("./events/");
client.logger.log(`Loading a total of ${evtFiles.length} events.`);
evtFiles.forEach(file => {
const eventName = file.split(".")[0];
const event = require(`./events/${file}`);
client.on(eventName, event.bind(null, client));
delete require.cache[require.resolve(`./events/${file}`)];
});
client.levelCache = {};
for (let i = 0; i < client.config.permLevels.length; i++) {
const thisLevel = client.config.permLevels[i];
client.levelCache[thisLevel.name] = thisLevel.level;
}
// Here we login the client.
client.login(client.config.token);
};
init();