Skip to content

Random picture of cats discord.js Uncaught TypeError: Cannot read property ‘pipe’ of undefined

I am trying to make a bot that sends cat pictures from a cat API but when I run the code it gives an error that I have never seen.

var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
function randomcat(){
    let cat
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
      cat = this.responseText.split(`"`)[9]
  };
  xhttp.open("GET", "https://api.thecatapi.com/v1/images/search", true);
  xhttp.send();
  return cat
}
const Discord = require('discord.js');
const client = new Discord.Client();

client.on('message', async message=>{
console.log(randomcat());
message.channel.send("My Bot's message", {files: [randomcat()]});
})

When I run the code it returns Uncaught TypeError: Cannot read property 'pipe' of undefined.

Answer

Instead of the low-level xmlhttprequest you could use node-fetch to grab the response from the API. The API returns a JSON object as the response so you won’t need to fiddle around with responseText.splits etc.

With fetch, it’s pretty easy to get a response. Check out the snippet below:

async function getRandomCat() {
  const response = await fetch('https://api.thecatapi.com/v1/images/search');
  const json = await response.json();

  return json[0]?.url;
}

getRandomCat().then(img => console.log('1', img))
getRandomCat().then(img => console.log('2', img))
getRandomCat().then(img => console.log('3', img))

Your full code would look like this. Don’t forget to install node-fetch by running npm i node-fetch in your console.

Check out the working code below:

const fetch = require('node-fetch');

async function getRandomCat() {
  const response = await fetch('https://api.thecatapi.com/v1/images/search');
  const json = await response.json();

  return json[0]?.url;
}

client.on('message', async (message) => {
  if (message.author.bot) return;
  const args = message.content.slice(prefix.length).split(/ +/);
  const command = args.shift().toLowerCase();

  if (command === 'cat') {
    try {
      const cat = await getRandomCat();

      if (cat) return message.channel.send({ files: [cat] });
    } catch (error) {
      console.log(error);
      message.channel.send(
        'There was an error fetching your random cat. Try again later!',
      );
    }
  }
});

enter image description here