JoonyBoy
JoonyBoy

Reputation: 31

Discord.js Tenor API error [Displaying image from Embed]

I'm using the Tenor API to display a random gif in an embed in Discord.js. I did everything correctly, however, the image is not loading.

Here is my code:

require('dotenv').config();
const Discord = require('discord.js');
const fetch = require('node-fetch')
module.exports = {
    name: 'tenor',
    category: 'misc',
    aliases: ['gif', 't'],
    async execute(message) {
        const url = `https://g.tenor.com/v1/search?q=Anime_Kiss&key=${process.env.TENOR}&limit=20`
        let response = await fetch(url)
        let mom = await response.json();
        const makerandom = Math.floor(Math.random() * mom.results.length);
        let embed = new Discord.MessageEmbed()
        .setImage(mom.results[makerandom].itemurl)
        message.channel.send({ embeds: [embed]})
    }
};

Here's what comes up:

enter image description here

Upvotes: 3

Views: 450

Answers (1)

Zsolt Meszaros
Zsolt Meszaros

Reputation: 23189

It's because itemurl is not a direct link to the file, but the full URL to view the post on tenor.com. You should use the media key instead. It's an array of dictionaries with the format (like gif, mp4, webm, etc.) as the key and a media object (with keys like size, duration, and url) as the value. It means you can get the URL of the gif image by using results[<random index>].media[0].gif.url.

I've updated your code, it works as expected now:

require('dotenv').config();
const Discord = require('discord.js');
const fetch = require('node-fetch');
module.exports = {
  name: 'tenor',
  category: 'misc',
  aliases: ['gif', 't'],
  async execute(message) {
      let url = `https://g.tenor.com/v1/search?q=Anime_Kiss&key=${process.env.TENOR}&limit=20`;
      try {
        let response = await fetch(url);
        let { results } = await response.json();
        let randomResult = results[Math.floor(Math.random() * results.length)];
        let { gif } = randomResult.media[0];
        let embed = new Discord.MessageEmbed().setImage(gif.url);

        message.channel.send({ embeds: [embed] });
      } catch (err) {
        console.log(err);
        message.channel.send('Oops, there was an error');
      }
  },
};

enter image description here

Upvotes: 2

Related Questions