how to send a webhook to discord in javascript

To send a webhook to Discord using JavaScript, you need to create a webhook in your Discord server settings and get the webhook URL. Then, you can use the axios library to send a POST request to the webhook URL with the data you want to send.

Here's an example code snippet:

index.tsx
const axios = require('axios');

const webhookUrl = 'https://discord.com/api/webhooks/<WEBHOOK_ID>/<WEBHOOK_TOKEN>';

const data = {
  'content': 'Hello, world!', // message content
  'username': 'My Webhook', // override the webhook's username
  'avatar_url': 'https://mywebsite.com/avatar.png', // override the webhook's avatar
  'embeds': [{
    'title': 'Embed Title',
    'description': 'Embed Description'
  }] // array of embed objects
};

axios.post(webhookUrl, JSON.stringify(data))
  .then(response => {
    console.log('Webhook sent:', response.data);
  })
  .catch(error => {
    console.error('Error sending webhook:', error.message);
  });
654 chars
22 lines

In this example, we're using axios.post to send a POST request to the webhookUrl variable, which contains the URL for our Discord webhook. We're also passing in the data variable as the request body, after stringifying it with JSON.stringify.

The data variable contains several key-value pairs that define the message we want to send. The content field is the actual message content, while username and avatar_url allow us to override the webhook's default username and avatar. The embeds field is an array of embed objects that can be used to attach additional rich content to the message, such as images, videos, or links.

If the webhook is sent successfully, axios.post will return a response object with the data field containing the JSON response from Discord. If there's an error, the .catch() method will catch the error and log it to the console.

gistlibby LogSnag