src/Tracing/Write-XrmMessageToSlack.ps1

<#
    .SYNOPSIS
    Push message to slack

    .DESCRIPTION
    Use Slack webhook to send current message in target channel.
    Write-HostAndLog sends its warnings and errors this way when the SLACKURL environment variable is set.

    .PARAMETER SlackUrl
    Url to Slack webhook. (Default: SLACKURL environment variable)

    .PARAMETER BotName
    User name for message sender. (Default: DevOps, replaced by "Release <definition name>" or "Build <definition name>" in an Azure DevOps pipeline)

    .PARAMETER Message
    Message to send.

    .PARAMETER Emoji
    Emoji to use as the icon for this message.

    .OUTPUTS
    System.Void.

    .EXAMPLE
    Write-XrmMessageToSlack -SlackUrl $slackWebhookUrl -BotName "Contoso deployment" -Message "Solution contoso_core imported." -Emoji ":rocket:";
    
    .LINK
    https://github.com/AymericM78/PowerDataOps/blob/main/documentation/commands/Write-XrmMessageToSlack.md

    .LINK
    https://api.slack.com/methods/chat.postMessage
#>

function Write-XrmMessageToSlack {
    [CmdletBinding()]
    [OutputType([System.Void])]
    param
    (        
        [Parameter(Mandatory = $false)]
        [String]
        $SlackUrl = $env:SLACKURL,
        
        [Parameter(Mandatory = $false)]    
        [String]
        $BotName = "DevOps",

        [Parameter(Mandatory = $true)]    
        [String]
        $Message,

        [Parameter(Mandatory = $false)]
        [String]
        $Emoji
    )
    process {
        
        if ($BotName -eq "DevOps") {
            # $projectName = $env:SYSTEM_TEAMPROJECT;
            
            if ($env:RELEASE_DEFINITIONNAME) {
                $BotName = "Release $($env:RELEASE_DEFINITIONNAME)";
            }
            elseif ($env:BUILD_DEFINITIONNAME) {
                $BotName = "Build $($env:BUILD_DEFINITIONNAME)";
            }
        }        
        
        $BodyTemplate = ConvertTo-Json @{
            username   = "$BotName"
            text       = "$Message"
            icon_emoji = "$Emoji"
        }

        Invoke-RestMethod -uri $SlackUrl -Method Post -body $BodyTemplate -ContentType 'application/json' | Out-Null;
    }
}

Export-ModuleMember -Function Write-XrmMessageToSlack -Alias *;