This repository has been archived by the owner on May 4, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bot.js
284 lines (250 loc) · 10.2 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
const dev_mode = false;
const Discord = require('discord.js');
const client = new Discord.Client();
const tokens = require('./tokens.json');
const ytdl = require('ytdl-core');
const search = require('youtube-search');
let secret;
try {
secret = require('./secret.json');
} catch (err) {
console.log('Secret not found. Ignoring.');
}
const {
Client
} = require('pg');
let db;
const prefix = dev_mode ? tokens.dev_prefix : tokens.prefix;
if (process.env.DATABASE_URL) {
console.log('Connecting via heroku..');
db = new Client({
connectionString: process.env.DATABASE_URL,
ssl: true,
});
} else {
console.log('Connecting via local..')
db = new Client({
user: 'postgres',
host: 'localhost',
database: 'postgres',
password: secret.dbpswrd,
port: 5432,
});
}
db.connect(err => {
if (err) throw err;
console.log('Connected!');
});
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
});
let queue = [];
const commands = {
'play': (msg) => {
if (!msg.member.voiceChannel) return msg.channel.send(embed('', 'Join a voice channel first.'));
msg.member.voiceChannel.join().then(async connection => {
const opts = {
maxResults: 10,
key: process.env.YOUTUBE_API_TOKEN || secret.youtube_api_key,
order: 'viewCount'
};
const streamOptions = {
seek: 0,
volume: 1,
bitrate: 96000,
passes: 2
};
let song = msg.content.split(' ').slice(1).join(' ');
if (!song) return msg.channel.send('Specify a song!');
let songs = [];
search(song, opts, async function(err, results) {
if (err) return console.log(err);
results.forEach(function(element) {
songs.push({
title: element.title,
url: element.link,
id: element.id
});
});
getSongs(songs).then(async songs => {
let message = [];
for (let i = 0; i < songs.length; i++) {
message[i] = `${i + 1}. ${songs[i].title}`;
}
msg.channel.send(embed('Choose a Song', message.join('\n'), `Pick a number between 1 and ${songs.length}.`)).then(message => {
let songPicker = msg.channel.createMessageCollector(m => m);
songPicker.on('collect', async m => {
if (isNaN(m)) return;
//await m.delete();
let number = await parseInt(m) - 1;
if (number < 0 || number > songs.length) return;
songPicker.stop();
m.delete();
message.delete();
//channel.fetchMessages({ limit: 10 })
if (!queue.hasOwnProperty(msg.guild.id)) queue[msg.guild.id] = {}, queue[msg.guild.id].playing = false, queue[msg.guild.id].repeat = false, queue[msg.guild.id].songs = [];
queue[msg.guild.id].songs.push({
url: songs[number].url,
name: songs[number].title
});
if (queue[msg.guild.id].playing) return msg.channel.send(embed('', `Added ${songs[number].title} to the queue.`));
playSong();
async function playSong() {
queue[msg.guild.id].playing = true;
const stream = await ytdl(queue[msg.guild.id].songs[0].url, {
filter: 'audioonly'
});
const dispatcher = connection.playStream(stream, streamOptions);
msg.channel.send(embed('', `Getting the party ready..`)).then(async message => {
let collector_reaction = emoteCollector(message, ['▶', '⏸', '⏭', '🔁'], msg.author.id);
dispatcher.on('start', async () => {
let song_length = 0;
ytdl.getInfo(songs[number].id, (err, info) => {
song_length = info.length_seconds;
});
await message.edit(embed('', `Playing ${queue[msg.guild.id].songs[0].name}`));
await message.react('▶');
await message.react('⏸');
await message.react('⏭');
await message.react('🔁');
collector_reaction.on('collect', (messageReaction, reactionCollector) => {
let reaction = messageReaction.emoji.name;
if (reaction == '⏸') {
if (!dispatcher.paused) {
dispatcher.pause();
clearInterval(queue[msg.guild.id].intervalID);
message.reactions.find(val => val.emoji.name === '⏸').remove(msg.author.id);
}
}
if (reaction == '▶') {
if (dispatcher.paused) {
dispatcher.resume();
queue[msg.guild.id].intervalID = setInterval(timeLeft, 15000);
message.reactions.find(val => val.emoji.name === '▶').remove(msg.author.id);
}
}
if (reaction == '⏭') {
queue[msg.guild.id].repeat = false;
dispatcher.end();
message.edit(embed('', `Skipped ${queue[msg.guild.id].songs[0].name}`));
}
if (reaction == '🔁') {
if (!queue[msg.guild.id].repeat) {
queue[msg.guild.id].repeat = true;
msg.channel.send(embed('', `${queue[msg.guild.id].songs[0].name} will now repeat.`));
} else {
queue[msg.guild.id].repeat = false;
msg.channel.send(embed('', `${queue[msg.guild.id].songs[0].name} will no longer repeat.`));
}
message.reactions.find(val => val.emoji.name === '🔁').remove(msg.author.id);
}
});
let progressBar = [];
let progressBarLength = 40;
for (let i = 0; i < progressBarLength; i++) {
if (i == 0) {
progressBar[i] = '[';
} else if (i == progressBarLength - 1) {
progressBar[i] = ']';
} else {
progressBar[i] = '-';
}
}
queue[msg.guild.id].intervalID = setInterval(timeLeft, 15000);
function timeLeft() {
let current_time = Math.floor(dispatcher.time / 1000);
let percent = Math.floor(current_time / song_length * 100);
let progressBarPosition = Math.floor(percent / 100 * progressBarLength);
for (let i = 1; i < progressBarPosition - 2; i++) {
progressBar[i] = '=';
}
let theDate = new Date(dispatcher.time);
let showTime = theDate.getMinutes() + ":" + (theDate.getSeconds() < 10 ? '0' : '') + theDate.getSeconds();
let finalDate = new Date(song_length * 1000);
let endTime = finalDate.getMinutes() + ":" + (finalDate.getSeconds() < 10 ? '0' : '') + finalDate.getSeconds();
message.edit(embed('', `Playing ${queue[msg.guild.id].songs[0].name}`, `${progressBar.join('')} [${showTime} / ${endTime}]`));
}
});
dispatcher.on('end', async () => {
clearInterval(queue[msg.guild.id].intervalID);
await collector_reaction.stop();
message.clearReactions();
message.edit(embed('', `Finished playing ${queue[msg.guild.id].songs[0].name}`));
queue[msg.guild.id].playing = false;
if (!queue[msg.guild.id].repeat) queue[msg.guild.id].songs.shift();
if (queue[msg.guild.id].songs.length != 0) {
playSong();
}
});
dispatcher.on('error', (err) => {
console.log(err);
});
dispatcher.on('debug', (info) => {
console.log(info);
});
});
}
/*let collector = msg.channel.createMessageCollector(m => m);
collector.on('collect', m => {
if (m.content.startsWith(prefix + 'skip')) {
dispatcher.end();
msg.channel.send(embed('', `Skipped ${songs[number].title}`));
}
if (m.content.startsWith(prefix + 'time')) {
msg.channel.send(dispatcher.time / 1000);
}
});*/
});
});
});
});
});
}
};
client.on('message', async msg => {
if (msg.author.bot) return;
if (msg.channel.type == 'dm') return;
if (!msg.content.startsWith(prefix)) return;
if (commands.hasOwnProperty(msg.content.toLowerCase().slice(prefix.length).split(' ')[0])) {
commands[msg.content.toLowerCase().slice(prefix.length).split(' ')[0]](msg);
}
if (msg.content.startsWith(prefix + 'play')) {
}
});
function emoteCollector(reactionMessage, emotes, id) {
const filter = (reaction, user) => {
return emotes.includes(reaction.emoji.name) && user.id === id;
};
const collector = reactionMessage.createReactionCollector(filter);
return collector;
}
function getSongs(songs) {
return new Promise((resolve, reject) => {
resolve(songs);
});
}
function embed(title, desc, footer) {
return {
embed: {
title: title,
description: desc,
footer: {
text: footer
}
}
}
}
if (dev_mode) {
client.login(dev_mode ? secret.dev_token : secret.token);
} else {
client.login(process.env.BOT_TOKEN);
}
/*db.query('CREATE TABLE IF NOT EXISTS supertable (name text UNIQUE, i integer)');
db.query('INSERT INTO supertable (name, i) VALUES ($1, $2) ON CONFLICT (name) DO NOTHING;', [msg.author.id, 3]);
db.query('SELECT * FROM supertable', (err, res) => {
if (err) throw err;
for (let row of res.rows) {
console.log(row.name);
console.log(row.i);
}
});*/