PowerShell: Send to Teams Channel (Cat Facts\Images)

Overview:

As I have been learning more about leveraging PowerShell and APIs, I decided to work on some fun side projects to put what I learned into action. While I am still quite new to the APIs and Teams webhooks, this was a fun challenge, and I will be releasing a few more after this initial post, which I will link to this article. All source code can be found on my GitHub

At a high level, these scripts will search for data from an API endpoint or endpoints, randomize the information, post date, and text values, then post to a Teams channel of your choosing using Webhooks.

Send-Purr

An image is randomly selected from a random cat subreddit. Cat facts are pulled from the catfact.ninja API. When the r/Chonkers subreddit is used, the Teams post will be formatted to accommodate the chonkers size.

WARNING: Various filters are in place to try and prevent any inappropriate images from being sent.

Initial Setup & Running

  1. Teams Channel > Connectors > Incoming Webhook
  2. Give the Webhook a name & logo
    • Create the Teams Webhook
  3. Copy the URI
    • The URI is how you tell the script what teams channel to send posts to.
.\Send-Purr.ps1 -TeamsURI 'https://outlook.office.com/webhook/123/123/123/.....'

Using the defined webhooks connector URI a random cat fact and image are sent to the webhooks Teams channel.

No output is displayed in the console. Using the -Verbose option will give you a basic display output

Help

Help info and a list of parameters can be found by running Get-Help .\Send-Purr.ps1, such as:

Get-Help .\Send-Purr.ps1
Get-Help .\Send-Purr.ps1 -Full

GitHub\Source

The source code can be found here – Send-Purr

<#
.NOTES
    NAME: Send-Purr.ps1
    Type: PowerShell

        AUTHOR:  David Schulte
        DATE:    2022-06-20
        EMAIL:   [email protected]
        Updated:
        Date:

    VERSION HISTORY:
    0.1 - 2022-06-20 - Initial Release

    TODO:
    N\A

.SYNOPSIS
    Sends a cat image & fact to a Teams channel.

.DESCRIPTION
    The Send-Purr script sends a cat image & fact to a Teams channel using a Teams webhook connector URI.

    Various filters are in place to try and prevent any inappropriate images from being sent.

    An image is randomly selected from a random cat subreddit. Cat facts are pulled from the catfact.ninja API
    When the r/Chonkers subreddit is used, the Teams post will be formatting to accommodate for the chonks size.

    Unless the -Verbose parameter is used, no output is displayed.

.PARAMETER TeamsURI
    A string that defines where the Microsoft Teams connector URI sends information to.

.EXAMPLE
    .\Send-Purr.ps1 -TeamsURI 'https://outlook.office.com/webhook/123/123/123/.....'

    Using the defined webhooks connector URI a random cat image & fact are sent to the webhooks Teams channel.

    No output is displayed to the console.

.EXAMPLE
    .\Send-Purr.ps1 -TeamsURI 'https://outlook.office.com/webhook/123/123/123/.....' -Verbose

    Using the defined webhooks connector URI a random cat image & fact are sent to the webhooks Teams channel.

    Output is displayed to the console.

.INPUTS
    TeamsURI

.OUTPUTS
    Console, TXT

.LINK
    Celerium - https://www.celerium.org/
    Cat Facts - https://catfact.ninja/fact

#>

<############################################################################################
                                        Code
############################################################################################>
#Requires -Version 5.0

#Region  [ Parameters ]

[CmdletBinding()]
param(
        [Parameter(ValueFromPipeline = $true, Mandatory=$true)]
        [ValidateNotNullOrEmpty()]
        [String]$TeamsURI
    )

#EndRegion  [ Parameters ]

Write-Verbose ''
Write-Verbose "START - $(Get-Date -Format yyyy-MM-dd-HH:mm)"
Write-Verbose ''
Write-Verbose " - (1/3) - $(Get-Date -Format MM-dd-HH:mm) - Gathering Purr Data"

#Region     [ Prerequisites ]

    $Log = "C:\Celerium\Logs\Send-Purr-Report"
    $TXTReport = "$Log\Send-PurrLog.txt"

#EndRegion  [ Prerequisites ]

#Region  [ Main Code ]

try {

    $PurrSources = @(   'https://www.reddit.com/r/catpics/.json?sort=top&t=week&limit=25' ,
                        'https://www.reddit.com/r/IllegallySmolCats/.json?sort=top&t=week&limit=25' ,
                        'https://www.reddit.com/r/CatsInBusinessAttire/.json?sort=top&t=week&limit=25' ,
                        'https://www.reddit.com/r/Thisismylifemeow/.json?sort=top&t=week&limit=25' ,
                        'https://www.reddit.com/r/CatsStandingUp/.json?sort=top&t=week&limit=25',
                        'https://www.reddit.com/r/Chonkers/.json?sort=top&t=week&limit=25'
                )
        $PurrURI = Get-Random -InputObject $PurrSources

    $PurrData = Invoke-RestMethod -Uri $PurrURI -ErrorAction Stop
    $PurrImage = Get-Random $( $PurrData.data.children.data | Where-Object {$_.author -ne 'TrendingBot' -and $_.over_18 -eq $false -and $_.is_video -eq $false -and $_.url -notlike "*gallery*" -and $_.url -notlike "*v.redd*" -and $_.url -notlike "*gif*" -and $_.is_self -eq $false} )

    $PurrFact = (Invoke-RestMethod -Uri 'https://catfact.ninja/fact' -ErrorAction Stop).fact

}
catch {
    Write-Error $_

    if ( (Test-Path -Path $Log -PathType Container) -eq $false ){
        New-Item -Path $Log -ItemType Directory > $null
    }

    (Get-Date -Format yyyy-MM-dd-HH:mm) + " - " + "[ Step (1/3) ]" + " - " + $_.Exception.Message | Out-File $TXTReport -Append -Encoding utf8

    exit
}

