discord.js using axios: TypeError: Cannot read properties of undefined (reading 'ephemeral')

Viewed 29

I'm trying to make a GET request using Axios for my Discord bot, but I'm getting a problem.

The error:

TypeError: Cannot read properties of undefined (reading 'ephemeral')

I used the discordjs guide to create this bot and followed this tutorial for the Axios GET request.

The code:

const { SlashCommandBuilder } = require('discord.js');
const axios = require('axios');

module.exports = {
    data: new SlashCommandBuilder()
        .setName('cat2')
        .setDescription('Random cat'),
    async execute(interaction) {
        await interaction.reply(getRandomCat());
    },
};

function getRandomCat(){
    axios.get('https://api.thecatapi.com/v1/images/search')
    .then ((res) => {
        var data = res.data[0].url 
        console.log('res: ', data)
        return data               
})
    .catch((err) => {console.error('err: ', err)})
}

This command is used to get random pictures of a cat from the cat API. I'm just starting to know discord js so any help is welcome! Thanks in advance.

1 Answers

Try making getRandomCat an asynchronous function.

const { SlashCommandBuilder } = require('discord.js');
const axios = require('axios');

module.exports = {
    data: new SlashCommandBuilder()
        .setName('cat2')
        .setDescription('Random cat'),
    async execute(interaction) {
        await interaction.reply(await getRandomCat());
    },
};

async function getRandomCat(){
    const res = await axios.get('https://api.thecatapi.com/v1/images/search').catch(e => console.error);
    var data = res.data[0].url 
    console.log('res: ', data);
    return data;
}
Related