Skip to content
Advertisement

How do I use an API in Discord.js?

I was looking for a cool way I could automate some interesting news articles on my discord server. I wanted to use webhooks at first but then decided to go with APIs. I looked all around and saw that I should go with New York Times API but when I went to code it, it came up with a few errors.

const Discord = require("discord.js");
const client = new Discord.Client();
const token = require("./token.js");
const fetch = require('node-fetch');
const prefix = '!';

const trim = (str, max) => str.length > max ? `${str.slice(0, max - 3)}...` : str;

client.once('ready', () => {
    console.log('Ready!');

});

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

    const args = message.content.slice(prefix.length).trim().split(/ +/);
    const command = args.shift().toLowerCase();

    if (command === 'news') {
        const { file } = await fetch('https://api.nytimes.com/svc/topstories/v2/technology.json?api-key=').then(response => response.json());

        message.channel.sendMessage(file);

    }
    }).then((state) => {
        assert(state.action === 'DONE', 'should change state');
    })
        .catch((error) => {
            assert.isNotOk(error, 'Promise error');
        });
throw
client.login(token);

This is my code, I know this is probably riddled with mistakes but I am just starting out with node.js I looked at the example from the discord.js website and took some stuff from there. I don’t know what I should do and if you could explain it out a little to help me learn that would be great. I keep getting the Unhandled Rejection Promise Warning and the Cannot send an empty message errors. I am using Visual Studio Code.

Advertisement

Answer

You can use the async/await to get the results array from the API response, then send the details in embeds. You can either send the first article, a random article or more than one articles.

The following should work, it sends the first three articles:

const { Client, MessageEmbed } = require('discord.js');
const fetch = require('node-fetch');

const token = require("./token.js");

const client = new Client();
const API_KEY = 'QerEdX953-NOT-REAL-hdvgx7UPs';
const prefix = '!';

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

  const args = message.content.slice(prefix.length).split(/ +/);
  const command = args.shift().toLowerCase();

  if (command === 'news') {
    try {
      const response = await fetch(
        `https://api.nytimes.com/svc/topstories/v2/technology.json?api-key=${API_KEY}`,
      );
      const data = await response.json();

      if (data.results.length === 0) {
        return message.channel.send('There are no top stories for you today 🙊');
      }

      const embed = new MessageEmbed();
      // you could also get the number of stories from args[0]
      const MAX_STORIES = 3;

      data.results.slice(0, MAX_STORIES).forEach((result) => {
        embed.setTitle(result.title);
        embed.setDescription(result.abstract);
        embed.setURL(result.url);
        embed.setTimestamp(result.published_date);

        if (result.multimedia.length && result.multimedia[2]) {
          embed.setThumbnail(result.multimedia[2].url);
        }

        message.channel.send(embed);
      });
    } catch (error) {
      message.channel.send('Oops, there was an error fetching the API');
      console.log(error);
    }
  }
});

enter image description here

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement