DEV Community

Oskar Codes
Oskar Codes

Posted on • Edited on

Send automated Discord messages through Webhooks using JavaScript

I'm sure you've heard of Discord, the all-in-one voice and text chat app, and maybe you're even using it. Well did you know that it is possible to send automated messages in Discord servers directly from JavaScript? It's called Webhooks. Let's see how to easily set one up in order for you to integrate it with your app, or even just have fun sending custom messages.
This works by sending a post request with some JSON data to a unique URL Discord provides when you create your Webhook.

Create the Webhook

Discord provides a feature to create Webhooks, but note that it is only available in server channels, not in direct messages. To create a Webhook, click the cog next to the channel in which you wish to set up your Webhook:
channel settings

Then head to the Webhooks tab, and hit Create Webhook. You'll then be able to specify the name, which is the name that is used when sending messages if none is specifided in the JSON post request.
You can also adjust the channel, and add a default image. Again, that image can later be customized from the JSON post request.

Then at the bottom, you'll get the unique Webhook URL. Copy it and save it somewhere, as we will use it later.

Setup the JavaScript file

In order to send POST requests to your webhook, you'll have to set up some form of JavaScript environment in which you can execute code. In my case I'll just simply create a local HTML file that I'll name index.html. Inside it I'll create a basic button that executes the JavaScript function sendMessage().
Here's the code:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Discord Webhook Tutorial</title>
  </head>
  <body>
    <button onclick="sendMessage()">Send</button>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

Then I'll add a script tag in which I'll declare the sendMessage function:

<script>
  function sendMessage() {

  }
</script>
Enter fullscreen mode Exit fullscreen mode

Inside of that function I'll create a new XMLHttpRequest, and I'll save the return value in the request variable. The first parameter will be "POST", because we want to do a POST request to the Webhook. The second parameter is your Webhook URL, that you got when creating your Webhook. If you don't have it, go to your Webhook's settings, and copy it from there.

Please note that the URL specified below is the URL referencing my Discord channel, so you need to change it in order for the code to work in your Discord channel.

Your sendMessage function should look like this:

function sendMessage() {
      const request = new XMLHttpRequest();
      request.open("POST", "https://discordapp.com/api/webhooks/676118118082281513/ZS5YcWhurzokBrKX9NgexqtxrJA5Pu2Bo4i7_JsIxC-JIbPBVhSZkcVVukGOro52rnQA");
      // replace the url in the "open" method with yours
}
Enter fullscreen mode Exit fullscreen mode

Then I'll call the setRequestHeader method, and specify the "Content-type" to be "application/json" in order to indicate that what we're sending is JSON data, like so:

request.setRequestHeader('Content-type', 'application/json');
Enter fullscreen mode Exit fullscreen mode

Then, I'll declare a params object, containing the JSON data we want to send to our Webhook:

const params = {
    username: "My Webhook Name",
    avatar_url: "",
    content: "The message to send"
}
Enter fullscreen mode Exit fullscreen mode

If you don't specify a username or avatar, it will default to the one you chose when creating the Webhook. The content attribute can't be empty, otherwise the request will fail.

And then for the last step, we need to send the actual data, like so:

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

Notice how JSON.stringify is used. It converts our params object to a valid string that can be sent.

Here's the final HTML file in case you want it:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Discord Webhook Tutorial</title>
  </head>
  <body>
    <button onclick="sendMessage()">Send</button>
  </body>

  <script>
    function sendMessage() {
      const request = new XMLHttpRequest();
      request.open("POST", "https://discordapp.com/api/webhooks/676118118082281513/ZS5YcWhurzokBrKX9NgexqtxrJA5Pu2Bo4i7_JsIxC-JIbPBVhSZkcVVukGOro52rnQA");

      request.setRequestHeader('Content-type', 'application/json');

      const params = {
        username: "My Webhook Name",
        avatar_url: "",
        content: "The message to send"
      }

      request.send(JSON.stringify(params));
    }
  </script>
