Search code examples
javascriptnode.jsdiscorddiscord.js

Discord.js v14 - Translating old Math.random() code for bot to change server icon periodically


I am trying to translate/update some old discord.js code I typed up a very long time ago (maybe in 2017/18) for a .js bot I was practicing code on. Essentially, what it used to do was change the guild icon periodically on one server I owned. It used an array and Math.random(). Here is some of the code I think that could be salvageable:

function changeGuildIcon(guild) {
  var icons = new Array();

  icons[0] = "https://cdn.glitch.com/221cf221-9488-4246-bae1-269b2e87266f%2Fquack1.jpg?1546874576807";
  icons[1] = "https://cdn.glitch.com/221cf221-9488-4246-bae1-269b2e87266f%2Fquack2.png?1546874572153";
  icons[2] = "https://cdn.glitch.com/221cf221-9488-4246-bae1-269b2e87266f%2Fquack3.png?1546874572398";
  icons[3] = "https://cdn.glitch.com/221cf221-9488-4246-bae1-269b2e87266f%2Fquack4.png?1546874572493";
  icons[4] = "https://cdn.glitch.com/221cf221-9488-4246-bae1-269b2e87266f%2Fquack5.png?1546874573152";

  function shuffle(a) {
    var j, x, i; //var is important
    for (i = a.length - 1; i > 0; i--) {
      j = Math.floor(Math.random() * (i + 1));
      x = a[i];
      a[i] = a[j];
      a[j] = x;
    }
    return a;
  }

  var icons_shuffle = shuffle(icons);

  console.log(icons_shuffle);

  var iconsans = icons_shuffle[icons_shuffle.length - 1];
  icons_shuffle.pop();

  guild.setIcon(iconsans).then(console.log).catch(console.error);
}

client.on("ready", () => {
  let guild = client.guilds.get("242786073040781322");
  setInterval(
    changeGuildIcon,
    1000 /* < milliseconds */ * 60 /* < seconds */ * 60 /* < minutes */,
    guild
  );
});

I can't remember what version of discord.js I used for this however I had it written all in one long main.js file with many other commands split by else if statements.

How could I get this to work again automatically whilst my discord bot is online and what do I add before calling these functions to work as an event?

Any suggestions/resources would be very appreciated, thanks!


Solution

  • Following LarryTLlama's suggestions, I made the following additions & changes:

    const client = require("../../index.js");
    const { Client, GatewayIntentBits } = require('discord.js');
    
    function changeGuildIcon(guild, interaction) {
      var icons = new Array();
    
    

    and

    
      var icons_shuffle = shuffle(icons);
    
      //console.log(icons_shuffle);
    
      var iconsans = icons_shuffle[icons_shuffle.length - 1];
      icons_shuffle.pop();
    
      guild.setIcon(iconsans)/*.then(console.log).catch(console.error)*/;
    }
    
    client.on("ready", () => {
      let guild = client.guilds.cache.get("242786073040781322");
      setInterval(
        changeGuildIcon,
        1000 /* < milliseconds */ * 60 /* < seconds */ * 30 /* < minutes */,
        guild
      );
    });
    

    seemed to have done the trick. Thanks.