DEV Community

Cover image for Sending Discord Messages With JS Using Webhooks
sandytrolling
sandytrolling

Posted on

Sending Discord Messages With JS Using Webhooks

 
Webhooks! They are kind of a data that you receive from web. To make it more understandable, you have a website for people to post content. You allow people to get some data with webhooks (e.g. user infos). So someone can get the data and use it in their own code.
So Discord, the platform you prob'ly know, has that "Webhook" feature, so you can create a webhook on Discord attached to channel and send message via it's special URL.
Now, let's head into coding!

1. Channel to Add the Webhook.
Now first up, we'll need a channel to send the messages. It can be any kind of text channel.
Click little settings at the right-side of channel name as shown in the image.
2. Click integration at sidebar.
Now click the "Integrations" option at the sidebar positioned in left.
3. Create a Webhook
Now hit that "Create Webhook" button and Boom! Now you have your very first webhook!
So, we have our webhook and now, we will copy it's URL by clicking that little "Copy Webhook URL" thing.
4. Copy URL.
Hey, as long as we have the URL, now we can start actually coding stuff!
5. JS Time.
First, create a file called "my-webhook.js" and open it with any IDE or text editor you want.
After that, we will store our webhook with a variable.

const request = new XMLHttpRequest();
request.open("POST", "webhook_link");
request.setRequestHeader("Content-type", "application/json");
Enter fullscreen mode Exit fullscreen mode

That's amazing! Now we'll have to create a function to send messages.

function send(displayname, message) {
  let options = {
    username: displayname,
    avatar_url: "", //You can put any image URL here
    content: message,
  }
}
Enter fullscreen mode Exit fullscreen mode

Lastly, let's send it.

request.send(JSON.stringify(options));
Enter fullscreen mode Exit fullscreen mode

Now you can add this code to your HTML and create a feedback system, troll your friends :D or whatever you want!

Make sure like this and follow me for more tutorials like this. And comment the things you want to learn, goodbye!

Top comments (0)