Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

139
Views
Trying to get value from object using external url but

When i start bot console say:

Online with undefined/5

and when 10 secconds are passed give this error:

undefined:1 [object Promise] ^ SyntaxError: Unexpected token o in JSON at position 1

My Code:

let jogadores
client.on("ready", async () => {

async function players_online() {
    const response = fetch(`http://ip:port/dynamic.json`);
    const data = JSON.parse(response);
    jogadores = data.clients;


}

async function autoconnect() {

    if (jogadores === -1) {
        console.log('Offline');

    } else {
        console.log('Online with ' + jogadores + '/5')

    }
}
autoconnect()

setInterval(() => {
    client.user.setStatus('dnd');
    client.user.setActivity(`Online with ${jogadores} players.`, { type: 'PLAYING' })
    players_online()
}, 10000)

})
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You have quite some problems with your code. I will list them below:

Required fixes

  • As @about14sheep said, you must use await to get the actual response.
  • You are not supposed to use JSON.parse() on a response, but rather response.json() to get the JSON body.
  • Use of an incorrect operator, for numbers I'd suggest you use == than ===
  • Before 10 seconds have passed, it will show undefined. To fix this, call the function before the setInterval().

Optional things I added

  • Formatted JS code
  • Added semicolons when necessary
  • Used ES6 template literals feature
  • Removed async when un-needed

I have fixed all of these problems in the code below.

let jogadores;

client.on('ready', async () => {

    async function players_online() {
        const response = await fetch(`http://ip:port/dynamic.json`);
        const data = await response.json();
        jogadores = data.clients;
    }

    function autoconnect() {
        if (jogadores == -1) {
            console.log('Offline');
        } else {
            console.log(`Online with ${jogadores}/5`);
        }
    }

    autoconnect();
    players_online();

    setInterval(() => {
        client.user.setStatus('dnd');
        client.user.setActivity(`Online with ${jogadores} players.`, {
            type: 'PLAYING'
        });
    }, 10000);

});
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!