-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
86 lines (67 loc) · 2.28 KB
/
index.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
require('dotenv').config();
const Discord = require('discord.js');
const ytdl = require('ytdl-core');
const lowdb = require('lowdb');
const FileSync = require('lowdb/adapters/FileSync');
const client = new Discord.Client();
client.login(process.env.DISCORD_BOT_TOKEN);
const db = lowdb(new FileSync('db.json'));
db.defaults({
users: {},
}).write();
const commands = {
welcome(message) {
const user = message.mentions.members.first();
const [, link] = /^(?:\/welcome <.+>) (.+)/.exec(message.content) || [];
if (link) {
db.get('users').assign({
[user.id]: link,
}).write();
message.delete();
}
},
};
function routeMessage(message) {
const command = Object.keys(commands)
.find(command => new RegExp(`\/${command}`).test(message.content));
if (command) {
commands[command](message);
}
}
client.on('message', routeMessage);
let queue = [];
let isPlaying = false;
async function addToQueue(soundEffect, voiceChannel, id) {
if (!isPlaying) {
isPlaying = true;
queue = queue.filter(({ id: idToRemove }) => id !== idToRemove);
const connection = await voiceChannel.join();
const youtubeStream = ytdl(soundEffect, { filter: 'audioonly' });
const discordStream = connection.playStream(youtubeStream);
discordStream.on('end', reason => {
if (reason) {
isPlaying = false;
if (queue.length) {
addToQueue(...Object.values(queue.shift()));
} else {
connection.disconnect();
}
}
});
} else {
queue.push({ soundEffect, voiceChannel, id });
}
}
client.on('voiceStateUpdate', async (oldMember, newMember) => {
const soundEffect = db.get(`users.${newMember.user.id}`).value();
if (!soundEffect) {
return;
}
const { voiceChannel: newUserChannel } = newMember;
const { voiceChannel: oldUserChannel } = oldMember;
if(oldUserChannel === undefined && newUserChannel !== undefined) {
addToQueue(soundEffect, newMember.voiceChannel);
} else if (newUserChannel === undefined) {
client.voiceConnections.every(connection => connection.disconnect());
}
});