Public/Send-SlackWebMessage.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
function Send-SlackWebMessage {
    Param (
        [Parameter(ParameterSetName = 'ChannelName', Mandatory)]
        [string]$ChannelName,
        [Parameter(ParameterSetName = 'ChannelID', Mandatory)]
        [string[]]$ChannelID,
        [Parameter(ParameterSetName = 'ChannelName', Mandatory)]
        [Parameter(ParameterSetName = 'ChannelID', Mandatory)]
        [string]$Text
    )

    if (-not $ChannelID) {
        $ChannelID = (Get-SlackWebChannel -Name $ChannelName).id
    }

    foreach ($CID in $ChannelID) {
        $FormData = @{
            channel                    = $CID
            ts                         = (ConvertTo-UNIXTime -Date (Get-Date)) # current time. The original client increments the low part by one.
            type                       = 'message'
            xArgs                      = '{{}}'
            unfurl                     = '[]'
            blocks                     = ('[{{{{"type":"rich_text","elements":[{{{{"type":"rich_text_section","elements":[{{{{"type":"text","text":"{0}"}}}}]}}}}]}}}}]' -f $Message)
            include_channel_perm_error = 'true'
            client_msg_id              = [guid]::NewGuid().Guid
            token                      = '' # This property is filled by Invoke-ApiRequest
            _x_reason                  = 'webapp_message_send'
        }

        Invoke-ApiRequest -FormData $FormData -Method 'chat.postMessage'
    }
}