3

In my Discord Bot that I am making, it needs to select a random object from a JSON file. My current code is this:

    function spawn(){
        if (randomNum === 24) return
        const name = names.randomNum
        const embed = new Discord.RichEmbed()
        .setTitle(`${name} has been found!`)
        .setColor(0x00AE86)
        .setThumbnail(`attachment://./sprites/${randomNum}.png`)
        .setTimestamp()
        .addField("Quick! Capture it with `>capture`!")
        msg.channel.send({embed});
    }

The JSON file looks like this:

{
    "311": "Blargon",
    "310": "Xryzoz",
    "303": "Noot",
    "279": "",
    "312": "Arragn",
    "35": "Qeud",
    ...
}

I want it to pick a random one of those, such as 303, and post it in a rich embed. What do I do from here?

2

3 Answers 3

7

You can select a random name like this:

// Create array of object keys, ["311", "310", ...]
const keys = Object.keys(names)

// Generate random index based on number of keys
const randIndex = Math.floor(Math.random() * keys.length)

// Select a key from the array of keys using the random index
const randKey = keys[randIndex]

// Use the key to get the corresponding name from the "names" object
const name = names[randKey]

// ...
Sign up to request clarification or add additional context in comments.

Comments

3

const jsonData = {
    "311": "Blargon",
    "310": "Xryzoz",
    "303": "Noot",
    "279": "",
    "312": "Arragn",
    "35": "Qeud",
}
const values = Object.values(jsonData)

const randomValue = values[parseInt(Math.random() * values.length)]

console.log(randomValue)

Comments

0

This can be done in two steps

Loading Json file using Javascript and local server

1> Create a Json file, name it botNames.json, add your data.

Note: .json files can only contain Json Object, Array or Json literal

{
    "311": "Blargon",
    "310": "Xryzoz",
    "303": "Noot",
    "279": "",
    "312": "Arragn",
    "35": "Qeud"
}

Use XMLHttpRequest() to load the data, you can use below function to load the .json file passing a callback function and the path as an argument.

function loadJSON(callback,url) {   
  var xobj = new XMLHttpRequest();
  xobj.overrideMimeType("application/json");
  xobj.open('GET', url, true); 
  xobj.onreadystatechange = function () {
        if (xobj.readyState == 4 && xobj.status == "200") {
          callback(xobj.responseText);
        }
  };
  xobj.send(null);
}

To generate a random index you can use the below expression

Math.floor(lowerLimt + (upperLimit - lowerLimit+1)*Math.Random())

this will give you values in the range [lowerLimit,upperLimit)

Note: This is possible because Math.random() generates a fractional number in the range [0,1)

Your callback function will be

function callback1(response){
        var botNames = JSON.parse(response)
        var keys = Object.keys(botNames);
        var randomProperty = keys[Math.floor(keys.length*Math.random())]
        var botName = botNames[randomProperty]
        console.log(botName);
    }

You can use above concepts in your code as

function loadJSON(callback,url) {   
    var xobj = new XMLHttpRequest();
    xobj.overrideMimeType("application/json");
    xobj.open('GET', url, true); 
    xobj.onreadystatechange = function () {
            if (xobj.readyState == 4 && xobj.status == "200") {
            // sending the resonse to your callback
            callback(xobj.responseText);
            }
    };
    xobj.send(null);
}

function spawn(){
        loadJSON(function(response){
          //This is your callback function

          var names = JSON.parse(response)
          var keys = Object.keys(botNames);
          var randomNum = keys[Math.floor(keys.length*Math.random())]
            
          if (randomNum === 24) return
          const name = names[randomNum]
          const embed = new Discord.RichEmbed()
          .setTitle(`${name} has been found!`)
          .setColor(0x00AE86)
          .setThumbnail(`attachment://./sprites/${randomNum}.png`)
          .setTimestamp()
          .addField("Quick! Capture it with `>capture`!")
          msg.channel.send({embed});
        },'/PATH_TO_YOUR_JSON/botNames.json')
    }

4 Comments

I tried what you did there, and I got this error: TypeError: xobj.overrideMimeType is not a function
It works for me, I tried with python and nodeJs servers, in Chrome,IE. Can you give some inputs like which server, browser and software versions you are using? I got a post on similar problem, posted yesterday stackoverflow.com/questions/49675273/…
Info Across the internet: If using IE, It is only supported in IE11 and later. You can omit that line, it will still work, with the default server provided MIME type eg. 'text/plain'
One more alternative you can safe guard it by using if (xobj.overrideMimeType) { xobj.overrideMimeType( 'application/json' ); }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.