Create a Discord Webhook in JavaScript

Discord Webhooks are a comfortable opportunity to send messages - using internet magic - directly into your Discord channel. This article is for Discord Server owners which want to create a Webhook-Bot to sent messages (e.g. from their website) into a specific channel.

Only use this webhook in a password-secured area. Writing code in JavaScript means it will be exposed to the frontend user. Everyone who is seing the source code can also send messages to the specific channel(s).

Let's create the webhook

To create Webhook in Discord open the settings of a channel first. The webhook will send messages to the selected channel, so choose wisely. You need admin permissions to add a new webhook. Then, in the settings, head over to integrations and create a new Webhook.

Create the webhook

Now you can set a name and a profile image of the Webhook. You change them later at any time.

Write the code

Add this JavaScript snippet to your website. Please replace your WEBHOOK-URL with the url given in the Webhook panel on Discord. You can even test this locally in a .html file.

<!DOCTYPE html>
<html lang='de' dir='ltr'>

<head>
  <meta charset='utf-8'>
  <title>Webhook</title>
  <script>
    function webhook() {
      var hook = new XMLHttpRequest();

      hook.open('POST', 'WEBHOOK-URL');

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

      var content = {
        username: 'Webhook Name',
        avatar_url: 'https://example.com/profile-icon-for-bot.png',
        content: document.getElementById('message').value
      }

      hook.send(JSON.stringify(content));
    }
  </script>
</head>

<body>

  <form onsubmit='webhook();return false;'>

    <input type='name' id='message'>

    <input type='submit' value='Send'>

  </form>

</body>

</html>

How does the code work?

Thanks for this... complicated code? In this code we have a form element which will trigger our webhook() function in JavaScript if submitted. We prevent the submit event with a "return false;", which would otherwise lead to a reload of the page.

Create a Discord Webhook in JavaScript
DarkIntaqt
DarkIntaqt

©2020 - 2024

DarkIntaqt

DarkIntaqt

HomeAboutBlog