Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

244
Visualizações
Discord JS bot how to make a recursive async function fetching from API

I am trying to make a discord bot. I want it to fetch an API every X seconds and check for new topics created.

The API JSON contains just one object, the latest post on the site. I wanted the bot to fetch every X seconds and if the latest post found has a bigger uid to send a message in a channel. If not do nothing. The uid is a number.

Tried to use the setInterval function but could not get it to work as it gave out errors that await needs to be in a top async function.

I also hardcoded the latest post uid "latest_post" and the way I saw it working is if post_id from API is higher that the hardcoded one then hardcoded one receives the value of the new one. However latest_post's value remains unchanged as the function is executed again and lates_post is hardcoded every time. Tried to declare it outside the function but came out as undefined.

This is my current almost working code

client.on('messageCreate', async (message) => {
    if (!message.content.startsWith(prefix) || message.author.bot) return;    
    const args = message.content.slice(prefix.length).split(/ +/);
    const command = args.shift().toLowerCase();
    if (command === 'new') {
        var latest_post = 12345; // hardcoded latest post uid 
      try {
        const response = await fetch('API HERE').then(r => r.text()); 
        const body = JSON.parse(response);
        const obj = body.data;
        const objId = obj[0].post_id; 
        const objAuthor = obj[0].author;
        const objTitle = obj[0].title;    

        if (objTopic > latest_post) {

          client.channels.cache.get("CHANNEL ID").send(`Found a new post by ${objAuthor}`);              
        var latest_post = objId; // if it fetches a post with a higher uid then latest_post receives the value of that higher uid
        } else {

          var d = new Date();
          var n = d.toLocaleTimeString();
          console.log(`No new posts yet at ${n}`); //logs "No new posts yet at 1:30 PM"
        }

      } catch (error) {
        message.channel.send('Oops, there was an error fetching the API');
        console.log(error);
      }
    }
  });

Can anyone guide me how to transform this in a recursive function that runs automatically every X seconds. Thanks !

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

After some iterations managed to make it work the way I wanted. Will leave the code below, hope it helps!

  let refreshint = 10 * 1000;  //10 seconds
  var API = "API_HERE";

  client.on('ready', async (message) => {
  console.log('Bot is connected...');

  var latest_post = 12345 // hardcoded latest post uid 
  setInterval(async function(){

      try {
        const response = await fetch('API').then(r => r.text()); 
        const body = JSON.parse(response);
        const obj = body.data;
        const objId = obj[0].post_id; 
        const objAuthor = obj[0].author;
        const objTitle = obj[0].title;

        if (objTopic > latest_post)              

          client.channels.cache.get("CHANNEL ID").send(`Found a new post by ${objAuthor}`); 

         console.log(`Found a new post by ${objAuthor}`);
            function change_value(latest_post){
            return latest_post;
            }
          latest_post = change_value(topicId);

        } else {
          var d = new Date();
          var n = d.toLocaleTimeString();
          console.log(`No new thread yet at ${n}`);
        }

      } catch (error) {
        message.channels.cache.get('channel ID here').send('Oops, there was an error fetching the API');
        console.log(error);
      }

  }, refreshint) });
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda