What's a Discord Webhook?
A Discord Webhook allows you to send a message to a text channel auto-magically. It essentially provides a URL that is associated with a channel. You can customize the name of the sender, the avatar picture, and of course send over the contents of the mesage. More info on Discord Webhooks here.
Getting Started
The first step will be to create the Webhook in Discord.
1. Navigate to Server Settings on the server you want to create the hook on.
2. Click Webhooks from the options on the left, and then Create Webhook on the right.
3. Fill out the name of the hook, the channel you want it to hook into, and optionally associate an image.
4. Save the Webhook, and get the Webhook Url, as we'll need that later.
Using the Webhook in PowerShell
To utilize the Webhook in PowerShell, we'll make use of the Invoke-RestMethod command, and build a custom object as our payload.
1. Store the hook url we created earlier in a variable.
$hookUrl = "your hook url goes here"
2. Store the content in a variable (this is the message you'll be sending to the hook).
$content = @" You can enter your message content here. With a here-string, new lines are included as well! Enjoy. "@
3. Create the payload as a PowerShell custom object, in order to get the properties converted to JSON later.
$payload = [PSCustomObject]@{ content = $content }
4. Finally, use Invoke-RestMethod to utlize the Webhook, and post the message.
Invoke-RestMethod -Uri $hookUrl -Method Post -Body ($payload | ConvertTo-Json)
We are using the Post method with Invoke-RestMethod to send over the $payload
The payload is a PSCustomObject, which is great when working in PowerShell, but not-so-great when working with Web APIs, which almost always want something to be formatted as JSON (JavaScript Object Notation).
That's why we use ($payload | ConvertTo-Json) with this Invoke-RestMethod call.
Here is what the object looks like:
Here is what it looks like converted to JSON:
Altogether, our code should now look like this:
$hookUrl = 'https://enterYourUrlHere' $content = @" You can enter your message content here. With a here-string, new lines are included as well! Enjoy. "@ $payload = [PSCustomObject]@{ content = $content } Invoke-RestMethod -Uri $hookUrl -Method Post -Body ($payload | ConvertTo-Json)
Note:
You may need to append:
-ContentType 'Application/Json'
To your Invoke-RestMethod command in later versions of PowerShell.
Let's run that, and see what happens in the Discord channel the hook is associated with.
Success!
But wait... there's more!
Keep an eye out for part 2, where I'll expand upon what we can add to the payload. This includes a different user name, avatar icon, and even embeds!
Let me know if you have any trouble or ideas in the comment section, below!
I am also interested in hearing how you plan to use your PowerShell -> Discord Webhooks.
Happy Scripting!