Advertisement
dragonfree97

Untitled

Apr 11th, 2020
444
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const fs = require('fs');
  2. const Discord = require('discord.js');
  3. const Utils = require('../../modules/utils.js');
  4.  
  5. const cards = require('../../resources/cards/dat/cards.json');
  6. const dailyTimestamp = require("../../resources/cards/dat/dailytimeouts.json");
  7.  
  8. const colour = 0x6A62A7;
  9. const colour_error = 0xFF0000;
  10. const cardslocation = "./resources/cards/img/";
  11. const inventorylocation = "./resources/cards/inv/";
  12. const logolocation = "./resources/cards/logo.png";
  13.  
  14. const sets = [
  15.         'Golden Age of Pod',
  16.         'Weebshit',
  17.         'Chatroom Classics',
  18.         'Skype Classics',
  19.         'Utter Nonsense',
  20.         'Modern Achat',
  21.         'Trolls and Scrubs',
  22.         'Achat IRL',
  23.         'Original Characters',
  24.         'Obscurities'
  25.     ];
  26.    
  27. const year_colours = {
  28.     "2010": 0xFA0000,
  29.     "2013": 0xFA8108,
  30.     "2014": 0xFAEA0A,
  31.     "2015": 0x0FE000,
  32.     "2016": 0x00EEFF,
  33.     "2017": 0x0000FF,
  34.     "2018": 0x7B08FF,
  35.     "2019": 0xBF0FFF,
  36.     "2020": 0xFF0FFF
  37. }
  38.  
  39. const CURRENTLY_AVAILABLE = 301;
  40. const DAILY_CARDS = 5;
  41.  
  42. var errorEmbed = function(title, description) {
  43.     var emb = new Discord.RichEmbed()
  44.         .setColor(colour_error)
  45.         .setTitle(title);
  46.     if(description) {
  47.         emb.setDescription(description);
  48.     }
  49.     return emb;
  50. }
  51.  
  52. var moreThanADayAgo = function(year, month, date) {
  53.     var d = new Date();
  54.     if (year > d.getFullYear()) {
  55.         return false;
  56.     }
  57.     if (month > d.getMonth()+1) {
  58.         return false;
  59.     }
  60.     if (date > d.getDate()) {
  61.         return false;
  62.     }
  63.     if (year == d.getFullYear() && month == d.getMonth()+1 && date == d.getDate()) {
  64.         return false;
  65.     }
  66.     return true;
  67. }
  68.  
  69. var getCardByName = function(name) {
  70.     for (var i = 0; i < cards.length; i++) {
  71.         if (cards[i].name == name) {
  72.             return i;
  73.         }
  74.     }
  75.     return false;
  76. }
  77.  
  78. var upFirst = function(str) {
  79.     return str.charAt(0).toUpperCase() + str.slice(1);
  80. };
  81.  
  82. var formatStat = function(num) {
  83.     if (num > 0) {
  84.         return "+"+num;
  85.     } else {
  86.         return num;
  87.     }
  88. };
  89.  
  90. var getFilename = function(index) {
  91.     var filename = cardslocation+index+".png";
  92.     var filename_attached = "attachment://"+index+".png";
  93.    
  94.     if (!fs.existsSync(filename)) {
  95.         filename = cardslocation+index+".gif";
  96.         filename_attached = "attachment://"+index+".gif";
  97.     }
  98.    
  99.     if (!fs.existsSync(filename)) {
  100.         filename = cardslocation+index+".jpg";
  101.         filename_attached = "attachment://"+index+".jpg";
  102.     }
  103.    
  104.     if (!fs.existsSync(filename)) {
  105.         filename = './resources/cards/logo.png';
  106.         filename_attached = "attachment://logo.png";
  107.     }
  108.     return { "fn": filename, "fn_a": filename_attached };
  109. }
  110.  
  111. var getInv = function(u) {
  112.     var user = u.id;
  113.     var inv = {};
  114.     var filelocation = inventorylocation+user+'.json';
  115.     if (fs.existsSync(filelocation)) {
  116.         delete require.cache[require.resolve("../."+filelocation)];
  117.         inv = require("../."+filelocation);
  118.     } else {
  119.         fs.copyFileSync(inventorylocation+"_default.json", filelocation);
  120.         delete require.cache[require.resolve("../."+filelocation)];
  121.         inv = require("../."+filelocation);
  122.     }
  123.     return inv;
  124. }
  125.  
  126. var lookup = function(message, args, props) {
  127.     if (args.length == 1) {
  128.         return message.channel.send(errorEmbed("Please specify a card."));
  129.     }
  130.    
  131.     var card = args[1];
  132.    
  133.     var inventory = getInv(message.author);
  134.     var c = false;
  135.     var index;
  136.    
  137.     if (args.length > 2) {
  138.         args = [args[0], (function() {
  139.             args.shift();
  140.             return args;
  141.         })().join("")];
  142.         console.log(args);
  143.     }
  144.    
  145.     // do a search
  146.     if(isNaN(args[1])) {
  147.         var searchstring = "";
  148.         for (var i = 1; i<args.length; i++) {
  149.             searchstring += args[i];
  150.         }
  151.         searchstring = searchstring.toLowerCase().replace(/[^\w\s]|_/g, "").replace(/\s+/g, "");
  152.         console.log(searchstring)
  153.         var matchFound = false;
  154.         for (var i = 1; i < cards.length; i++) {
  155.             if(!matchFound) {
  156.                 var result = cards[i];
  157.                 var cardname = cards[i].name.toLowerCase().replace(/[^\w\s]|_/g, "").replace(/\s+/g, "")
  158.                 console.log(searchstring + " / " + cardname);
  159.                 if (cardname.indexOf(searchstring) != -1) {
  160.                     var search_index = ("000" + i.toString()).slice(-3);
  161.                     // Card has matched our string. Now we check if it's in our dex, else we'll reject
  162.                     if (inventory[search_index]) {
  163.                         if (inventory[search_index].dex) {
  164.                             // bingo
  165.                             c = result;
  166.                             index = search_index;
  167.                             matchFound = true;
  168.                             console.log("Matched "+cardname);
  169.                         }
  170.                     }
  171.                 }
  172.             }
  173.         }
  174.         if (!c) {
  175.             return message.channel.send(errorEmbed("No results in your CardDex for "+searchstring));
  176.         }
  177.     }
  178.    
  179.     if (!c) {
  180.         c = cards[Number(card)];
  181.         index = ("000" + card.toString()).slice(-3);
  182.     }
  183.  
  184.     if (message.guild.id != "455814567298072597") {
  185.         if (!inventory[index].dex) {
  186.             var err = new Discord.RichEmbed()
  187.                 .setColor(colour_error)
  188.                 .setTitle("You can't look at a card you've never owned.");
  189.            
  190.             return message.channel.send(err);
  191.         }
  192.     }
  193.    
  194.     var fn = getFilename(index);
  195.    
  196.     try {
  197.         var emb = new Discord.RichEmbed()
  198.             .attachFiles([fn.fn])
  199.             .setThumbnail(fn.fn_a)
  200.             .setColor(year_colours[c.year])
  201.             .setTitle("#" + index + " — " + c.name)
  202.             .setDescription('*"'+c.quote+'"*')
  203.             .addField("Year", c.year, true)
  204.             .addField("Set", sets[c.set], true)
  205.             .addField('\u200B', '\u200B', true);
  206.         for (var stat in c.stats) {
  207.             emb.addField(upFirst(stat), formatStat(c.stats[stat]), true);
  208.         }
  209.         return message.channel.send(emb);
  210.     } catch (err) {
  211.         console.log(err);
  212.     }
  213. };
  214.  
  215. var showInventory = function (player) {
  216.     var inventory = getInv(player);
  217.     var myCards = [];
  218.    
  219.     var emb = new Discord.RichEmbed()
  220.         .setColor(colour)
  221.         .setTitle(player.username+"'s Collection")
  222.         .attachFiles([logolocation])
  223.         .setThumbnail("attachment://logo.png");
  224.        
  225.     var set = function(n) {
  226.         return (Math.floor((n-1)/25)*25)+25;
  227.     }
  228.    
  229.     var sets = {
  230.         "25" : "",
  231.         "50" : "",
  232.         "75" : "",
  233.         "100" : "",
  234.         "125" : "",
  235.         "150" : "",
  236.         "175" : "",
  237.         "200" : "",
  238.         "225" : "",
  239.         "250" : "",
  240.         "275" : "",
  241.         "300" : "",
  242.         "325" : "",
  243.         "350" : "",
  244.         "375" : "",
  245.         "400" : ""
  246.     }
  247.    
  248.     for (card in inventory) {
  249.         if (inventory[card].num > 0) {
  250.             var name = cards[Number(card)].name;
  251.             if (name == name.replace(/^(.{14}[^\s]*).*/, "$1")) {
  252.                 var text = "#"+card+" **" + name + "** (×"+inventory[card].num+"), ";
  253.             } else {
  254.                 var text = "#"+card+" **" + name.replace(/^(.{14}[^\s]*).*/, "$1...") + "** (×"+inventory[card].num+"), ";
  255.             }
  256.             sets[set(card).toString()] = sets[set(card)] + text;
  257.         }
  258.     }
  259.    
  260.     var fields_added = 0;
  261.     for (s in sets) {
  262.         if(sets[s]) {
  263.             emb.addField((s-24) + " — " + s, sets[s].slice(0,-2));
  264.             fields_added++;
  265.         }
  266.     }
  267.    
  268.     if(!fields_added) {
  269.         emb.setDescription("You don't have any cards! Collect some with `m!card`");
  270.     }
  271.    
  272.     return emb;
  273. }
  274.  
  275. var showDex = function (message) {
  276.     var inventory = getInv(message.author);
  277.     var myCards = [];
  278.     for (card in inventory) {
  279.         if (inventory[card].dex == true) {
  280.             myCards.push(card);
  281.         }
  282.     }
  283.    
  284.     var descr = "";
  285.     for (var i = 1; i < CURRENTLY_AVAILABLE+1; i++) {
  286.         var index = ("000" + i.toString()).slice(-3);
  287.         if(inventory[index]) {
  288.             if (inventory[index.toString()].num > 1) {
  289.                 if (myCards.includes(index)) {
  290.                     descr += " **__"+index+"__** "
  291.                 } else {
  292.                     descr += "__" + index + "__ ";
  293.                 }
  294.             } else {
  295.                 if (myCards.includes(index)) {
  296.                     descr += " **"+index+"** "
  297.                 } else {
  298.                     descr += "" + index + " ";
  299.                 }
  300.             }
  301.         } else {
  302.             descr += "" + index + " ";
  303.         }
  304.            
  305.     }
  306.    
  307.     var emb = new Discord.RichEmbed()
  308.         .setColor(colour)
  309.         .setTitle(message.author.username+"'s CardDex")
  310.         .attachFiles([logolocation])
  311.         .setThumbnail("attachment://logo.png")
  312.         .setDescription(descr)
  313.         .addField("Total", myCards.length+"/"+CURRENTLY_AVAILABLE, true)
  314.         .addField("Percentage complete", Math.floor((100*myCards.length)/CURRENTLY_AVAILABLE)+"%", true);
  315.    
  316.     return message.channel.send(emb);
  317. }
  318.  
  319. var verifyTrade = async function (message, card, recipient) {
  320.    
  321.     var recipientInventory = getInv(recipient);
  322.     var index = ("000" + getCardByName(card.name)).slice(-3)
  323.    
  324.     var isNew = false;
  325.     if(!recipientInventory[index]) {
  326.         isNew = true;
  327.     } else if (!recipientInventory[index].dex) {
  328.         isNew = true;
  329.     }
  330.    
  331.     var fn = getFilename(index);
  332.    
  333.     var success = new Discord.RichEmbed()
  334.         .setColor(colour)
  335.         .setTitle(recipient.username+", you received a card from "+message.author.username+"!")
  336.         .attachFiles([fn.fn])
  337.         .setThumbnail(fn.fn_a)
  338.     if(isNew) {
  339.         success.setDescription("<@!"+recipient.id+">, "+message.author.username+" has sent you a copy of **"+card.name+"** (#"+index+")! Congratulations! That's a new card for you!");
  340.     } else {
  341.         success.setDescription("<@!"+recipient.id+">, "+message.author.username+" has sent you a copy of **"+card.name+"** (#"+index+")!");
  342.     }
  343.    
  344.    
  345.     var trade = new Promise((resolve, reject) => {
  346.         var emb = new Discord.RichEmbed()
  347.             .setColor(colour)
  348.             .setTitle("Sending a card to "+recipient.username)
  349.             .setDescription("You're sending one copy of **"+card.name+"** (#"+("000" + getCardByName(card.name)).slice(-3)+"). Are you sure? React with a ✅ to send, ❌ to cancel. This will time out in 60 seconds.")
  350.             .attachFiles([fn.fn])
  351.             .setThumbnail(fn.fn_a);
  352.            
  353.         message.channel.send(emb)
  354.             .then((msg) => {
  355.                 msg.react("✅");
  356.                 msg.react("❌");
  357.                
  358.                 var filter = (reaction, user) => {
  359.                     return ['✅', '❌'].includes(reaction.emoji.name) && user.id === message.author.id;
  360.                 };
  361.                 var collector = new Discord.ReactionCollector(msg, filter, { max: 1, time: 60000 });
  362.                
  363.                 collector.on('collect', reaction => {
  364.                     collector.stop(reaction.emoji);
  365.                 });
  366.                
  367.                 collector.on('end', (collected, reason) => {
  368.                     console.log(reason);
  369.                     if(reason == "time") {
  370.                         var reply = errorEmbed("Trade with "+recipient.username+" timed out.")
  371.                         reply.setThumbnail();
  372.                         msg.edit(reply);
  373.                         resolve(false);
  374.                     } else if (reason.name == "✅") {
  375.                         msg.edit(success);
  376.                         resolve(true);
  377.                     } else {
  378.                         var reply = errorEmbed("Trade with "+recipient.username+" cancelled.")
  379.                         reply.setThumbnail();
  380.                         msg.edit(reply);
  381.                         resolve(false);
  382.                     }
  383.                 });
  384.                
  385.                
  386.             }).catch((err) => {
  387.                 console.log(err);
  388.             });
  389.     });
  390.    
  391.     let result = await trade;
  392.     return result;
  393. }
  394.  
  395. var trade = function (message, args, props) {
  396.    
  397.     // Is it a valid card?
  398.    
  399.     if(!args[1] || !args[1].match(/^(?:[0-9]{1,3})$/) || args[1] < 0 || args[1] > CURRENTLY_AVAILABLE) {
  400.         return message.channel.send(errorEmbed("You must provide a valid card."));
  401.     }
  402.    
  403.     var card = args[1];
  404.     var c = cards[Number(card)];
  405.     var index = ("000" + card.toString()).slice(-3);
  406.     var inventory = getInv(message.author);
  407.    
  408.     // Check if the player has it
  409.    
  410.     if(!inventory[index]) {
  411.         return message.channel.send(errorEmbed("You don't have this card!"));
  412.     }
  413.     if (inventory[index.toString()].num < 1) {
  414.         return message.channel.send(errorEmbed("You don't have this card!"));
  415.     }
  416.    
  417.     // save the DM with the user we're going to send a
  418.    
  419.     var recipient = message.mentions.users.first();
  420.    
  421.     if (recipient.id == message.author.id) {
  422.         return message.channel.send(errorEmbed("You can't send a card to yourself!"));
  423.     }
  424.    
  425.     var rec_inventory = getInv(recipient);
  426.    
  427.     verifyTrade(message, c, recipient)
  428.         .then((result) => {
  429.             if(result) {
  430.                 inventory[index].num--;
  431.                 if(!rec_inventory[index]) {
  432.                     rec_inventory[index] = {
  433.                         num: 0,
  434.                         dex: false
  435.                     }
  436.                 }
  437.                 rec_inventory[index].num++;
  438.                 rec_inventory[index].dex = true;
  439.                 fs.writeFile(inventorylocation+message.author.id+'.json', JSON.stringify(inventory, null, "\t"));
  440.                 fs.writeFile(inventorylocation+recipient.id+'.json', JSON.stringify(rec_inventory, null, "\t"));
  441.             }
  442.         }).catch((err) => {
  443.             console.log(err);
  444.         });
  445.    
  446. }
  447.  
  448. var dailies = function (message, args, props) {
  449.     //Enable this line to disable Dailies in Animal Chat
  450.     // if (message.guild.id != "455814567298072597") { return; }
  451.    
  452.     var user = message.author.id;
  453.     var inventory = getInv(message.author);
  454.    
  455.     if(!dailyTimestamp[user]) {
  456.         dailyTimestamp[user] = {
  457.             "year": 0,
  458.             "month": 0,
  459.             "date": 0
  460.         };
  461.     }
  462.    
  463.     var now = new Date();
  464.    
  465.     // this if statement lets us bypass the daily limit in the test server for debugging purposes
  466.     if (message.guild.id != "455814567298072597") {
  467.         if (!moreThanADayAgo(dailyTimestamp[user].year, dailyTimestamp[user].month+1, dailyTimestamp[user].date)) {
  468.             var tomorrow = new Date(now.getFullYear()+"-"+(now.getMonth()+1)+"-"+now.getDate());
  469.             tomorrow.setDate(tomorrow.getDate() + 1);
  470.            
  471.             var offset = ((tomorrow.getTime() - now.getTime())/1000);
  472.             var offsetDescr = "It will be ready in "+Math.floor(offset/3600)+" hours, "+Math.floor((offset%3600)/60)+" minutes, "+Math.floor((offset%3600)%60)+" seconds.";
  473.             return errorEmbed(message, "Your trading card pack for today isn't ready yet!", offsetDescr);
  474.         }
  475.     }
  476.    
  477.     var emb = new Discord.RichEmbed()
  478.         .setColor(colour)
  479.         .setDescription("Here's what you received! Remember you can look at a specific card with `m!card v NUMBER`.")
  480.         .setTitle(message.author.username + ", here's today's trading card pack!");
  481.    
  482.     for (var i = 0; i < DAILY_CARDS; i++) {
  483.         var card = Utils.iRandom(1, CURRENTLY_AVAILABLE);
  484.         var index = ("000" + card.toString()).slice(-3);
  485.         if (i == 0) {
  486.             var fn = getFilename(index);
  487.             emb.attachFiles([fn.fn]).setThumbnail(fn.fn_a);
  488.         }
  489.         c = cards[card];
  490.         emb.addField("Card "+(i+1), "#" + index + " — **" + c.name + "**");
  491.         if(!inventory[index]) {
  492.             inventory[index] = { "num": 0, "dex": false }
  493.         }
  494.         inventory[index].num++;
  495.         if(!inventory[index].dex) {
  496.             inventory[index].dex = true;
  497.         }
  498.     }
  499.    
  500.     dailyTimestamp[user] = {
  501.         "year": now.getFullYear(),
  502.         "month": now.getMonth(),
  503.         "date": now.getDate()
  504.     }
  505.    
  506.     fs.writeFile("./resources/cards/dat/dailytimeouts.json", JSON.stringify(dailyTimestamp, null, "\t"));
  507.     fs.writeFile(inventorylocation+user+'.json', JSON.stringify(inventory, null, "\t"));
  508.    
  509.     return message.channel.send(emb);  
  510. };
  511.  
  512. var help = function(message, args, props) {
  513.     var emb = new Discord.RichEmbed()
  514.         .setColor(colour)
  515.         .setTitle("Achat Cards")
  516.         .attachFiles([logolocation])
  517.         .setThumbnail("attachment://logo.png")
  518.         .addField("Receiving your daily cards", "At midnight UK time (7pm Eastern), you can claim new cards. Every day, you'll get 5 new cards. Claim new cards by typing `m!card`.")
  519.         .addField("Giving cards to your friends", "You can give cards to your friends by typing `m!card t 001 @friend`. Replace 001 with the number of a card, and @friend with a mention of your friend. You can give as many cards as you want per day, but you can't give away cards you don't own.")
  520.         .addField("Checking your inventory", "Check your inventory with `m!card i`.")
  521.         .addField("Checking your CardDex", "Check your CardDex with `m!card d`. Bolded numbers represent cards you own; underlined numbers represent cards you own and have more than one of. The objective of the game is to collect all "+CURRENTLY_AVAILABLE+" cards.")
  522.         .addField("Viewing a card", "You can view a card that's registered in your CardDex by typing `m!card v 001`, replacing 001 with the name or number of the card you want to look at. You don't have to currently own the card to look at it, you just have to have had it at least once in the past.");
  523.    
  524.     message.channel.send(emb);
  525. }
  526.  
  527. module.exports = {
  528.     "name": "cards",
  529.     "desc": "cards",
  530.     "func": function (message, args, props) {
  531.         var serverid = message.guild.id;
  532.         if (serverid!="151108533109260288"&&serverid!="360586476842385409"&&serverid!="455814567298072597"&&serverid!="221826269086613504") {
  533.             // achat, meteorcraft, test server, dachis
  534.             return;
  535.         }
  536.        
  537.         switch (args[0]) {
  538.             case "inventory":
  539.             case "inv":
  540.             case "i":
  541.                 return message.channel.send(showInventory(message.author));
  542.             case "dex":
  543.             case "d":
  544.                 return showDex(message, args, props);
  545.             case "trade":
  546.             case "t":
  547.                 return trade(message, args, props);
  548.             case "lookup":
  549.             case "look":
  550.             case "info":
  551.             case "view":
  552.             case "v":
  553.                 return lookup(message, args, props);
  554.             case "list":
  555.                 return message.channel.send("List of all cards\nWarning: contains spoilers!\nhttps://pastebin.com/raw/65Jwukxy");
  556.             case "help":
  557.             case "h":
  558.                 return help(message, args, props);
  559.             default:
  560.                 return dailies(message, args, props);
  561.         }
  562.        
  563.        
  564.     }
  565. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement