PowerShellUniversal.Triggers.Discord.psm1

function Send-PSUDiscordNotification {
    <#
    .SYNOPSIS
    Send a notification to Discord
     
    .DESCRIPTION
    Send a notification to Discord from triggers in PowerShell Universal.
     
    .PARAMETER Data
    The trigger data. Generated by PowerShell Universal.
 
    .PARAMETER Job
    The trigger data. Generated by PowerShell Universal.
    #>

    param(
        [Parameter(Mandatory = $true, ParameterSetName = "Data")]
        $Data,
        [Parameter(Mandatory = $true, ParameterSetName = "Job")]
        $Job
    )

    if ($DiscordWebhookUrl -eq $null) {
        throw "Please create a variable called `DiscordWebhookUrl` with the value of your Discord Webhook URL"
    }

    $Content = ""
    $Text = ""
    $Header = ""

    if ($Job) {
        $Content = "A job has completed."
        $Text = Format-PSUJobDescription -Job $Job -AsMarkdown
        $Header = "[$($Job.Id)] $($Job.ScriptFullPath) $($Job.Status.ToString())"
    }

    if ($Text -eq "") {
        Write-Warning "Unknown trigger type."
        return
    }

    $Color = 0x00FF00
    switch ($Job.Status.ToString()) {
        "Running" { $Color = 0xFFFF00 }
        "Failed" { $Color = 0xFF0000 }
        "Completed" { $Color = 0x00FF00 }
        "Cancelled" { $Color = 0xFF00FF }
        "TimedOut" { $Color = 0xFF00FF }
        "Error" { $Color = 0xFF0000 }
        "Warning" { $Color = 0xFFFF00 }
        default { $Color = 0x00FF00 }
    }

    $DiscordData = @{
        content = $Content
        embeds  = @(
            @{
                title       = $Header
                description = $Text
                color       = $Color
            }
        )
    }

    Invoke-RestMethod -Uri $DiscordWebhookUrl -Method Post -Body ($DiscordData | ConvertTo-Json -Depth 10) -ContentType "application/json"

}