Functions/Get-SlackMessage.ps1
<#
.SYNOPSIS This function gets messages from a Slack channel. .DESCRIPTION This function gets messages from a Slack channel. #> function Get-SlackMessage { [CmdletBinding(PositionalBinding=$false)] [OutputType([PSObject])] param( # The authentication token for Slack [Parameter(Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$token, # The name of the new channel [Parameter(Mandatory=$true)] [ValidateNotNullOrEmpty()] [String]$channelName, # Select the stream where the messages will be directed. [Parameter(Mandatory=$false)] [ValidateSet("Information", "Warning", "Error", "None")] [String]$outputStream = "Error" ) # Convert channelName and corresponding ID and verify that it exists $channelID = (Get-SlackChannel -Token $token -ChannelName $channelName).id if (!$channelID) { Write-OutputMessage "The channel '$($channelName)' cannot be found in Slack." -OutputStream $outputStream -ReturnMessage:$false return $null } # Prepare the API call parameters $invokeRestMethodParams = @{ Uri = "https://slack.com/api/channels.history" Method = "GET" Headers = @{ "Content-Type" = "application/x-www-form-urlencoded" Authorization = "Bearer $($token)" } Body = @{ "channel" = "$($channelID)" } } # Try to retrieve messages Write-Information "Retrieving messages from channel '$($channelName)'." try { $response = Invoke-RestMethod @invokeRestMethodParams } catch { Write-OutputMessage "Exception occurred while retrieving messages from channel '$($channelName)'.`r`n$($_.Exception.Message)" -OutputStream $outputStream -ReturnMessage:$false return $null } # Verify that the retrieval is successful if ($response.ok) { return $response.messages } else { Write-OutputMessage "Failed to get messages from channel '$($channelName)' with the error message:`r`n$($response.error)." -OutputStream $outputStream -ReturnMessage:$false return $null } } |