Jayy_N
Jayy_N

Reputation: 13

How would I get the content of a http request?

So I'm making a discord bot and I want it to display some stats. So I got the content from a website that I want to get it from, and I used the following code:

const Discord = require('discord.js');
var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
const {prefix,token} = require('./config.json');
const client = new Discord.Client()

function httpGet(theUrl)
{
    var xmlHttp = new XMLHttpRequest()
    xmlHttp.open( "GET", theUrl, false ); // false for synchronous request
    xmlHttp.send( null );
    return xmlHttp.responseText;
}

client.on('ready',() => {
    console.log('Bot ready!');
})

client.on('message',message => {
    if (message.content.startsWith(`${prefix}http`)) {
        let result = httpGet('https://games.roblox.com/v1/games/2012508359/favorites/count')
        message.channel.send(result)
        message.reply(`Still a WIP! ${message.member.user.tag}`);
    } 
})

client.login(token);

It works, but it displays like this:

{"favoritesCount":31219}

How would I make it so it just displays the number (31219) and not {"favoritesCount":31219}

Thanks!

Upvotes: 0

Views: 257

Answers (1)

stark
stark

Reputation: 409

Instead of passing result you need to return the key favoritesCount from result in your on message handler.

You can do this by modifying you on message handler as follow:

client.on('message',message => {
    if (message.content.startsWith(`${prefix}http`)) {
        let result = httpGet('https://games.roblox.com/v1/games/2012508359/favorites/count');
        const favoritesCount = JSON.parse(result).favoritesCount;
        message.channel.send(favoritesCount);
        message.reply(`Still a WIP! ${message.member.user.tag}`);
    } 
})

make sure you handle error response too before parsing

Upvotes: 2

Related Questions