-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbot.js
485 lines (431 loc) · 13.5 KB
/
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
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
const Discord = require("discord.js");
const fs = require("fs");
const ytdl = require("ytdl-core");
const VDiscord = require("./vdiscord.js");
const utilities = require("./index.js");
const ytpl = require("ytpl");
const client = new Discord.Client({
intents: ["GUILD_MESSAGES", "GUILD_VOICE_STATES", "GUILDS"],
});
const config = require("./config.json");
const queue = new Map();
const controller = new VDiscord(client);
const utils = new utilities();
const isAddingPlaylist = new Map();
const clearQueue = new Map();
// async function play(connection, url) {
// connection.play(await ytdl(url, { filter: "audioonly" }), { type: "opus" });
// }
client.on("ready", () => {
console.log(
`Bot has started, with ${client.users.cache.size} users, in ${client.channels.cache.size} channels of ${client.guilds.cache.size} guilds.`
);
client.user.setActivity(`Use $ for commands.`);
});
client.on("message", async (message) => {
if (isAddingPlaylist.get(message.guild.id) === undefined) {
isAddingPlaylist.set(message.guild.id, false);
clearQueue.set(message.guild.id, false);
}
if (!message.content.startsWith(config.prefix)) return;
const args = message.content.slice(config.prefix.length).trim().split(/ +/g);
const command = args.shift().toLowerCase();
const channel = message.member.voice.channel;
if (command === "deafen") {
message.member.voice.setDeaf(true);
}
if (command === "undeafen") {
message.member.voice.setDeaf(false);
}
//use utils
utils.respondToMessage(message, client);
if (command === "ping") {
const m = await message.channel.send("Ping?");
m.edit(
`Pong! Latency is ${
m.createdTimestamp - message.createdTimestamp
}ms. API Latency is ${Math.round(client.ws.ping)}ms`
);
}
if (command === "join") {
if (!channel) return message.reply("Please join a voice channel first!");
if (channel.members.filter((e) => client.user.id === e.user.id).size > 0)
return message.reply(`I'm already in your voice channel!`);
if (!channel.joinable)
return message.reply(
`I don't have permission to join that voice channel!`
);
if (!channel.speakable)
return message.reply(
`I don't have permission to speak in that voice channel!`
);
if (channel) {
const connection = await channel.join();
chan = message.channel;
}
process.on("exit", (err) => {
if (channel) channel.disconnect();
});
}
const serverQueue = queue.get(message.guild.id);
if (command === "play") {
execute(message, serverQueue);
return;
} else if (command === "skip") {
skip(message, serverQueue);
return;
} else if (command === "stop") {
stop(message, serverQueue);
return;
} else if (command === "shuffle") {
shuffle(message, serverQueue);
return;
} else if (command === "queue") {
showQueue(message, serverQueue);
return;
} else if (command === "np") {
nowPlaying(message, serverQueue);
return;
}
//leave call
if (command === "leave") {
try {
if (
message.member.voice.channel.members.filter(
(e) => client.user.id === e.user.id
).size == 0
)
return message.reply(`I already left`);
if (isAddingPlaylist.get(message.guild.id)) {
clearQueue.set(message.guild.id, true);
}
try {
serverQueue.songs = [];
serverQueue.connection.dispatcher.end();
} catch (error) {}
channel.leave();
} catch (error) {}
}
if (command === "record") {
if (!channel) return message.channel.send("Join a VC first!");
if (channel.members.filter((e) => client.user.id === e.user.id).size == 0)
return message.reply("Join a VC");
const connection = client.voice.connections.get(message.member.guild.id);
channel.members.forEach((memberVC) => {
if (!memberVC.user.bot) {
console.log(memberVC.user.username);
const receiver = connection.receiver.createStream(memberVC, {
mode: "pcm",
});
let buffer = [];
let count = 0;
receiver.on("data", (data) => {
//console.log("debug: " + data)
buffer.push(data);
count += 1;
console.log("sending" + count);
});
receiver.on("end", async () => {
buffer = Buffer.concat(buffer);
const duration = buffer.length / 48000 / 4;
try {
controller.googleAudio(buffer, memberVC);
} catch (e) {}
});
message.channel.send("Recording for " + memberVC.user.username);
/*
const writer = receiver.pipe(fs.createWriteStream('audio/'+memberVC.user.username+'audio'));
writer.on('finish', () => {
message.channel.send('Done for ' + memberVC.user.username);
});*/
}
});
}
});
client.on("voice", async (message, member) => {
console.log(message, " : ", member.user.username);
//const args = message.content.slice(config.prefix.length).trim().split(/ +/g);
const command = message;
const channel = member.voice.channel;
if (
command === "death" ||
command === "deafen" ||
command === "deaf" ||
command === "definitely" ||
command === "defin"
) {
member.voice.setDeaf(true);
}
if (
command === "deafen" ||
command === "deaf" ||
command === "definitely" ||
command === "defin"
) {
member.voice.setDeaf(true);
}
if (command === "undeafen") {
member.voice.setDeaf(false);
}
if (command === "undeafin" || command === "undefin") {
member.voice.setDeaf(false);
}
if (
command === "undeafined" ||
command === "undeffin" ||
command === "undefined"
) {
member.voice.setDeaf(false);
}
//use utils
utils.respondToVoice(message, member, client);
const serverQueue = queue.get(member.guild.id);
/*
if (command === "skip") {
v_skip(message, serverQueue);
return;
} else if (command === "stop") {
v_stop(message, serverQueue);
return;
} */
//leave call
if (command === "leave") {
if (
member.voice.channel.members.filter((e) => client.user.id === e.user.id)
.size == 0
)
return message.reply(`I already left`);
channel.leave();
}
});
client.on("shardError", (error) => {
console.error("A websocket connection encountered an error:", error);
});
async function execute(message, serverQueue) {
const args = message.content.split(" ");
const voiceChannel = message.member.voice.channel;
if (!voiceChannel)
return message.channel.send(
"You need to be in a voice channel to play music!"
);
const permissions = voiceChannel.permissionsFor(message.client.user);
if (!permissions.has("CONNECT") || !permissions.has("SPEAK")) {
return message.channel.send(
"I need the permissions to join and speak in your voice channel!"
);
}
if (args[1].includes("playlist")) {
try {
const playlistID = args[1].split("list=")[1];
const songLimit = Infinity;
const playlist = await ytpl(playlistID, { limit: songLimit });
const songCount = playlist.estimatedItemCount;
var currentServerQueue = serverQueue;
message.channel.send(
`Playing ${songCount} songs from: **${playlist.title}**`
);
var songsAdded = 0;
//UnhandledPromiseRejectionWarning error for addingplaylist and clearqueue
isAddingPlaylist.set(message.guild.id, true);
for (const currentSong of playlist.items) {
const clearQ = clearQueue.get(message.guild.id);
if (clearQ) {
break;
}
if (currentSong != undefined) {
songsAdded++;
const song = {
title: currentSong.title,
url: currentSong.url,
};
if (!queue.get(message.guild.id)) {
const queueContruct = {
textChannel: message.channel,
voiceChannel: voiceChannel,
connection: null,
songs: [],
volume: 5,
playing: true,
};
queue.set(message.guild.id, queueContruct);
currentServerQueue = queue.get(message.guild.id);
queueContruct.songs.push(song);
try {
var connection = await voiceChannel.join();
queueContruct.connection = connection;
play(message.guild, queueContruct.songs[0]);
} catch (err) {
console.log(err);
queue.delete(message.guild.id);
return message.channel.send(err);
}
} else {
currentServerQueue.songs.push(song);
}
}
}
isAddingPlaylist.set(message.guild.id, false);
if (clearQueue.get(message.guild.id)) {
clearQueue.set(message.guild.id, false);
return message.channel.send(`Queue cancelled`);
} else {
return message.channel.send(
`**${songsAdded}** songs have been added to the queue!`
);
}
} catch (error) {
console.log(error);
return message.channel.send("Error queue failed");
}
} else {
const songInfo = await ytdl.getInfo(args[1]);
const song = {
title: songInfo.videoDetails.title,
url: args[1],
};
if (!serverQueue) {
const queueContruct = {
textChannel: message.channel,
voiceChannel: voiceChannel,
connection: null,
songs: [],
volume: 5,
playing: true,
};
queue.set(message.guild.id, queueContruct);
queueContruct.songs.push(song);
try {
var connection = await voiceChannel.join();
queueContruct.connection = connection;
play(message.guild, queueContruct.songs[0]);
} catch (err) {
console.log(err);
queue.delete(message.guild.id);
return message.channel.send(err);
}
} else {
serverQueue.songs.push(song);
return message.channel.send(
`**${songInfo.videoDetails.title}** has been added to the queue!`
);
}
}
}
async function convert_audio(input) {
try {
// stereo to mono channel
const data = new Int16Array(input);
const ndata = new Int16Array(data.length / 2);
for (let i = 0, j = 0; i < data.length; i += 4) {
ndata[j++] = data[i];
ndata[j++] = data[i + 1];
}
return Buffer.from(ndata);
} catch (e) {
console.log(e);
console.log("convert_audio: " + e);
throw e;
}
}
function skip(message, serverQueue) {
if (!message.member.voice.channel)
return message.channel.send(
"You have to be in a voice channel to stop the music!"
);
if (!serverQueue)
return message.channel.send("There is no song that I could skip!");
const args = message.content.split(" ");
if (args.length == 2) {
const availaibleSongs = serverQueue.songs.length;
serverQueue.songs.splice(0, args[1]);
serverQueue.connection.dispatcher.end();
return message.channel.send(
`Skipped ${availaibleSongs <= args[1] ? availaibleSongs : args[1]} songs`
);
} else {
serverQueue.connection.dispatcher.end();
return message.channel.send(`Skipped`);
}
}
function v_skip(serverQueue) {
if (!serverQueue) return;
serverQueue.connection.dispatcher.end();
}
function v_stop(serverQueue) {
if (!serverQueue) return;
serverQueue.songs = [];
serverQueue.connection.dispatcher.end();
}
function shuffle(message, serverQueue) {
if (!serverQueue) return;
let songs = serverQueue.songs;
let index = songs.length;
while (index != 0) {
let rIndex = Math.floor(Math.random() * index);
index--;
[songs[index], songs[rIndex]] = [songs[rIndex], songs[index]];
}
return message.channel.send("Queue has been shuffled!");
}
function showQueue(message, serverQueue) {
if (!serverQueue) {
return message.channel.send("Nothing in the queue!");
}
const songs = serverQueue.songs;
let outString = "```\n";
let count = 0;
songs.slice(0, 16).forEach((item) => {
outString += count++ + ". " + item.title + "\n";
});
outString += "```";
return message.channel.send(outString);
}
function nowPlaying(message, serverQueue) {
if (!serverQueue) {
return message.channel.send("Nothing playing!");
}
return message.channel.send(`Currently playing: **${serverQueue[0].title}**`);
}
function stop(message, serverQueue) {
if (!message.member.voice.channel)
return message.channel.send(
"You have to be in a voice channel to stop the music!"
);
if (!serverQueue)
return message.channel.send("There is no song that I could stop!");
if (isAddingPlaylist.get(message.guild.id)) {
clearQueue.set(message.guild.id, true);
}
serverQueue.songs = [];
serverQueue.connection.dispatcher.end();
}
async function play(guild, song) {
const serverQueue = queue.get(guild.id);
if (!song) {
serverQueue.voiceChannel.leave();
queue.delete(guild.id);
return;
}
//const songInfo = await ytdl.getInfo(song.url);
const currentSong = song;
await sleep(500);
let stream = ytdl(currentSong.url, {
filter: "audioonly",
opusEncoded: false,
fmt: "mp3",
encoderArgs: ["-af", "bass=g=10,dynaudnorm=f=200"],
});
const dispatcher = serverQueue.connection
.play(stream, { type: "unknown" })
.on("finish", () => {
serverQueue.songs.shift();
play(guild, serverQueue.songs[0]);
})
.on("error", (error) => console.log(error));
dispatcher.setVolumeLogarithmic(serverQueue.volume / 5);
serverQueue.textChannel.send(`Start playing: **${currentSong.title}**`);
}
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
client.login(config.discord_token);