I made a Discord Bot in 4days!

I made a Discord Bot in 4days!

Haha, yes you heard it right I am the chef in dev world who made a discord bot in 4days!

Featured on daily.dev

It all started with a small task that I was given in fueler.io as an ambassador a few months back! So all of this started like this.

Read it till the end because I have a beautiful video for you at the end in which you will able to see the full project demonstration!

image.png

Before we move ahead lets discuss what fueler is.

Millions of skilled individuals around the world miss out on thousands of dollars worth of opportunities every day.

This is just because they are not able to prove themselves or due to lack of discovery.

We have built a simple and easy-to-use tool that helps skilled individuals prove themselves by showcasing their work. Fueler is a new age portfolio tool.

It just takes 30 seconds to setup your profile on Fueler and its totally free.

Now I am a huge believer of proof of work and that's what I am documenting what I have created in these last 4 days.

For me its an achievement because its a first problem that I solved through code!

Problem

For people to get opportunities in any domain people need to create stuff and show it to the world. So to help people getting Ideas and show their proof of work. We came up with a website named Proof Of Work Ideas

Well we already had a website which had all of the proof of work of ideas

But if anyone wants that same thing on discord like the task I was given, I always had to load the website then ctrl+c and then ctrl+v then post it in the chat. Lol, I am talking developer languages, but somehow it doesnt work that way 😂😂 for the task that I did...

Solution

Now I was lazy and wanted everything at my fingertips so I had to create a bot that will generate Ideas based on the certain commands. I feel automating the process would help in scaling this as we individually can't give proof of work ideas to everyone. But this bot surely solves for this!

The ideas were based on the following:

image.png

That is when I discovered slash commands in discord and here I could easily categorize them inside slash commands. The inspiration came when I discovered MidJourney who had required prompts to generate images based on AI.

image.png

Features ✨

image.png

As for the Features the bot would be able to generate Ideas in the following Niche's

  • Copywriting - For generating ideas around copywriting
  • Community Building - For generating ideas around community building
  • Writing - For generating ideas around writing
  • Marketing - For generating ideas around marketing
  • Design - For generating ideas around designing and,
  • Development - For generating ideas around development

There will be a command named "all" if someone wants all types of ideas in one place.

If anyone wants help we can return a reply with the commands that are available to be tested by the bot.

image.png

Tech Stack 🛠️

For Tech Stack I have used the following:

tech-stack.png

Technical Details

To make the bot online we need the following :

  • Bot Token(This will be provided when we create a bot profile on discord developer platform) The Bot Token is saved on a file .env which would be a secure file only for the developer to access.

Now we need to define the intents for which the bot we will use is compulsory and it is accessed by GatewayIntentBits

Basic Commands to make the bot Online

import { config } from 'dotenv'
import { Client, GatewayIntentBits } from 'discord.js';

config()

const client = new Client({
    intents: [
        GatewayIntentBits.Guilds,
        GatewayIntentBits.GuildMessages,
        GatewayIntentBits.MessageContent,

    ]
});

const TOKEN = process.env.POW_BOT_TOKEN
client.login(TOKEN);

client.on('ready', () => {
    console.log(`Logged in as ${client.user.tag}!`);
})

Now to make the bot live and connect to a server we need the following

  • Client Id (That will be accessed by taking the id from the bot available on discord)
  • Guild Id(That will be accessed by taking the id from the server available on discord)

We need REST api to connect this and its available on the discord.js library.

Now after connecting the server(guild) and bot(client) we need to specify a specific keyword to access the slash command and that is the command keyword in the body of the REST api call.

The commands can be defined in the following JSON format

  • name : => the command through which slash command will be accessed for example proof-of-work is used here
  • description : => simple description of the access command.
  • options: => this opens options within the slash commands

// we need to add the following code with the above one.
import { REST, Routes } from 'discord.js';

const CLIENT_ID = process.env.POW_CLIENT_ID;
const GUILD_ID = process.env.POW_GUILD_ID;
const rest = new REST({ version: '10' }).setToken(TOKEN);
async function main() {
    const commands =[
        {
            name: 'proof-of-work',
            description: 'Command to get new proof of work ideas in the chat',
            options : [
                {
                    name: 'category',
                    description: 'Get proof of work ideas for a specific category',
                    type: 3,
                    required: true,
                    "choices": [
                        {
                            "name": "help",
                            "value": "help"                            
                        },
                        {
                            "name": "development",
                            "value": "development"
                        },
                        {
                            "name": "design",
                            "value": "design"
                        },
                        {
                            "name": "copywriting",
                            "value": "copywriting"
                        },
                        {
                            "name": "marketing",
                            "value": "marketing"
                        },
                        {
                            "name": "community",
                            "value": "community"
                        },
                        {
                            "name": "writing",
                            "value": "writing"
                        },
                        {
                            "name": "all",
                            "value": "all"
                        }
                    ]
                }

            ]
        }
];

    try {
        console.log('Started refreshing application (/) commands.');
        await rest.put(Routes.applicationGuildCommands(CLIENT_ID, GUILD_ID), { 
            body: commands
        })
    } catch (error) { console.log(err) }
}
main();

