Advertisement
edwin0258

Bot

Aug 12th, 2017
214
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 16.46 KB | None | 0 0
  1. const DubAPI = require('dubapi');
  2. const YouTube = require('youtube-node');
  3. const fs = require('fs');
  4. const compArr = require('./composerArray.js');
  5. let YT = new YouTube();
  6. YT.setKey('-----');
  7. // username
  8. let un = '-----'
  9.  
  10. new DubAPI({username: un, password: '-----'}, function(err, bot) {
  11. if (err) return console.error(err);
  12.  
  13. console.log('Running DubAPI v' + bot.version);
  14.  
  15. function connect() {bot.connect('limitless');}
  16. connect();
  17.  
  18. bot.on('connected', function(name) {
  19. console.log('Connected to ' + name);
  20. setTimeout(shouldUpDub, 2000);
  21.  
  22. });
  23.  
  24.  
  25. bot.on('disconnected', function(name) {
  26. console.log('Disconnected from ' + name);
  27. setTimeout(connect, 15000);
  28. });
  29.  
  30. bot.on('error', function(err) {
  31. console.error(err);
  32. });
  33.  
  34. bot.on(bot.events.chatMessage, function(data) {
  35. console.log(data.user.username + ': ' + data.message);
  36. let message = data.message;
  37. let user = data.user.username;
  38. respondToMessage(message, user);
  39. });
  40.  
  41. bot.on(bot.events.userJoin, (data) => {
  42. console.log(data.user.username + " has joined.");
  43. updateUser(data.user.username, () => {});
  44. })
  45.  
  46.  
  47.  
  48. // My functions
  49. let currentId; // Current Music id - Changes on each new video.
  50. let radioMode = false; // if the radio is active this will be set to true.
  51. let roullete = false;
  52. let entered = [];
  53. let songStats;
  54. function addToRadio() {
  55. let ca = compArr.getArray();
  56. function getRandom(arr, remove) {
  57. return arr[Math.floor(Math.random() * arr.length)];
  58. }
  59.  
  60. let artist = getRandom(ca);
  61. console.log(artist);
  62. let videos = [];
  63. YT.search(artist, 4, (err, results) => {
  64. results.items.forEach(item => {
  65. if(item.id.kind == 'youtube#video') {
  66. let vID = item.id.videoId;
  67. videos.push(vID);
  68. }
  69. })
  70. queueVideos();
  71. })
  72. // remove duplicates.
  73. function queueVideos() {
  74. videos = [... new Set(videos)];
  75. if(videos.length != 0) {
  76. for(let i = 0; i < 1; i++) {
  77. let randVid = getRandom(videos);
  78. let index = videos.indexOf(randVid);
  79. videos.splice(index, 1);
  80. bot.queueMedia('youtube', randVid);
  81. fs.appendFile("songsQueued.txt", randVid + " artist: " + artist + '\n' , (err) => {
  82. if(err){ console.log(err); }
  83. })
  84. }
  85. bot.pauseQueue(false);
  86. } else {
  87. addToRadio();
  88. }
  89. }
  90. }
  91.  
  92. /* shouldUpDub */
  93. /* - If there is something being played and the bot has not regestered it before then the bot will updub the song. It will also send to chat a "Now Playing" message. It will then sent the currentId to this new songs id song it does not try to updub twice. It thens sets a timeout for the shouldUpDub function to be called again in 10 seconds.
  94. - If the song has already been registered then the shouldUpDub will be called again in 10 seconds via a setTimeout.
  95. - If no song is currently playing then first a 10 second timeout will call shouldUpDub with its only parameter called radio. If nothing has still not been queued after the 10 seconds then if the bot has it's radio mode enabled it will add to it's radio queue and start playing some music. It will also call shouldUpDub in a setTimeout as normal.
  96. */
  97.  
  98. function shouldUpDub(radio) {
  99. if(bot.getMedia()) {
  100. let {id, name, type, fkid} = bot.getMedia();
  101. if (currentId != id) {
  102. console.log("updubing");
  103. fs.readFile('./stats.json',"utf8", (err, data) => {
  104. let stats = JSON.parse(data);
  105. stats[id] = stats[id] || {};
  106. stats[id].count = stats[id].count + 1 || 1;
  107. stats[id].totalGrabs = stats[id].totalGrabs || 0;
  108. stats[id].name = stats[id].name || name;
  109. stats[id].fkid = stats[id].fkid || fkid;
  110. stats[id].type = stats[id].type || type;
  111. // most grabs for song in a single play.
  112. stats[id].mostGrabs = stats[id].mostGrabs || 0;
  113. songStats = stats[id];
  114.  
  115. ((id) => {
  116. setTimeout(() => {
  117. // skipped track gets overwritten, FIX.
  118. // Add grabs to total grans for song.
  119. stats[id].totalGrabs += bot.getScore().grabs;
  120. // if grabs for play are more then previous record for song.
  121. if(stats[id].mostGrabs < bot.getScore().grabs) {
  122. stats[id].mostGrabs = bot.getScore().grabs;
  123. }
  124. fs.writeFile('./stats.json', JSON.stringify(stats), (err) => {
  125. if(err) throw err;
  126. console.log(stats[id]);
  127. })
  128. }, +bot.getTimeRemaining());
  129. })(id);
  130. })
  131. //bot.sendChat("Now Playing: " + name);
  132. bot.updub();
  133. currentId = id;
  134. setTimeout(() => {shouldUpDub()}, 10000);
  135.  
  136. } else {
  137. setTimeout(() => {shouldUpDub()}, 10000);
  138. }
  139. } else {
  140. if(radio) {
  141. if(radioMode && bot.getQueue().length == 0) {
  142. addToRadio();
  143. }
  144. setTimeout(() => {shouldUpDub()}, 10000);
  145. } else {
  146. setTimeout(() => {shouldUpDub(true)}, 10000);
  147. }
  148. }
  149. }
  150. let times = [3000000, 3600000, 2400000];
  151. let time = times[Math.floor(Math.random() * times.length)];
  152. setTimeout(() => { startRoullete() }, time);
  153. function startRoullete() {
  154. bot.sendChat("@----- !r");
  155. // random time
  156.  
  157. time = times[Math.floor(Math.random() * times.length)];
  158. setTimeout(() => { startRoullete() }, time);
  159. }
  160.  
  161. function updateUser(user, callback) {
  162. let uid = bot.getUserByName(user).id;
  163. fs.readFile('./users.json',"utf8", (err, data) => {
  164. let stats = JSON.parse(data);
  165. stats[uid] = stats[uid] || {"wins": 0, "username": user};
  166. if(typeof stats[uid].username == "undefined" || stats[uid].username != user) {
  167. stats[uid].username = user;
  168. }
  169. stats[uid].lastSeen = new Date;
  170. fs.writeFile('./users.json', JSON.stringify(stats), (err) => {
  171. if(err) throw err;
  172. callback();
  173. })
  174. })
  175. }
  176.  
  177. function respondToMessage(message, user) {
  178. let bot_response = false;
  179.  
  180. function checkMessage(command) {
  181. if(message.includes(command) && message.includes(`@${un}`) && bot_response == false && (user == "----" || user == "-----")) {
  182. return true;
  183. }
  184. return false;
  185. }
  186.  
  187.  
  188.  
  189. if(message == "!stats") {
  190. bot.sendChat(`song stats: total grabs - ${songStats.totalGrabs + bot.getScore().grabs}, times played: - ${songStats.count}.`)
  191. }
  192.  
  193. if(message == "!topgrabbed") {
  194. fs.readFile('./stats.json',"utf8", (err, data) => {
  195. let stats = JSON.parse(data);
  196. let topGrabbedKeys = Object.keys(stats).sort((a, b) => {
  197. return stats[b].totalGrabs - stats[a].totalGrabs
  198. })
  199. bot.sendChat('Most grabbed songs (total grabs):');
  200. //let message = "";
  201. for(let x = 0; x < 3; x++) {
  202. bot.sendChat(`${stats[topGrabbedKeys[x]].name} - ${stats[topGrabbedKeys[x]].totalGrabs}`);
  203. }
  204. })
  205. }
  206.  
  207. if(message == "!hotplays") {
  208. fs.readFile('./stats.json',"utf8", (err, data) => {
  209. let stats = JSON.parse(data);
  210. let topGrabbedKeys = Object.keys(stats).sort((a, b) => {
  211. return stats[b].totalGrabs - stats[a].totalGrabs
  212. })
  213. bot.sendChat('Most grabbed songs (single play):');
  214. //let message = "";
  215. for(let x = 0; x < 3; x++) {
  216. bot.sendChat(`${stats[topGrabbedKeys[x]].name} - ${stats[topGrabbedKeys[x]].totalGrabs}`);
  217. }
  218.  
  219. })
  220. }
  221.  
  222. if(message.includes("!info") && message.split(' ').length == 2 && message.split(' ')[0] == "!info") {
  223. // Update user that asked in case they are not registered in users.
  224. //queried user for info.
  225. let queryUser = message.split(' ')[1];
  226. //bot.sendChat('This feature is still experimental.')
  227. fs.readFile('./users.json',"utf8", (err, data) => {
  228. let users = JSON.parse(data);
  229. let usernames = {};
  230. for(x in users) { usernames[users[x].username] = {id: x} }
  231. let sortedWins = Object.keys(users).sort((a, b) => {
  232. return users[b].wins - users[a].wins
  233. })
  234. if(bot.getUserByName(queryUser) && !usernames[queryUser]) {
  235. updateUser(queryUser, () => {
  236. bot.sendChat('You have just been added to users, try again.');
  237. })
  238. } else if (usernames[queryUser]) {
  239. let uid = usernames[queryUser].id;
  240.  
  241. bot.sendChat(`User: ${queryUser}`);
  242. bot.sendChat(`Wins: ${users[uid].wins} (${sortedWins.indexOf(uid)}/${sortedWins.length})`);
  243. if(users[uid].lastSeen) {
  244. bot.sendChat(`Last Seen: ${users[uid].lastSeen}`);
  245. } else {
  246. //bot.sendChat(`Last Seen has not been set yet.`);
  247. }
  248. } else {
  249. bot.sendChat('User is not registered.');
  250. }
  251. });
  252. }
  253.  
  254. if(message == "!info") {
  255. bot.sendChat('Sorry, you need to specify a username after !info.');
  256. }
  257.  
  258. if(message == "!commands") {
  259. bot.sendChat("Commands are: !stats, !sign, !mostplayed, !topgrabbed, !hotplays, !winners, !song, !info");
  260. }
  261.  
  262. if(message == "!mostplayed") {
  263. fs.readFile('./stats.json',"utf8", (err, data) => {
  264. let stats = JSON.parse(data);
  265. let topPlayedKeys = Object.keys(stats).sort((a, b) => {
  266. return stats[b].count - stats[a].count
  267. })
  268. bot.sendChat('Most played songs:');
  269. for(let x = 0; x < 3; x++) {
  270. bot.sendChat(`${stats[topPlayedKeys[x]].name} - ${stats[topPlayedKeys[x]].count}`);
  271. };
  272. })
  273. }
  274.  
  275. if(message == "!winners") {
  276. fs.readFile('./users.json',"utf8", (err, data) => {
  277. let stats = JSON.parse(data);
  278. let topPlayerKeys = Object.keys(stats).sort((a, b) => {
  279. return stats[b].wins - stats[a].wins
  280. })
  281. bot.sendChat('Users with the most wins:');
  282. for(let x = 0; x < 3; x++) {
  283. if(topPlayerKeys[x]) {
  284. bot.sendChat(`${stats[topPlayerKeys[x]].username} - ${stats[topPlayerKeys[x]].wins}`);
  285. }
  286. }
  287. })
  288. }
  289.  
  290. if(checkMessage("!r")) {
  291. roullete = true;
  292. bot.sendChat("@djs The roulette is starting! Have a song queued and type anything in chat to enter the roulette!");
  293.  
  294. setTimeout(() => {
  295. let n = Math.floor(Math.random() * entered.length);
  296. let position = Math.floor(Math.random() * 3);
  297. let users = bot.getQueue().reduce((obj, item) => {
  298. obj[item.user.username] = item.user.id;
  299. return obj;
  300. },[]);
  301. let winner = entered[n];
  302. if(winner != undefined) {
  303. bot.sendChat(`@${winner} wins.`);
  304. let uid = bot.getUserByName(winner).id;
  305.  
  306. fs.readFile('./users.json',"utf8", (err, data) => {
  307. let users = JSON.parse(data);
  308. users[uid] = users[uid] || {};
  309. users[uid].wins = users[uid].wins + 1 || 1;
  310.  
  311. if(!users[uid].username || users[uid].username != winner) {
  312. users[uid].username = winner;
  313. console.log(users[uid].username);
  314. }
  315. fs.writeFile('./users.json', JSON.stringify(users), (err) => {
  316. if(err) throw err;
  317. })
  318. })
  319. bot.sendChat(`Moving ${winner} to position 1`);
  320. bot.moderateMoveDJ(users[entered[n]], 0);
  321. } else {
  322. bot.sendChat('Looks like no one wins.');
  323. }
  324. entered = [];
  325. roullete = false;
  326. }, 60000);
  327. }
  328.  
  329. if(roullete) {
  330. let queuedUsers = bot.getQueue().reduce((arr, item) => {
  331. arr.push(item.user.username);
  332. return arr;
  333. },[]);
  334. if(user != "-----" && message && !entered.includes(user)) {
  335. if(!queuedUsers.includes(user)) {
  336. //bot.sendChat(`Sorry ${user} you aren't in the queue.`)
  337. } else {
  338. entered.push(user);
  339. //bot.sendChat(`You've joined the roulette, ${user}.`)
  340. entered = [...new Set(entered)];
  341. }
  342. }
  343. }
  344.  
  345. if(checkMessage("!i")) {
  346. console.log(bot.getMedia());
  347. console.log(bot.getScore().grabs)
  348. setTimeout(() => { bot.sendChat(`Total of ${bot.getScore().grabs} grabs`)}, +bot.getTimeRemaining());
  349. }
  350.  
  351. // !cq stands for clear queue, this will clear the bots queue.
  352. if(checkMessage("!cq")){
  353. console.log(`cleared by ${user}`);
  354.  
  355. bot.pauseQueue(true, () => {
  356. bot.clearQueue();
  357. });
  358. fs.writeFile('songsQueued.txt','',(err) => {if(err) console.log(err) })
  359. bot_response = true;
  360. }
  361.  
  362. if(checkMessage("!stopradio")) {
  363. radioMode = false;
  364. bot_response = true;
  365. }
  366.  
  367. // !startradio stands for start radio
  368. if(checkMessage("!startradio")) {
  369. radioMode = true;
  370. //addToRadio();
  371. bot_response = true;
  372. }
  373.  
  374. // !qr stands for queue related.
  375. if(checkMessage("!qr")) {
  376. let id = bot.getMedia().fkid;
  377. YT.related(id, 5, function(error, result) {
  378. if (error) throw error;
  379.  
  380. let video = result;
  381. //fileVideos(video);
  382. video.items.forEach(vid => {
  383. if(vid.id.videoId != undefined) {
  384. let vID = vid.id.videoId.toString();
  385. var vName = vid.snippet.title.toString();
  386. bot.queueMedia('youtube', vID);
  387. fs.appendFile("songsQueued.txt", vID + " name: " + vName + '\n' , (err) => {
  388. if(err){
  389. console.log(err);
  390. }
  391. });
  392. }
  393. });
  394. });
  395. bot.pauseQueue(false);
  396. bot_response = true;
  397. }
  398.  
  399. if(message == "!sign") {
  400. fs.appendFile("guestbook.txt", `${user} - ${new Date}\n`, () => {
  401. bot.sendChat(`Thankyou for signing the guestbook, ${user}!`)
  402. })
  403. }
  404.  
  405. }
  406. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement