Advertisement
artemisbot

Final Flips Code

Jul 24th, 2016
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*jshint esversion: 6 */
  2. /* jshint node: true */
  3. const webSocket = require('ws');
  4. const tmi = require('tmi.js');
  5. const fs = require('fs');
  6. const locallydb = require('locallydb');
  7. var db = new locallydb('./coinflipdb');
  8. var flipData = db.collection('currFlipsData');
  9. var options = {
  10.     options: {
  11.         debug: false
  12.     },
  13.     connection: {
  14.         cluster: "aws",
  15.         reconnect: true
  16.     },
  17.     identity: {
  18.         username: '#################',
  19.         password: 'oauth:##############'
  20.     },
  21.     channels: ['#onscreenlol', '#onscreenbot']
  22. };
  23.  
  24. var client = new tmi.client(options);
  25. var inPlay = [];
  26. var joinInProg = false;
  27. var firstJoin = true;
  28. client.connect();
  29. console.log('Coinflip bot is online.');
  30. client.on("join", function (channel, username, self) {
  31.     if (channel == "#onscreenlol" && firstJoin === true) {
  32.         client.say('#onscreenlol', 'Coinflip bot is online. Use "!coinflip help" to see commands.');
  33.         firstJoin = false;
  34.     }
  35. });
  36. client.on("chat", function(channel, user, message, self) {
  37.     var mesArray = message.split(" ");
  38.     var twitchUser = user.username;
  39.     var command = mesArray[1];
  40.     var entryGold = 0;
  41.     var joinedFlip = 0;
  42.     var currentDate = (new Date()).toString();
  43.     if (mesArray[0] == "!coinflip") {
  44.         console.log(`===================================================`);
  45.         console.log(`${twitchUser} sent a coinflip request: ${command}.`);
  46.         if (user.subscriber === true) {
  47.             if (command == "start" || command == "join") {
  48.                 deepbotFunc('get_points', twitchUser, null, function(goldString) {
  49.                     var gold = parseInt(goldString);
  50.                     console.log(`${twitchUser} has ${gold}.`);
  51.                     console.log(`Join in progress: ${joinInProg}.`);
  52.                     if (command == "start") {
  53.                         if (flipData.where({
  54.                                 starterName: twitchUser
  55.                             }).items.length === 0) {
  56.                             console.log('Coinflip start requested.');
  57.                             entryGold = Math.floor(parseInt(mesArray[2]));
  58.                             if (isNaN(entryGold) === false) {
  59.                                 team = mesArray[3].toLowerCase();
  60.                                 if (entryGold < 50) {
  61.                                     outputSend(channel, user, 'The minimum for a coinflip is 50 gold.');
  62.                                 } else {
  63.                                     if (gold < entryGold) {
  64.                                         outputSend(channel, user, 'You do not have enough gold to start this coinflip.');
  65.                                     } else {
  66.                                         if (team == "ct" || team == "t") {
  67.                                             deepbotFunc('add_to_escrow', twitchUser, entryGold, function(response) {
  68.                                                 newID(inPlay, function(flipID) {
  69.                                                     inPlay.push(flipID);
  70.                                                     console.log(inPlay);
  71.                                                     flipData.insert([{
  72.                                                         starterName: twitchUser,
  73.                                                         flipGold: entryGold,
  74.                                                         starterTeam: team,
  75.                                                         joinID: flipID
  76.                                                     }]);
  77.                                                     client.say('#onscreenlol', `Coinflip with ID ${flipID} has begun with ${twitchUser} for ${entryGold} gold on side ${team.toUpperCase()} - join with "!coinflip join ${flipID}".`);
  78.                                                     console.log(`Coinflip with ID ${flipID} has begun with ${twitchUser} for ${entryGold} gold on side ${team.toUpperCase()} - join with "!coinflip join ${flipID}".`);
  79.                                                 });
  80.                                             });
  81.                                         } else {
  82.                                             outputSend(channel, user, 'Team must be T or CT.');
  83.                                         }
  84.                                     }
  85.                                 }
  86.                             } else {
  87.                                 console.log('Entry Gold must be an integer.');
  88.                                 outputSend(channel, user, 'Entry Gold must be an integer.');
  89.                             }
  90.                         } else {
  91.                             outputSend(channel, user, 'You already have a coinflip in progress.');
  92.                         }
  93.                     } else if (command == "join" && joinInProg === false) {
  94.                         joinInProg = true;
  95.                         console.log('Coinflip join requested.');
  96.                         joinedFlipID = parseInt(mesArray[2]);
  97.                         joinedFlipData = flipData.where({
  98.                             joinID: joinedFlipID
  99.                         }).items[0];
  100.                         if (typeof joinedFlipData == 'object') {
  101.                             if (joinedFlipData.starterName != twitchUser) {
  102.                                 entryGold = joinedFlipData.flipGold;
  103.                                 if (joinedFlipData.starterTeam == 't') {
  104.                                     team = 'ct';
  105.                                 } else if (joinedFlipData.starterTeam == 'ct') {
  106.                                     team = "t";
  107.                                 }
  108.                                 if (gold >= entryGold) {
  109.                                     deepbotFunc('add_to_escrow', twitchUser, entryGold, function(response) {
  110.                                         result = (Math.floor(Math.random() * 2) === 0) ? 't' : 'ct';
  111.                                         winnerGold = Math.floor(entryGold * 2 * 0.95);
  112.                                         console.log(result);
  113.                                         opponent = joinedFlipData.starterName;
  114.                                         setTimeout(function() {
  115.                                             if (result == team) {
  116.                                                 client.say('#onscreenlol', `Coinflip with ID ${joinedFlipID} resulted in the coin landing on ${result.toUpperCase()}! It was won by ${twitchUser} defeating ${opponent}. The winner received ${winnerGold} gold.`);
  117.                                                 console.log(`Coinflip with ID ${joinedFlipID} resulted in the coin landing on ${result.toUpperCase()}! It was won by ${twitchUser} defeating ${opponent}. The winner received ${winnerGold} gold.`);
  118.                                                 deepbotFunc('commit_user_escrow', opponent, null, function(response) {
  119.                                                     deepbotFunc('commit_user_escrow', twitchUser, null, function(response) {
  120.                                                         deepbotFunc('add_points', twitchUser, winnerGold, function(response) {
  121.                                                             console.log('Transaction Complete.');
  122.                                                             flipData.remove(joinedFlipData.cid);
  123.                                                             inPlay.splice(inPlay.indexOf(joinedFlipID), 1);
  124.                                                             joinInProg = false;
  125.                                                         });
  126.                                                     });
  127.                                                 });
  128.                                             } else if (result == joinedFlipData.starterTeam) {
  129.                                                 client.say('#onscreenlol', `Coinflip with ID ${joinedFlipID} resulted in the coin landing on ${result.toUpperCase()}! It was won by ${opponent}, defeating ${twitchUser}. The winner received ${winnerGold} gold.`);
  130.                                                 console.log(`Coinflip with ID ${joinedFlipID} resulted in the coin landing on ${result.toUpperCase()}! It was won by ${opponent}, defeating ${twitchUser}. The winner received ${winnerGold} gold.`);
  131.                                                 deepbotFunc('commit_user_escrow', twitchUser, null, function(response) {
  132.                                                     deepbotFunc('commit_user_escrow', opponent, null, function(response) {
  133.                                                         deepbotFunc('add_points', opponent, winnerGold, function(response) {
  134.                                                             console.log('Transaction Complete.');
  135.                                                             flipData.remove(joinedFlipData.cid);
  136.                                                             inPlay.splice(inPlay.indexOf(joinedFlipID), 1);
  137.                                                             joinInProg = false;
  138.                                                         });
  139.                                                     });
  140.                                                 });
  141.                                             }
  142.                                         }, 2000);
  143.                                     });
  144.                                 } else {
  145.                                     outputSend(channel, user, 'You do not have enough gold to join this coinflip.');
  146.                                     joinInProg = false;
  147.                                 }
  148.                             } else {
  149.                                 outputSend(channel, user, 'You cannot join your own coinflip.');
  150.                             }
  151.                         } else {
  152.                             outputSend(channel, user, 'This coinflip does not exist.');
  153.                             joinInProg = false;
  154.                         }
  155.                     }
  156.                 });
  157.             } else if (command == "join" && joinInProg === true) {
  158.                 console.log('Join is currently in progress.');
  159.                 outputSend(channel, user, 'Join is currently in progress.');
  160.             } else if (command == "info") {
  161.                 console.log('Coinflip info requested.');
  162.                 selectedFlip = parseInt(mesArray[2]);
  163.                 selectedFlipData = flipData.where({
  164.                     joinID: selectedFlip
  165.                 }).items[0];
  166.                 if (typeof selectedFlipData == 'object') {
  167.                     outputSend(channel, user, `Coinflip ${selectedFlip} was created by ${selectedFlipData.starterName}. Entry is ${selectedFlipData.flipGold} and their chosen side was ${selectedFlipData.starterTeam.toUpperCase()}.`);
  168.                     console.log(`Message sent to ${twitchUser}: Coinflip ${selectedFlip} was created by ${selectedFlipData.starterName}. Entry is ${selectedFlipData.flipGold} and their chosen side was ${selectedFlipData.starterTeam.toUpperCase()}.`);
  169.                 } else {
  170.                     outputSend(channel, user, `The selected flip does not exist.`);
  171.                     console.log('The selected flip does not exist.');
  172.                 }
  173.             } else if (command == "help") {
  174.                 console.log('Coinflip help requested.');
  175.                 outputSend(channel, user, "Commands for coinflips: !coinflip start [gold] [t or ct] - starts a coinflip for a gold amount, with you on side T or CT; !coinflip join [flipID] - joins a coinflip with the matching id; !coinflip cancel [flipID] - allows some mods or the user who created the flip with that ID to cancel it; !coinflip info [flipID] - gives information on the selected flip; !coinflip list - list all in-progress coinflips.");
  176.             } else if (command == "list") {
  177.                 console.log('Coinflip list requested.');
  178.                 flipNumber = flipData.items.length;
  179.                 userOutput = "Flips currently in progress: ";
  180.                 if (flipNumber > 0) {
  181.                     for (var i=0; i < flipNumber; i++) {
  182.                         userOutput += `${i+1}: Flip ID - ${flipData.items[i].joinID}, Starter -  ${flipData.items[i].starterName}, Gold - ${flipData.items[i].flipGold}, Chosen Side - ${flipData.items[i].starterTeam.toUpperCase()}; `;
  183.                     }
  184.                     console.log(userOutput);
  185.                     outputSend(channel, user, `${userOutput.slice(0, -2)}.`);
  186.                 } else {
  187.                     outputSend(channel, user, 'There are no flips currently in progress.');
  188.                     console.log('There are no flips currently in progress.');
  189.                 }
  190.             } else if (command == "cancel") {
  191.                 console.log('Coinflip cancel requested.');
  192.                 selectedFlip = parseInt(mesArray[2]);
  193.                 selectedFlipData = flipData.where({
  194.                     joinID: selectedFlip
  195.                 }).items[0];
  196.                 if (typeof selectedFlipData == 'object')
  197.                     if (twitchUser == selectedFlipData.starterName || twitchUser == "artemisbot" || twitchUser == "deelmo" || twitchUser == "ilkleytom") {
  198.                         deepbotFunc('cancel_escrow', twitchUser, null, function(response) {
  199.                             flipData.remove(selectedFlipData.cid);
  200.                             client.say('#onscreenlol', `Coinflip with ID ${selectedFlip} has been cancelled.`);
  201.                             inPlay.splice(inPlay.indexOf(selectedFlip), 1);
  202.                             console.log(`Coinflip with ID ${selectedFlip} has been cancelled.`);
  203.                         });
  204.  
  205.                     } else {
  206.                         client.say('#onscreenlol', `You cannot delete another user's coinflip.`);
  207.                        console.log('User does not own coinflip.');
  208.                    }
  209.                else {
  210.                    outputSend(channel, user, 'The selected coinflip does not exist.');
  211.                    console.log('Unrecognised coinflip.');
  212.                }
  213.            } else if (command == "shutdown" && (twitchUser == "artemisbot" || twitchUser == "deelmo" || twitchUser == "ilkleytom")) {
  214.                client.say('#onscreenlol', 'Coinflip bot shutting down.....');
  215.                console.log('Bot Shutting Down.');
  216.                process.exit();
  217.            } else {
  218.                client.say('#onscreenlol', 'That command is unrecognised. Check !coinflip help.');
  219.                console.log('Unrecognised command.');
  220.            }
  221.        } else {
  222.            outputSend(channel, user, `Coinflips are a sub only system.`);
  223.            console.log('Plebs cannot do coinflips.');
  224.        }
  225.    }
  226.    flipData.save();
  227. });
  228.  
  229. // ============================= Global Functions =======================================
  230.  
  231. function outputSend(channel, user, msg) {
  232.    //console.log("Message sending...");
  233.    //console.log(user);
  234.    if (user['user-type'] == 'mod' || user['user-id'] == user['room-id'] || channel == '#onscreenbot') {
  235.        client.say(channel, user['display-name'] + ', ' + msg);
  236.    } else {
  237.        client.whisper(user['display-name'], msg);
  238.    }
  239. }
  240.  
  241. function newID(inPlay, cb) {
  242.    for (var i = 1; true; i++) {
  243.        if (inPlay.indexOf(i) < 0) {
  244.            break;
  245.        }
  246.    }
  247.    cb(i);
  248. }
  249.  
  250. function deepbotFunc(scope, param1, param2, cb) {
  251.    //console.log(cb);
  252.    param1 = param1 || null;
  253.    param2 = param2 || null;
  254.    var ws = new webSocket('ws://############:3337/');
  255.     ws.on('open', function() {
  256.         //console.log('sending API registration');
  257.         ws.send('api|register|##################');
  258.         //console.log('registration sent');
  259.         var noParam = ['get_song_count'];
  260.         var singleParam = ['get_points', 'cancel_escrow', 'commit_user_escrow'];
  261.         if (singleParam.indexOf(scope) >= 0) {
  262.             ws.send(`api|${scope}|${param1}`);
  263.         } else if (noParam.indexOf(scope) >= 0) {
  264.             ws.send(`api|${scope}`);
  265.         } else {
  266.             //console.log('sent request');
  267.             ws.send(`api|${scope}|${param1}|${param2}`);
  268.             //console.log('sent request');
  269.         }
  270.     });
  271.     ws.on('message', function(message) {
  272.         //console.log('message received')
  273.         //console.log(message)
  274.         messageParse = JSON.parse(message);
  275.         if (messageParse['function'] == 'register') {
  276.             //console.log('auth successful')
  277.         } else {
  278.             ws.terminate();
  279.             cb(messageParse.msg);
  280.         }
  281.     });
  282. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement