Fetching gifs from the Tenor API

Advertisements

I’m having issues fetching any gifs from the Tenor API – I’ve also tried to use tenor.googleapis.com.

But so far, I’ve gotten this error over and over again:
Sorry, no media found in the search result

Here’s the code I’ve worked with:

client.on('interactionCreate', async (interaction) => {
  if (!interaction.isCommand()) return;

  if (interaction.commandName === 'cat') {
    const api_key = 'API_KEY';
    const search_term = 'kitty';
    const limit = 50;
    const url = `https://tenor.googleapis.com/v2/search?q=${search_term}&key=${api_key}&limit=${limit}`;
    const command = `curl --request GET ${url}`;

    try {
      const response = await axios({
        method: 'GET',
        url: url,
        headers: {
          'User-Agent': 'PostmanRuntime/7.28.4'
        }
      });
      const data = response.data;
      if (!data.results || data.results.length === 0) {
        console.log('Sorry, no results found for kitty review');
        await interaction.reply('Sorry, no results found for kitty review');
        return;
      }
      const index = Math.floor(Math.random() * data.results.length);
      const result = data.results[index];
      const gif = result.gif && result.gif.url;
      if (!gif) {
        console.log('Sorry, no gif URL found in the search result');
        await interaction.reply('Sorry, no gif URL found in the search result');
        return;
      }
      console.log(`Found kitty review: ${gif}`);

      // send the gif in an embed
      const embed = new MessageEmbed()
        .setTitle('Here is your kitty review!')
        .setColor('#FFC0CB')
        .setImage(gif);

      await interaction.reply({ embeds:  });
    } catch (error) {
      console.error(error);
      await interaction.reply('Sorry, an error occurred.');
    }
  }
});

I’ve edited the code, so that it returns if no URL was found in the result, and the issue seems to be, that it’s not fetching the GIF URL: Sorry, no gif URL found in the search result

>Solution :

It doesn’t return no results, but error that result.gif is undefined.

You should change this line:

const gif = result.gif.url;

to:

const gif = result.url;

Then it works fine. At least in my case.

PS. This answer is based on originally posted code, not the changed one. Won’t check the new one again.

Leave a ReplyCancel reply