OrangeDurito.blog

An amalgamation of engineering and artistry

Making My Own Discord Bots

Prologue

Lately, I have been spending a considerable time on Discord. For one, most of our lab conversations happen on Discord and secondly, I have finally started to realize the power of this platform to create an engaging community. Seriously, Discord is awesome! You have different servers of your interest with different channels within, it has pretty decent photos and videos support and you can have group voice and videos calls. But the important of all, which is cherry on the cake, are the Discord bots. They can extend the functionality of this platform multifold. Any task that is mundane or tedious for human intervention can be delegated to bots - - [x] moderation - [x] saying hi - [x] summarizing information - [x] server health monitoring - [x] list of rocket launches - [x] telling jokes

You get the idea. Now, it is the last two that I focused on for my Weekend Project.

First of all, follow the setup steps mentioned here for a rudimentary Discord bot connection and testing. After that, all you are limited by is your imagination and the availability of a good API. That's it. Here's my bot.js file for the 'Upcoming Launches' bot which returns a list of next 10 rocket launches whenever you type and enter !launch on Discord -

var Discord = require('discord.io');

var logger = require('winston');

var auth = require('./auth.json');

const axios = require('axios')

var disc = require('discord.js')

// Configure logger settings

logger.remove(logger.transports.Console);

logger.add(new logger.transports.Console, {
    colorize: true
});

logger.level = 'debug';

// Initialize Discord Bot

var bot = new Discord.Client({

    token: auth.token,

    autorun: true

});


bot.on('ready', function (evt) {

    logger.info('Connected');

    logger.info('Logged in as: ');

    // logger.info(bot.username + ' - (' + bot.id + ')');
    logger.info(bot.username);
});


bot.on('message', function (user, userID, channelID, message, evt) {

// Our bot needs to know if it will execute a command

// It will listen for messages that will start with `!`

    if (message.substring(0, 1) == '!') {
        var args = message.substring(1).split(' ');
        var cmd = args[0];
        args = args.splice(1);

        switch(cmd) {
            case 'launch':
                let axiosOptions = {
                    method: "get",
                    url: `https://ll.thespacedevs.com/2.0.0/launch/upcoming/`
                }

                axios(axiosOptions)
                    .then(response => {
                        // console.log(response.data)
                        let table = response.data.results

                        let launchlist = "";

                        table.forEach(item => {
                            net_time = new Date(item.net)
                            launchlist += `- ${item.name}, ${net_time.toString().slice(-100,-42)}, ${net_time.toString().slice(-41)}\n`
                        });

                        var embed = new disc.MessageEmbed()
                            .setTitle('Upcoming Launches')
                            .setDescription(launchlist)
                            .setURL('http://chandansinha.me')

                    bot.sendMessage({
                        to: channelID,
                        message: `> **${embed.title}** \n${embed.description}`
                        });
                    })       
            break;
        }
    }
});

I struggled with composing a rich text message with discord.io, so after scratching my head for 3 days and looking through the poor documentation I finally decided to go with discord.js in conjunction with the former. I also used axios library for HTTP request to query the API.

Similarly, here is the code for my joke bot 'Hoot Hoot' which tells you a joke everytime you type and enter !joke on Discord -

var Discord = require('discord.io');

var logger = require('winston');

var auth = require('./auth.json');

const axios = require('axios')

var disc = require('discord.js')

// Configure logger settings

logger.remove(logger.transports.Console);

logger.add(new logger.transports.Console, {
    colorize: true
});

logger.level = 'debug';

// Initialize Discord Bot

var bot = new Discord.Client({

    token: auth.token,

    autorun: true

});


bot.on('ready', function (evt) {

    logger.info('Connected');

    logger.info('Logged in as: ');

    // logger.info(bot.username + ' - (' + bot.id + ')');
    logger.info(bot.username);
});


bot.on('message', function (user, userID, channelID, message, evt) {

// Our bot needs to know if it will execute a command

// It will listen for messages that will start with `!`

    if (message.substring(0, 1) == '!') {
        var args = message.substring(1).split(' ');
        var cmd = args[0];
        args = args.splice(1);

        switch(cmd) {
            case 'joke':
                let axiosOptions = {
                    method: "get",
                    url: `https://v2.jokeapi.dev/joke/Any`
                }

                axios(axiosOptions)
                    .then(response => {
                        let type = response.data.type

                        if(type == 'single'){
                            var whole_joke = response.data.joke
                        }

                        else if(type=='twopart'){
                            var whole_joke = `${response.data.setup} \n${response.data.delivery}`
                        }

                        var embed = new disc.MessageEmbed()
                            .setTitle("Hoot Hoot! Here's a joke for yah!")
                            .setDescription(whole_joke)
                            .setURL('http://chandansinha.me')

                    bot.sendMessage({
                        to: channelID,
                        message: `> **${embed.title}** \n${embed.description}`
                        });
                    })       
            break;
        }
    }
});

// https://sv443.net/jokeapi/v2/

Next Step

  • https://www.writebots.com/discord-bot-hosting/

Comments