Automatic Slack Notifications from Windows
Sep 4, 2016I often execute long running scripts on my development machine and want to get notified when their done, even when I’m not in the room. I’d prefer to do this without installing anything extra, because nobody hates software more than software developers. I’m already running Slack, so one practical way to do this is by exploiting Slack’s Incoming Webhooks. Unfortunately, all Slack’s examples for web hooks use cURL and I’m developing on Windows 10. There are solutions for getting cURL on Windows, but I’d prefer something that works on a fresh install. This is where Powershell’s Invoke-RestMethod comes in.
First, lets set up the Incoming Webhooks integration in slack. Log into the web app, and click on your team’s name in the top left corner. Select Team settings from the dropdown.
$payload = @{
text = 'Hello World'
}
$json = $payload | ConvertTo-Json
Invoke-RestMethod -Uri https://hooks.slack.com/services/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 -Method POST -Body $json
In PowerShell ISE hit the green Run Script button to test your script out, you should get ok as a return value, and you should see your message in Slack. Make sure you check the right channel!
bool
to indicate success or failure:
param (
[Parameter(Mandatory=$true)][string]$uri,
[Parameter(Mandatory=$true)][bool]$success
)
$message = 'Build Failed'
$emoji = ':rage:'
if($success)
{
$message = 'Build Succeeded'
$emoji = ':nerd_face:'
}
$payload = @{
username='Compiler'
text=$message
icon_emoji=$emoji
}
$json = $payload | ConvertTo-Json
$response = Invoke-RestMethod -Uri $uri -Method POST -Body $json
You can invoke it from plain old windows shell like so:
powershell -command .\buildStatus.ps1 https://hooks.slack.com/services/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 0
I’d love to hear about the awesome things you automate after trying this out!