Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Post message with results to Slack #57

Open
MrPeanut12 opened this issue Feb 20, 2022 · 4 comments
Open

Post message with results to Slack #57

MrPeanut12 opened this issue Feb 20, 2022 · 4 comments
Assignees
Labels
enhancement New feature or request

Comments

@MrPeanut12
Copy link

I am starting to move all of my notifications to Slack and was wondering if this script could post the results to Slack, similar to how it sends an email. Another example is how Tautulli sends notifications to Slack.

I have an Incoming Webhook set up (via Sending messages using Incoming Webhooks). I am able to post from PowerShell with something like the code below (modified from Sending messages to Slack using PowerShell). However, I'm not sure how to modify this script in order to send success/failure messages with the appropriate data.

Example PowerShell script:

$uriSlack = "https://hooks.slack.com/services/<my-unique-url>"
$body = ConvertTo-Json @{
    text = "PlexBackup.ps1 complete."
}

try {
    Invoke-RestMethod -uri $uriSlack -Method Post -body $body -ContentType 'application/json' | Out-Null
} catch {
    Write-Error "Unable to post to Slack."
}

Slack has a convenient Block Kit Builder to show some of the components available.

Example JSON to post to Slack:

{
    "blocks": [
        {
            "type": "header",
            "text": {
                "type": "plain_text",
                "text": "\u2714\uFE0F Success",
                "emoji": false
            }
        },
        {
            "type": "section",
            "text": {
                "type": "mrkdwn",
                "text": "Plex backup script *C:\\Users\\User\\Documents\\PlexBackup.ps1* completed the `BACKUP -7ZIP (TEST)` operation on *PlexServer*. The backup folder *\\\\nas\\PlexBackup\\20220220112909* contains *1* objects and *0* GB of data. The script started at *02/20/2022 11:29:09* and ended at *02/20/2022 11:29:11* running for *00:00:02.593* (hr:min:sec.msec)."
            }
        }
    ]
}
@alekdavis
Copy link
Owner

I do not have time to look into this now, so wouldn't promise anything, but if you are willing to make a change, you can obviously clone the code and do whatever you like, but this will involve a lot of changes: (a) the SendMail method (to use Slack instead of email), (b) the logic that deals with mail properties (SMTP server, credentials, etc), (c) possibly the FormatEmail method (I suspect there is a way to pass HTML message to Slack, but I do not know). You will also need a couple of new properties for Slack settings and to indicate which notification provider to use. And the logic that validates all inputs before executing the main operation. Off the top of my head, I'd say it may be nice to have but given the amount of changes, that need to be implemented, I'd skip it.

@alekdavis alekdavis added the enhancement New feature or request label Feb 20, 2022
@MrPeanut12
Copy link
Author

Thanks. I don't have much experience with PowerShell, but I'll see about using what already exists as a starting point. I have a good start by duplicating the FormatEmail method.

#--------------------------------------------------------------------------
# SlackMessage
#   Generates the body of the Slack message.
function SlackMessage {
    [CmdletBinding()]
    param (
    )
    WriteDebug "Entered SlackMessage."

    [string]$backupMode     = $null
    [string]$dataDirPath    = $null

    if ($Script:Type) {
        $backupMode = $Script:Mode + " -" + $Type
    }
    else {
        $backupMode = $Script:Mode
    }

    if ($Script:Test) {
        $backupMode += " (Test)"
    }

    $dataDirPath = $Script:BackupDir | ConvertTo-Json

    $body = '*PlexBackup.ps1* completed the `' + $backupMode + '` operation on *PlexServer* (Plex version: ' + $Script:PlexVersion + '). Backup started at *' + $Script:StartTime + '* and ended at *' + $Script:EndTime + '* (total of *' + $Script:Duration + '*). Backup folder `' + $dataDirPath.Replace("`"","") + '` contains *' + $Script:ObjectCount + '* objects and *' + $Script:BackupSize + '* GB of data.'

    WriteDebug "Exiting SlackMessage."
    return $body
}

I'm then hijacking SendMail right now to send the notification.

$slackHeaderSuccess = "\u2705 Success"
$slackHeaderError = "\uD83D\uDC4E Failed"

if ($Script:ErrorResult) {
    $slackHeader = $slackHeaderError
}
else {
    $slackHeader = $slackHeaderSuccess
}

$messageSlack = SlackMessage

$bodySlack = @"
{
    "text": "$slackHeader - $messageSlack",
    "blocks": [
        {
            "type": "header",
            "text": {
                "type": "plain_text",
                "text": "$slackHeader",
                "emoji": true
            }
        },
        {
            "type": "section",
            "text": {
                "type": "mrkdwn",
                "text": "$messageSlack"
            }
        }
    ]
}
"@

$uriSlack = "https://hooks.slack.com/services/<my-unique-url>"

Invoke-RestMethod -uri $uriSlack -Method Post -body $bodySlack -ContentType 'application/json'

Obviously this needs a lot of work, but as an initial proof of concept, this appears to be a possibility.

Result so far:
2022-02-20_16 49 50_msedge

@alekdavis
Copy link
Owner

Sweet. Good luck with it. Btw, is there any security around who can post to your Slack URL?

@MrPeanut12
Copy link
Author

Sweet. Good luck with it. Btw, is there any security around who can post to your Slack URL?

No, there is no security. You just have to know the unique URL.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

2 participants