Crypto Prices in Discord - Bot

Sorry for the long delay, but this is the second and last part of my series of bringing cryptocurrency prices into Discord. This tutorial will use a Discord bot.

Setting up

To create our bot template, we are going to use a cool project called create-discord-bot.

Run npx peterthehan/create-discord-bot in the bash if you are on a Unix based system and in the Git bash if you are on Windows. Fill out the questions that it prompts you and you have a Discord bot ready to be used.

We will also be using the CoinGecko API to get prices for cryptocurrency, so run npm install --save coingecko-api.

How the current bot works

Our bot currently runs on a widget based framework. Any folder located under the folder widgets is considered a widget and every widget must contain a folder handlers with .js files with names of discord.js events. There is one widget command which comes with it, and has it's own system of commands. You can insert any command into it's commands folder and use a CommandBuilder class to create commands.

Programming the bot

First, you should run npm run dev to start nodemon so you don't need to keep on restarting the bot.

Create a new file in the command/commands folder called coinPrice.js. Put this inside of it:

const CommandBuilder = require("../classes/CommandBuilder");

const CoinGecko = require("coingecko-api");

const CoinGeckoClient = new CoinGecko();

module.exports = new CommandBuilder()
  .setName("coinprice")
  .setAliases(["coin", "price"])
  .setOwnersOnly(false)
  .setGuildOnly(false)
  .setRequireArgs(true)
  .setDeletable(false)
  .setCooldown(10)
  .setDisabled(false)
  // eslint-disable-next-line
  .setExecute(async (message, user, args) => {
    let data = await CoinGeckoClient.simple.price({
      ids: [args[0]],
      vs_currencies: [args[1]],
    });
    await message.channel.send(
      `${args[2] || 1} ${args[0]} -> ${
        data.data[args[0]][args[1]] * (args[2] || 1)
      } ${args[1]}`
    );
  });

This basically allows you to run the command coin with this format: .coin <coinToCheck> <currencyToCompareAgainst> [optionalAmountForCoinToCheck]

Finishing Thoughts

Try adding more commands such as comparison of margin and other things you could do.

WARNING The create-discord-bot project is currently going through some major changes migrating the codebase to Typescript in a way that you still won't have to change your project. You may still need to change your project for that though.

Source code on Github

Back | DEV.to

shadowtime2000

If you are looking at this you probably wonder who I am; teenage open source maintainer

shadowtime2000's DEV profile image