Now to reply with one Idea, I had a fueler API with all ideas now I fetch the json details, categorize them on the basis if keywords and then make a function to get random idea of a certain category.

This idea category is then returned when the function is called and that is what I did, I added the function call on interactionCreate to get idea for one category.

I will demonstrate one function and how I categorized and also how I called the API to get the data

import fetch from "node-fetch"; //for importing the fetch command

// for getting API
var url=process.env.POW_API;    
    const response=await fetch(url);
    const allIdeas = await response.json();

//filtering the data based on keywords
// the json was categorized with a key value of pow_category
const devIdeas = allIdeas.filter( element => element.pow_category =="Development")

// getting random ideas as a string using the random() in Math which the random number or index number for the object
function randomDev() {
    let random = devIdeas[Math.floor(Math.random() * devIdeas.length)];
    const ideaForward = `“**${random.pow_idea}.**”`;
    return ideaForward;
  }

Now whenever we call the function we will get a random idea from the function

Now to access the bot commands and with the category to implement on them we will use the interactionCreate in the bot and we can implement the following commands on interaction create by using any conditional statements like if-else or switch-case.

We can now call the function and return in a certain interaction.

I only added to two interactions here to show how to declare it.

client.on('interactionCreate', (interaction) => {
    if (interaction.options.getString('category')=== 'development') {

        interaction.reply({content: `You asked for a proof of work idea in ${interaction.options.getString('category')}`+ '\n **Here is a proof of work idea for you in Development :)**\n\n'+ randomDev()});

    }
    else if (interaction.options.getString('category')=== 'design') {

            interaction.reply({content: `You asked for a proof of work idea in ${interaction.options.getString('category')}`+ '\n **Here is a proof of work idea for you in Design :)**\n\n'+ randomDesign()});

        }
 else if(interaction.options.getString('category')=== 'help'){
        interaction.reply({
            "content": ":book: *GETTING STARTED? READ THE QUICK START GUIDE*",
            "embeds": [
              {
                "title": ":sparkle: *BASIC COMMANDS*",
                "description": "`/proof-of-work`  Slash Command to Access \n       `category:`  Shows the category of proof of work you can access for the time being.\nIn short, `/proof-of-work <Category> `\n\nFor a full list of Ideas visit <https://fueler.io/proof-of-work-ideas>",
                "color": 65535
              },
              {
                "title": ":white_check_mark: *OPTIONS IN CATEGORY:*",
                "description": "Parameters are options added to the end of your prompt that change which Idea you get.\n       - *Development:* Will get you ideas around Development\n       - *Design:*  Will get you ideas around Design.\n       - *Copywriting:*  Will get you ideas around CopyWriting.\n       - *Marketing:*  Will get you ideas around Marketing.\n       - *Community:*  Will get you ideas around Community Management.\n       - *All:* Bored? And don't know what to create choose `all` and get any ideas to Implement on :wink:",
                "color": 65535
              },
              {
                "title": ":man_technologist: *WEBSITE*",
                "description": "View all the proof of work and access your account on \n<https://fueler.io/proof-of-work-ideas>",
                "color": 65535
              }
            ],
            "attachments": []
          });
    }
})

In the help section i used embed to beautify the Instructions. You can read more here.

The Embed looks something like this!

image.png

Deployment

For the deployment of the project I have used express js to host a website on repl and keep the bot alive.

import express from 'express';
const server = express();

server.all('/', (req, res) => {
    res.send(`Result: [OK].`);
})

export default function keepAlive() {
    server.listen(8080, () => {
        console.log('Server is now Ready!' + Date.now());
    })
};

Even if repl.it has restrictions of keeping the website live for hours but I have figured out a way to keep it live for 24x7 using an uptime bot

Project demonstration💫

Source Code 📦

PS: To run the bot yourself you need to have a discord bot account a discord server and the api to fetch data from fueler.

To Test the live bot join and use this at any channel ;D

image.png

Credits

  • I am grateful to create and implement this project at Fueler, It was not at all possible without Team Fueler's support. I am real happy for implementing this project and I am totally grateful to this team. They are totally like my family❤️
  • Really Grateful to Riten Debnath my mentor, my senior, founder of fueler who has been real supportive in this :). Please do follow him here image.png
  • A big thanks to Aquib Jawed and Anshu Shandilya as well who helped me figure out things when I was stuck.
  • To You, my viewer! If you read this till the end here, please please please dm me, I will happy to respond to you :)

Connect with me

Do add your thoughts or if you have any questions, shoot'em below in the comments. Stay Safe ❤️