DEV Community

loading...

Send automated Discord messages through Webhooks using JavaScript

oskarcodes profile image Oskar Codes Updated on ・4 min read

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() {
      var 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:

var 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() {
      var request = new XMLHttpRequest();
      request.open("POST", "https://discordapp.com/api/webhooks/676118118082281513/ZS5YcWhurzokBrKX9NgexqtxrJA5Pu2Bo4i7_JsIxC-JIbPBVhSZkcVVukGOro52rnQA");

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

      var 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

Discussion (34)

pic
Editor guide
Collapse
suther profile image
Samuel Suther

Really nice article.
I've also made one, how to connect your Linux-Server to Discord.
It might be useful as additional information if somebody need to trigger a message from a server-process, instead out of JS.

just-sell-online-en.blogspot.com/2...

Collapse
jetfire158 profile image
jetfire158 • Edited

So I can just store the html file on the local machine? What would I need to add in order to tell it to execute every 2 hours? And could I run the webhook off of heroku or somewhere so that I wouldn't have to keep my PC on in order for it to work?

Collapse
oskarcodes profile image
Oskar Codes Author

You could start a Node server and use a node module like this one: npmjs.com/package/discord-webhook-...
Then you could maybe use a window.setInterval to execute it repeatedly with an interval.

Collapse
reelock profile image
Alessandro • Edited

Hello, Really cool, thanks a bounch!
it his possible to do something like this inside discord app?
I'm using Telegram and it has the cool option to let you write commands in a text message. Then the user click it and Telegram simply repeat the link content and send it to your bot.
Something like this

'Click /done when you have done.'

when you click (or tap) on /done, telegram send a message like this

/done@YourCoolBot

and your bot grab it as a regular command, like if you wrote /done yourself in the text line.

i would like to replicate the behavior on discord to or, if not possible since it seems not, at least do something like that

Collapse
oskarcodes profile image
Oskar Codes Author

You mean having some programmed logic when pressing links on the message sent by the Webhook?

Collapse
craigseller1979 profile image
craigseller1979

what html editor do you use because i kinda need one lol

Collapse
oskarcodes profile image
Oskar Codes Author

I use Visual Studio Code

Collapse
lecade09 profile image
a13bfg

for me personally i use repl.it, its online based, fast, and you don't need to download anything it supports multiple languages and it can be used as a website hoster.

Collapse
teodorv2 profile image
TEODORv2

Hi! So I wanted to enter the content directly from the html page, so I made a label, but I don't really know how to link the label's entered input to the content value. Anyone got any ideas? I'm really new to html, css and java so I don't really know much.

Collapse
oskarcodes profile image
Oskar Codes Author

Set the content field to the value of your input:

content: document.querySelector("input").value
Enter fullscreen mode Exit fullscreen mode
Collapse
enteruserhere22 profile image
EnterUsernameHere

How do you make it like send a message every 24 hours?

Collapse
br4dy0 profile image
Bradley Elko • Edited

set a timer for 24 hours that sends a request

Collapse
enteruserhere22 profile image
EnterUsernameHere

What would be the code to do that?
Sorry I am not very experienced at this.

Thread Thread
oskarcodes profile image
Oskar Codes Author

In JavaScript, you can use the setInterval method to run some code repeatedly.
Check out the documentation: developer.mozilla.org/en-US/docs/W...

Collapse
mmmm2006 profile image
Mmmm2006

Une partie 2, une partie 2, une partie 2

Collapse
oskarcodes profile image
Collapse
shllshckd profile image
shllshckd

Works flawlessly. <3

Collapse
lecade09 profile image
a13bfg

How do i make it send the content that was in the text box of a html page
like an discord webhook sender

Collapse
oskarcodes profile image
Oskar Codes Author

Set the content field to the value of your input:

content: document.querySelector("input").value // could be "textarea" as well
Enter fullscreen mode Exit fullscreen mode
Collapse
therayjohnson profile image
TheRayJohnson

Is it possible to do multiple webhooks? Like a dropdown menu of channels and selecting X channel from the form dropdown list will use Y webbook?

Collapse
oskarcodes profile image
Oskar Codes Author

Yes that’s totally possible, just check which option is selected in the drop down, and send to a different webhook url based on that

Collapse
thinker010 profile image
Punith Reddy V

can we put text box instead of writing the message in code all the time pls help

Collapse
oskarcodes profile image
Oskar Codes Author

Yes you can, just use the value property of the text box and pass it in the object that is sent in the webhook payload.

Collapse
misterymissile profile image
misterymissile

How do I make it send a variable in the content: parameter?

Collapse
oskarcodes profile image
Oskar Codes Author

Well you can just put your variable in there instead of the string

content: yourVariableName
Collapse
censorrmc profile image
censorr

Is there a way to make it so it sends multiple lined messages? In this it only allows me to send a message that is in all one line.

Collapse
oskarcodes profile image
Oskar Codes Author

Add the character \n to create a newline, like so:

content: "The message\nto send"

Otherwise you could use backsticks instead of quotes, like so:

content: `The message
to send`
Collapse
scrap_olive profile image
WikiNope

How would you post an updating game log through discord?

Collapse
oskarcodes profile image
Oskar Codes Author

Same logic as explained in this article, just that the environment is your game framework or engine.

Collapse
ianmoon06377246 profile image
Ian Moone

Is there a way to use webhook to send a private message if person is on the server which my app is connected to?

Collapse
oskarcodes profile image
Oskar Codes Author

No, for that you’ll need a Discord bot. A webhook can only send to server channels.

Collapse
mrlikeltu profile image
MrLikeLTU

Hello, I have a question: Where exactly I need to create the html file, and how to run it?

Collapse
oskarcodes profile image
Oskar Codes Author

The HTML can be created anywhere on your computer, just like you would create a plain text document, but with the .html extension. To run it, just double click it, it should open it in your default web browser.
Check this article out for what you need to start web development: developer.mozilla.org/en-US/docs/L...

Collapse
mrlikeltu profile image
MrLikeLTU

Thanks!