Discord bot for fetching random cat images

Hey everyone! I’m working on a Discord bot that shows random cat pictures. I’ve managed to get the JSON data from an API, but I’m stuck on how to send the image in a Discord channel. Here’s what I’ve got so far:

const Discord = require('discord.js');
const axios = require('axios');

const bot = new Discord.Client();
const PREFIX = '!';
const CAT_API = 'https://api.thecatapi.com/v1/images/search';

bot.on('message', async (message) => {
  if (message.author.bot || !message.content.startsWith(PREFIX)) return;

  const command = message.content.slice(PREFIX.length).toLowerCase();

  if (command === 'kitty') {
    try {
      const response = await axios.get(CAT_API);
      console.log(response.data);
      // How do I send the image to the channel?
    } catch (error) {
      console.error('Error fetching cat image:', error);
    }
  }
});

bot.login('YOUR_BOT_TOKEN');

Can anyone help me figure out how to send the image using message.channel.send()? I’d really appreciate some guidance on this! Thanks in advance!

hey tom, i had similar issue. try this:

const catImg = response.data[0].url;
message.channel.send({ files: [catImg] });

this should send the image directly to the channel. lmk if it works for u!

I’ve implemented a similar feature in my Discord bot. Here’s what worked for me:

After fetching the API response, you can extract the image URL and send it as an embed. This method allows for a cleaner presentation and more customization options.

const embed = new Discord.MessageEmbed()
.setTitle(‘Random Cat’)
.setImage(response.data[0].url)
.setColor(‘#0099ff’);

message.channel.send({ embeds: [embed] });

This approach not only sends the image but also wraps it in an attractive embed with a title. You can further customize the embed by adding fields, a footer, or changing colors to match your bot’s theme.

Remember to import MessageEmbed from discord.js at the top of your file if you haven’t already.