#EndRegion  [ Main Code ]

Write-Verbose " - (2/3) - $(Get-Date -Format MM-dd-HH:mm) - Formatting Purr Data"

#Region     [ Adjust for chonker ]

$DeployChonker = if ( $PurrURI -like "*Chonker*" ){$true}else{$false}

    switch ($DeployChonker){
        $true  {
            $TitleText = "The Daily Purr! - !!! INCOMING CHONKER !!!"
            $TitleColor = "warning"
            $SubTitleText = "- This is what peak performance looks like \r"
            $FactText = "We love pictures of chonkers, but the only thing we love more is a fine boy who was a chonker and has become healthy! If this is your chonk, please check out these links.
                \r- [How To Put Your Cat On A Diet](https://pets.webmd.com/cats/guide/healthy-weight-for-your-cat#1)
                \r- [Is My Cat Obese?](https://diamondcarepetfood.com/why-or-is-my-cat-fat/)
                \r- [Pet Weight Calculator](https://www.petmd.com/healthyweight?mobi_bypass=true)
                \r- [Getting Your Tubby Tabby Back Into Shape](https://pets.webmd.com/cats/guide/fat-cats-getting-tubby-tabby-back-into-shape#1) \r
            "
            $ImageHeight = 'auto'
        }
        $false {
            $TitleText = "The Daily Purr!"
            $TitleColor = "accent"
            $SubTitleText = "- Meowing for no reason at all since 7500BC \r"
            $FactText = "Did you know: _$($PurrFact)_"
            $ImageHeight = '350px'
        }

    }

#EndRegion  [ Adjust for chonker ]

Write-Verbose " - (3/3) - $(Get-Date -Format MM-dd-HH:mm) - Sending Purr Data"

#Region     [ Teams Code ]

$JSONBody = @"
{
    "type":"message",
    "attachments":[
    {
        "contentType":"application/vnd.microsoft.card.adaptive",
        "contentUrl":null,
        "content":{
            "$('$schema')":"http://adaptivecards.io/schemas/adaptive-card.json",
            "type":"AdaptiveCard",
            "version":"1.4",
            "body":[
                    {
                        "type": "TextBlock",
                        "size": "Large",
                        "weight": "Bolder",
                        "color": "$TitleColor",
                        "text": " $TitleText"
                    },
                    {
                        "type": "TextBlock",
                        "size": "Small",
                        "text": " $SubTitleText",
                        "isSubtle" : true
                    },
                    {
                        "type": "TextBlock",
                        "text": "$FactText",
                        "wrap": true
                    },
                    {
                        "type": "Image",
                        "url": "$($PurrImage.url)",
                        "altText": "$($PurrImage.title)",
                        "height": "$ImageHeight",
                        "width": "auto",
                        "msTeams": {
                            "allowExpand": true
                        }
                    }
                ],
                "actions": [
                    {
                        "type": "Action.OpenUrl",
                        "title": "Adopt a kitty",
                        "url": "https://www.hsbh.org/adopt-a-cat/#adopt-a-cat"
                    },
                    {
                        "type": "Action.OpenUrl",
                        "title": "Source",
                        "url": "https://reddit.com$($PurrImage.permalink)"
                    }
                ],
                "msTeams": {
                    "width": "Full"
                }
            }
        }
    ]
}
"@

try {

    Invoke-RestMethod -Uri $TeamsURI -Method Post -ContentType 'application/json' -Body $JsonBody -ErrorAction Stop > $null

}
catch {
    Write-Error $_

    if ( (Test-Path -Path $Log -PathType Container) -eq $false ){
        New-Item -Path $Log -ItemType Directory > $null
    }

    (Get-Date -Format yyyy-MM-dd-HH:mm) + " - " + "[ Step (3/3) ]" + " - " + $_.Exception.Message | Out-File $TXTReport -Append -Encoding utf8

    exit
}

#EndRegion  [ Teams Code ]

Write-Verbose ''
Write-Verbose "End - $(Get-Date -Format yyyy-MM-dd-HH:mm)"
Write-Verbose ''

2 Comments

  1. Pingback: PowerShell: Send to Teams Channel (DadJoke) - Celerium

  2. Pingback: PowerShell: Send to Teams Channel (Pokemon) - Celerium

Leave a Reply