This repository has been archived by the owner on Sep 4, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 36
/
Copy pathPost-ToSlack.ps1
74 lines (67 loc) · 2.64 KB
/
Post-ToSlack.ps1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#requires -Version 3
function Post-ToSlack
{
<#
.SYNOPSIS
Sends a chat message to a Slack organization
.DESCRIPTION
The Post-ToSlack cmdlet is used to send a chat message to a Slack channel, group, or person.
Slack requires a token to authenticate to an org. Either place a file named token.txt in the same directory as this cmdlet,
or provide the token using the -token parameter. For more details on Slack tokens, use Get-Help with the -Full arg.
.NOTES
Written by Chris Wahl for community usage
Twitter: @ChrisWahl
GitHub: chriswahl
.EXAMPLE
Post-ToSlack -channel '#general' -message 'Hello everyone!' -botname 'The Borg'
This will send a message to the #General channel, and the bot's name will be The Borg.
.EXAMPLE
Post-ToSlack -channel '#general' -message 'Hello everyone!' -token '1234567890'
This will send a message to the #General channel using a specific token 1234567890, and the bot's name will be default (PowerShell Bot).
.LINK
Validate or update your Slack tokens:
https://api.slack.com/tokens
Create a Slack token:
https://api.slack.com/web
More information on Bot Users:
https://api.slack.com/bot-users
#>
Param(
[Parameter(Mandatory = $true,Position = 0,HelpMessage = 'Slack channel')]
[ValidateNotNullorEmpty()]
[String]$Channel,
[Parameter(Mandatory = $true,Position = 1,HelpMessage = 'Chat message')]
[ValidateNotNullorEmpty()]
[String]$Message,
[Parameter(Mandatory = $false,Position = 2,HelpMessage = 'Slack API token')]
[ValidateNotNullorEmpty()]
[String]$token,
[Parameter(Mandatory = $false,Position = 3,HelpMessage = 'Optional name for the bot')]
[String]$BotName = 'PowerShell Bot'
)
Process {
# Static parameters
if (!$token)
{
$token = Get-Content -Path "$PSScriptRoot\token.txt"
}
$uri = 'https://slack.com/api/chat.postMessage'
# Build the body as per https://api.slack.com/methods/chat.postMessage
$body = @{
token = $token
channel = $Channel
text = $Message
username = $BotName
parse = 'full'
}
# Call the API
try
{
Invoke-RestMethod -Uri $uri -Body $body
}
catch
{
throw 'Unable to call the API'
}
} # End of process
} # End of function