</html>
Enter fullscreen mode Exit fullscreen mode

And now it's time to test it out! In my case I'll open up Chrome to execute my HTML file, and press the Send button in order to send the message.
And there you go! A message was sent from "My Webhook Name", and it says "The message to send", just like I specified:
Discord message result
If I had specified an avatar URL, it would have replaced the default Discord icon.

And that's basically it! You can now integrate this in your own application, to send automated messages when an event occurs in you app!

In a later tutorial, we'll see how to create embeds, in order to send really cool messages, like this one:
Discord Embed Example

Latest comments (54)

Collapse
 
andykvideo profile image
Andy • Edited

Can you send an image instead of text to the discord server? if so, what's the code?

Collapse
 
idk1232130 profile image
i need name ideas 💀

hey there is a problem for some reason it gives me this error:
(index):1 Uncaught ReferenceError: sendMessage is not defined
at HTMLButtonElement.onclick ((index):1:1)
can you help me fix it?

Collapse
 
kenzodk profile image
nipundil • Edited

I need to embed telegram post via this method to my discord channel. How to do it.
The embed code looks like this
<script async src="https://telegram.org/js/telegram-widget.js?19" data-telegram-post="codewithdila/2" data-width="100%"></script>

Collapse
 
notflamee121 profile image
NotflameE121

can you link the enbed vid plz ty

Collapse
 
oskarcodes profile image
Oskar Codes

Which video?

Collapse
 
htmlconverter22 profile image
HtmlConverter22 • Edited

This is very nice and all, but I have a question:

So I made a simplistic website and I want to add a webhook notifiyer right

Basically they paste their webhook in a textbox, and when they press a button,
a message I made gets sent to the webhook they posted in the text box.

I'd like to know how to do this please, and thank you.

Collapse
 
kengreg profile image
kengreg

hi, thanks for the help. Can you write also how to get messages from a channel? I am trying but everything and everyone just use discord.js which I cant use in my project

Collapse
 
oskarcodes profile image
Oskar Codes

Webhooks cannot read data from channels, because they're just HTTP endpoints you send requests to, there's no code logic involved in the Webhook on Discord's side.
So yeah, you'll have to use Discord.js to read from channels

Collapse
 
saucierpond profile image
SaucierPond • Edited

Hey @oskarcodes ! My code doesn't work. Can you please check why?

function sendMessage() {
    const request = new XMLHttpRequest();
    request.open("POST", "https://discordapp.com/api/webhooks/676118118082281513/ZS5YcWhurzokBrKX9NgexqtxrJA5Pu2Bo4i7_JsIxC-JIbPBVhSZkcVVukGOro52rnQA");

    request.setRequestHeader('Content-type', 'application/json');

    const params = {
        username: "My Webhook Name",
        avatar_url: "",
        content: "The message to send"
    }

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

Thank you!

Collapse
 
oskarcodes profile image
Oskar Codes

Your code looks fine, it must be the Webhook URL endpoint that is wrong

Collapse
 
Sloan, the sloth mascot
Comment deleted
Collapse
 
oskarcodes profile image
Oskar Codes

Then your webhook endpoint must be wrong, check it again.

Collapse
 
bigboielthico69 profile image
BIGBOIELTHICO⁶⁹

How would I make it to where I make a text submit box and get whatever hey typed in sent to the webhook?

Collapse
 
oskarcodes profile image
Oskar Codes • Edited

Make an HTML <input> element, select if from JavaScript, and pass the .value of that element to the payload you send to your Webhook.

Collapse
 
bigboielthico69 profile image
BIGBOIELTHICO⁶⁹

can you make an example of this please im really new to this

Collapse
 
abdus_salam_a81f8fe5dba4c profile image
abdus salam

How do you send the same messages to multiple server ??

Collapse
 
oskarcodes profile image
Oskar Codes

Make requests to multiple webhook endpoints

Some comments may only be visible to logged-in visitors. Sign in to view all comments.