I’m trying to create a Discord bot that can fetch and send random cat pictures. I’ve managed to get the JSON response from an API, but I’m stuck on how to actually 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('BOT_TOKEN');
Can someone help me figure out how to send the image using message.channel.send()
? I’d really appreciate some guidance on this!
hey man, i had the same issue. try using message.channel.send({ files: [response.data[0].url] }). that should work for sending the image. make sure ur bot has permissions to send attachments in the channel tho. good luck with ur kitty bot!
I’ve actually worked on a similar project before, and I can share what worked for me. After you get the response from the API, you’ll want to extract the image URL from the data. The Cat API typically returns an array with one object, and that object has a ‘url’ property.
Here’s how you can modify your code to send the image:
if (command === 'kitty') {
try {
const response = await axios.get(CAT_API);
const imageUrl = response.data[0].url;
await message.channel.send({ files: [imageUrl] });
} catch (error) {
console.error('Error fetching cat image:', error);
message.channel.send('Sorry, I couldn't fetch a cat image right now.');
}
}
This approach uses Discord.js’s ability to send files directly from URLs. It’s simple and works well for most cases. Just make sure your bot has the necessary permissions in the channel to send images. Hope this helps you get your kitty bot up and running!