How To Create a Simple Bot on Discord

This tutorial will show you how to set up a simple bot using webhooks on … Read more How To Create a Simple Bot on Discord

This tutorial will show you how to set up a simple bot using webhooks on a Discord channel. The bot will post a message to a channel. I recommend setting up your own personal server for testing purposes, before you unleash it on the world.



CREATE A BOT ON DISCORD

Follow this how-to and intro to webhooks, to the point where you get the webhook URL. You can give it a fun name and avatar. Have the webhook URL handy, so you can use it later.

Do not do Quick Example: GitHub Webhook Integration, it is not part of this tutorial

Discord "Copy webhook URL" button

Your bot is ready and waiting for input!



SET UP THE BOT

Make sure you have Node.js installed on your computer so you can run your script in the terminal. You can check if it’s installed by checking the version number in your terminal.

node --version

If you don’t have node, you can get it here.

Create a sendmessage.js file with a console.log function for testing in the terminal. We’ll build on this function as we go forward.

sendmessage.js

const sendMessage = () => {
  console.log("Hello");
};

sendMessage();

Run file by executing node sendmessage.js in the terminal. This should print “Hello” on the next line.

node sendmessage.js
Hello

Great! Your code is working and node is properly installed. Now you’ll want to get the project started.

Initialize your project using yarn or npm. They work similarly, but we’ll be using npm for this tutorial, because it comes bundled with node. Start it up by keying the following:

npm init

This will create a package.json file. That’s the library ‘ingredient list’ for your program. It keeps track of rules and dependencies that people will use to run your pgoram.

You will be prompted to fill in various fields at this point. Unless you want to link it to github or customize with your information, you can accept the defaults (i.e. press ‘Enter/return’ for each). This basic tutorial doesn’t cover any of this, so we are accepting the defaults.

Now you’ll want to get axios, so you can simplify sending HTTP requests.

npm install axios

Great! Now you have your ingredient list and ingredients. We are ready to put things together.



MAKE YOUR BOT TALK

We will be making an HTTP POST to our webhook URL. First, import axios at the top of your .js file. This links the axios library to your program, so you can use all of the perks you installed.

const axios = require("axios");

Make sure this is the first line of your code.

Next, create a couple of variables to hold the data you are sending. Discord requires an object with a content key, which is why we’ve got the text written in {key:value} format. If you tried to send it as a string, it would be interpreted as an empty message. When your program runs, you wouldn’t get an error, but your bot also would not post a message.

To make this code resuable, we will add the text in a command line argument, using Command Line Interface (CLI). It allows you to send a string when you run the program, instead of hardcoding it.

// This will pull the entry in the 3rd place on your array.
const commandLineText = process.argv[2];
// This object is needed because that is how Discord receives the information to post.
const messageData = {
  content: commandLineText;
};

Now go to your sendMessage function. Remove the console.log you had previously and replace it with this axios call. The comments will explain what each section does.

axios
    // This takes care of your HTTP POST. It needs two arguments.
  .post(
    // The webhook URL as a string
    "Paste Your Discord Webhook URL Here",
    // The variable that contains the object you are sending
    messageData
  )
  // axios is a promised-based .js library, so it has .then and .catch
  .then(function (response) {
    console.log(response);
    // This has been added so you can see all arguments being sent. It's not required
    console.log(process.argv);
  })
  .catch(function (error) {
    console.log(error);
  });

That’s it! Save your file and get ready. Your code should look something like this:

const axios = require("axios");
const commandLineText = process.argv[2];
const messageData = {
  content: commandLineText
};

const sendMessage = () => {
  axios
    .post("https://just-a-placeholder-for-your-webhook-url", messageData)
    .then(function (response) {
      console.log(response);
      console.log(process.argv);
    })
    .catch(function (error) {
      console.log(error);
    });
};

sendMessage();



RUN YOUR BOT!

Open the Discord channel where your bot lives.

Go to your terminal and make sure you are in the folder that holds your code.
Type node sendmessage.js "Hello!".

Peek over at your Discord channel. If all is well, you should see your bot pop up and say hi!

node sendmessage.js "Hello!"

Your Bot in Discord gives a friendly Hello!

Because the code also interprets the bash command as an array, it will print the string in the 3rd position, regardless of its size. You can sent it whatever text you’d like, as long as it is all part of the same string. Give it a try!

node sendmessage.js "What Lovely Weather We Be Havin'!"

Discord Bot comments on the weather

Way to go! Now you can set up a bot on another channel and share have some fun with friends, as long as you have the right permissions.

**Note:* If you’d like, you can add more to the array, but you’ll have to adjust process.argv[2] in commandLineText to modify your argument display*



SUMMARY

Today we learned how to set up a basic bot using webhooks on Discord.

Thanks for checking out my tutorial!

Source: DEV Community



Leave a Reply

Your email address will not be published. Required fields are marked *