· 6 years ago · Oct 02, 2019, 11:20 AM
1const http = require('http');
2const express = require('express');
3const app = express();
4app.get("/", (request, response) => {
5 console.log(Date.now() + " Ping Received");
6 response.sendStatus(200);
7});
8app.listen(process.env.PORT);
9setInterval(() => {
10 http.get(`http://${process.env.PROJECT_DOMAIN}.glitch.me/`);
11}, 280000);
12
13const { Client, Util, RichEmbed } = require('discord.js');
14const { TOKEN, PREFIX, GOOGLE_API_KEY } = require('./config');
15const YouTube = require('simple-youtube-api');
16const ytdl = require('ytdl-core');
17
18const client = new Client({ disableEveryone: true });
19
20const youtube = new YouTube(GOOGLE_API_KEY);
21
22const queue = new Map();
23
24client.on('warn', console.warn);
25
26client.on('error', console.error);
27
28client.on('ready', () => console.log(`${client.user.username} is online!`));
29
30client.on('disconnect', () => console.log('I just disconnected, making sure you know, I will reconnect now...'));
31
32client.on('reconnecting', () => console.log('I am reconnecting now!'));
33
34client.on('message', async msg => { // eslint-disable-line
35 if (msg.author.bot) return undefined;
36 if (!msg.content.startsWith(PREFIX)) return undefined;
37
38 const args = msg.content.split(' ');
39 const searchString = args.slice(1).join(' ');
40 const url = args[1] ? args[1].replace(/<(.+)>/g, '$1') : '';
41 const serverQueue = queue.get(msg.guild.id);
42
43 let command = msg.content.toLowerCase().split(' ')[0];
44 command = command.slice(PREFIX.length)
45
46 if (command === 'play') {
47 const voiceChannel = msg.member.voiceChannel;
48 if (!voiceChannel) return msg.channel.send('Lu Join Voice dulu baru ketik play!');
49 const permissions = voiceChannel.permissionsFor(msg.client.user);
50 if (!permissions.has('CONNECT')) {
51 return msg.channel.send('Gw ga bisa join Voice, Kasih Permissions dulu!');
52 }
53 if (!permissions.has('SPEAK')) {
54 return msg.channel.send('I cannot speak in this voice channel, make sure I have the proper permissions!');
55 }
56
57 if (url.match(/^https?:\/\/(www.youtube.com|youtube.com)\/playlist(.*)$/)) {
58 const playlist = await youtube.getPlaylist(url);
59 const videos = await playlist.getVideos();
60 for (const video of Object.values(videos)) {
61 const video2 = await youtube.getVideoByID(video.id); // eslint-disable-line no-await-in-loop
62 await handleVideo(video2, msg, voiceChannel, true); // eslint-disable-line no-await-in-loop
63 }
64 return msg.channel.send(`✅ Playlist: **${playlist.title}** has been added to the queue!`);
65 } else {
66 try {
67 var video = await youtube.getVideo(url);
68 } catch (error) {
69 try {
70 var videos = await youtube.searchVideos(searchString, 10);
71 let index = 0;
72 let HatiEmbed = new RichEmbed()
73 .setColor('RANDOM')
74 .setDescription(`
75__**Song selection:**__
76${videos.map(video2 => `**${++index} -** ${video2.title}`).join('\n')}
77`)
78 .setFooter('Please provide a value to select one of the search results ranging from 1-10.')
79
80 let iniHapus = await msg.channel.send(HatiEmbed)
81 // eslint-disable-next-line max-depth
82 try {
83 var response = await msg.channel.awaitMessages(msg2 => msg2.content > 0 && msg2.content < 11, {
84 maxMatches: 1,
85 time: 20000,
86 errors: ['time']
87 });
88 iniHapus.delete();
89 } catch (err) {
90 console.error(err);
91 msg.channel.send('No or invalid value entered, cancelling video selection.');
92 iniHapus.delete();
93 return;
94 }
95 const videoIndex = parseInt(response.first().content);
96 var video = await youtube.getVideoByID(videos[videoIndex - 1].id);
97 } catch (err) {
98 console.error(err);
99 return msg.channel.send('? I could not obtain any search results.');
100 }
101 }
102 return handleVideo(video, msg, voiceChannel);
103 }
104 } else if (command === 'skip') {
105 if (!msg.member.voiceChannel) return msg.channel.send('You are not in a voice channel!');
106 if (!serverQueue) return msg.channel.send('There is nothing playing that I could skip for you.');
107 serverQueue.connection.dispatcher.end('Skip command has been used!');
108 return undefined;
109 } else if (command === 'stop') {
110 if (!msg.member.voiceChannel) return msg.channel.send('You are not in a voice channel!');
111 if (!serverQueue) return msg.channel.send('There is nothing playing that I could stop for you.');
112 serverQueue.songs = [];
113 serverQueue.connection.dispatcher.end('Stop command has been used!');
114 return undefined;
115 } else if (command === 'volume') {
116 if (!msg.member.voiceChannel) return msg.channel.send('You are not in a voice channel!');
117 if (!serverQueue) return msg.channel.send('There is nothing playing.');
118 if (!args[1]) return msg.channel.send(`The current volume is: **${serverQueue.volume}**%`);
119 if (args[1] > 100) return msg.reply(`Volume limit is 100%, please do not hurt yourself!`);
120 serverQueue.volume = args[1];
121 serverQueue.connection.dispatcher.setVolumeLogarithmic(args[1] / 100);
122 return msg.channel.send(`I set the volume to: **${args[1]}**%`);
123 } else if (command === 'np') {
124 const request = msg.author.toString()
125 if (!serverQueue) return msg.channel.send('There is nothing playing.');
126 return msg.channel.send(`? Now playing: **${serverQueue.songs[0].title}**\nRequest by: ${serverQueue.songs[0].request}`);
127 } else if (command === 'queue') {
128 if (!serverQueue) return msg.channel.send('There is nothing playing.');
129 return msg.channel.send(`
130__**Song queue :**__
131${serverQueue.songs.map(song => `**-** ${song.title}`).join('\n')}
132`);
133
134 } else if (command === 'pause') {
135 if (serverQueue && serverQueue.playing) {
136 serverQueue.playing = false;
137 serverQueue.connection.dispatcher.pause();
138 return msg.channel.send('⏸ Paused the music for you!');
139 }
140 return msg.channel.send('There is nothing playing.');
141 } else if (command === 'resume') {
142 if (serverQueue && !serverQueue.playing) {
143 serverQueue.playing = true;
144 serverQueue.connection.dispatcher.resume();
145 return msg.channel.send('▶ Resumed the music for you!');
146 }
147 return msg.channel.send('There is nothing playing.');
148 }
149
150 return undefined;
151});
152
153async function handleVideo(video, msg, voiceChannel, playlist = false) {
154 const serverQueue = queue.get(msg.guild.id);
155 console.log(video);
156 const song = {
157 id: video.id,
158 title: Util.escapeMarkdown(video.title),
159 url: `https://www.youtube.com/watch?v=${video.id}`,
160 request: msg.author.toString()
161 };
162 if (!serverQueue) {
163 const queueConstruct = {
164 textChannel: msg.channel,
165 voiceChannel: voiceChannel,
166 connection: null,
167 songs: [],
168 volume: 100,
169 playing: true
170 };
171 queue.set(msg.guild.id, queueConstruct);
172
173 queueConstruct.songs.push(song);
174
175 try {
176 var connection = await voiceChannel.join();
177 queueConstruct.connection = connection;
178 play(msg.guild, queueConstruct.songs[0]);
179 } catch (error) {
180 console.error(`I could not join the voice channel: ${error}`);
181 queue.delete(msg.guild.id);
182 return msg.channel.send(`I could not join the voice channel: ${error}`);
183 }
184 } else {
185 serverQueue.songs.push(song);
186 console.log(serverQueue.songs);
187 if (playlist) return undefined;
188 else return msg.channel.send(`✅ **${song.title}** has been added to the queue!`);
189 }
190 return undefined;
191}
192
193function play(guild, song) {
194 const serverQueue = queue.get(guild.id);
195
196 if (!song) {
197 serverQueue.voiceChannel.leave();
198 queue.delete(guild.id);
199 return;
200 }
201 console.log(serverQueue.songs);
202
203 const dispatcher = serverQueue.connection.playStream(ytdl(song.url))
204 .on('end', reason => {
205 if (reason === 'Stream is not generating quickly enough.') console.log('Song ended.');
206 else console.log(reason);
207 serverQueue.songs.shift();
208 play(guild, serverQueue.songs[0]);
209 })
210 .on('error', error => console.error(error));
211 dispatcher.setVolumeLogarithmic(serverQueue.volume / 100);
212
213 serverQueue.textChannel.send(`? Start playing: **${song.title}**\nRequest by: ${song.request}`);
214}
215
216client.login(TOKEN);
217
218
219
220CONFIG.JS
221exports.TOKEN = 'NDk2NDY0NDI3MDU1NDQ4MDY3.DpmfxA.FuFdPLr0yM12VZ3Z5-MJnLCf03c';
222
223exports.PREFIX = 'k!';
224
225exports.GOOGLE_API_KEY = 'AIzaSyBLs-ZQkuMaYnr47R4eC04Dh58nF2YfmUY';
226
227
228
229SERVER.JS
230// server.js
231// where your node app starts
232
233// init project
234var express = require('express');
235var bodyParser = require('body-parser');
236var app = express();
237app.use(bodyParser.urlencoded({ extended: true }));
238
239// we've started you off with Express,
240// but feel free to use whatever libs or frameworks you'd like through `package.json`.
241
242// http://expressjs.com/en/starter/static-files.html
243app.use(express.static('public'));
244
245// init sqlite db
246var fs = require('fs');
247var dbFile = './.data/sqlite.db';
248var exists = fs.existsSync(dbFile);
249var sqlite3 = require('sqlite3').verbose();
250var db = new sqlite3.Database(dbFile);
251
252// if ./.data/sqlite.db does not exist, create it, otherwise print records to console
253db.serialize(function(){
254 if (!exists) {
255 db.run('CREATE TABLE Dreams (dream TEXT)');
256 console.log('New table Dreams created!');
257
258 // insert default dreams
259 db.serialize(function() {
260 db.run('INSERT INTO Dreams (dream) VALUES ("Find and count some sheep"), ("Climb a really tall mountain"), ("Wash the dishes")');
261 });
262 }
263 else {
264 console.log('Database "Dreams" ready to go!');
265 db.each('SELECT * from Dreams', function(err, row) {
266 if ( row ) {
267 console.log('record:', row);
268 }
269 });
270 }
271});
272
273// http://expressjs.com/en/starter/basic-routing.html
274app.get('/', function(request, response) {
275 response.sendFile(__dirname + '/views/index.html');
276});
277
278// endpoint to get all the dreams in the database
279// currently this is the only endpoint, ie. adding dreams won't update the database
280// read the sqlite3 module docs and try to add your own! https://www.npmjs.com/package/sqlite3
281app.get('/getDreams', function(request, response) {
282 db.all('SELECT * from Dreams', function(err, rows) {
283 response.send(JSON.stringify(rows));
284 });
285});
286
287// listen for requests :)
288var listener = app.listen(process.env.PORT, function() {
289 console.log('Your app is listening on port ' + listener.address().port);
290});
291
292
293
294PACKAGE.JSON
295
296{
297 "//1": "describes your app and its dependencies",
298 "//2": "https://docs.npmjs.com/files/package.json",
299 "//3": "updating this file will download and update your packages",
300 "name": "hello-sqlite",
301 "version": "0.0.1",
302 "description": "A simple Node app with SQLite as a database management system, instantly up and running.",
303 "main": "server.js",
304 "scripts": {
305 "start": "node bot.js"
306 },
307 "dependencies": {
308 "discord.js": "^11.4.2",
309 "express": "^4.16.3",
310 "sqlite3": "^4.0.2",
311 "simple-youtube-api": "^5.0.2",
312 "ytdl-core": "^0.26.1",
313 "node-opus": "^0.3.0"
314 },
315 "engines": {
316 "node": "8.x"
317 },
318 "repository": {
319 "url": "https://glitch.com/edit/#!/hello-sqlite"
320 },
321 "license": "MIT",
322 "keywords": [
323 "node",
324 "glitch",
325 "express"
326 ]
327}