I have a confession to make. Although this is part of the Discord Bots series, this article actually has nothing to do with Discord bots. Even so, it is extremely useful to know how webhooks work in Discord.
Webhooks provide a way to create a public HTTP endpoint that allow services to send messages to. Discord will parse those messages and display them in the channel where you created the webhook. This works great when you want to receive notifications from external systems.
Note that anyone who has your webhook can send messages to the channel, so treat these as secrets (because they are).
Create the Webhook
Creating webhooks in Discord is very easy. Inside your Discord server, right click on the channel you want the messages to drop and click Edit Channel, then Webhooks, and finally Create Webhook;
We’ll leave the default options for now. You can give your webhook a different name and a profile image, which will show in the channel when the message is displayed as well, but its entirely optional. Copy the Webhook URL that is provided and click save.
Sending a Message using Postman
Webhooks receive message using HTTP POST actions. You can simulate this using Postman, which is a very popular API testing client. If you dont have it installed already, you can download it from https://www.postman.com/downloads/
In Postman, do the following;
- Create a new tab for testing the webhook.
- Paste your webhook url in the address bar.
- Just to the left of the address bar, change the method to POST.
- Click on the Body tab underneath the address bar and select raw.
- To the right of those options, click on Text and change it to JSON.
- Finally, paste this JSON into the body.
"content": "Hello from my webhook!"
Once you click Send, your Postman client should look something like this. You can use the numbered steps that correspond with the directions above, but I also wanted to call out the Status in the response pane. You should receive a 204 No Content. This means the message was sent correctly. If not, you’ll receive an error message in the response body.
Back in Discord, you should see your message with your webhook as the sender.
You can actually send embeds into Discord using webhooks as well. The method is exactly the same, just the JSON is different. Using our Postman settings above, paste the following JSON into the Postman body and send it.
"title": "Webhook Embed",
"description": "Hello from my webhook!"
And instead of the text we received before, we now have a rich card instead.
You can get pretty creative with embeds, including images, fields, URLs, etc. Documentation of all available fields can be found here: https://discord.com/developers/docs/resources/channel#embed-object
Next week, I’ll be going over how to store data in a database as well as deploying our bot to Azure.