Microsoft Teams - Post a message

Octopus.Script exported 2023-08-31 by twerthi belongs to ‘Microsoft Teams’ category.

Posts a message to Microsoft Teams using a general webhook.

Parameters

When steps based on the template are included in a project’s deployment process, the parameters below can be set.

Webhook Url

HookUrl =

The specific URL provided by Microsoft Teams when adding an Incoming WebHook connector to a team channel. Copy and paste the full Webhook URL from Microsoft Teams here.

Message title

Title = #{Octopus.Project.Name} #{Octopus.Release.Number} deployed to #{Octopus.Environment.Name}#{if Octopus.Deployment.Tenant.Id} for #{Octopus.Deployment.Tenant.Name}#{/if}

The title of the message that will be posted to your Microsoft Teams channel.

Message body

Body = For more information, please see [deployment details](#{if Octopus.Web.ServerUri}#{Octopus.Web.ServerUri}#{else}#{Octopus.Web.BaseUrl}#{/if}#{Octopus.Web.DeploymentLink})!

The message body of post being added to your Microsoft Teams channel.

Color

Color =

The color to use for the border on the side of the message.

Timeout in seconds

Timeout = 60

The maximum timeout in seconds for each request.

Retry posting message

TeamsPostMessage.RetryPosting = False

Should retries be made? If this option is enabled, the step will attempt to retry the posting of message to teams up to the set retry count. Default: False.

Retry Count

TeamsPostMessage.RetryCount = 1

The maximum number of times to retry the post before allowing failure. Default 1

Retry delay in milliseconds

TeamsPostMessage.RetryDelay = 100

The amount of time in milliseconds to wait between retries. Default 100

Script body

Steps based on this template will execute the following PowerShell script.

[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
# Helper functions
function Retry-Command {
    [CmdletBinding()]
    Param(
        [Parameter(Position=0, Mandatory=$true)]
        [scriptblock]$ScriptBlock,
 
        [Parameter(Position=1, Mandatory=$false)]
        [int]$Maximum = 5,

        [Parameter(Position=2, Mandatory=$false)]
        [int]$Delay = 100
    )

    Begin {
        $count = 0
    }

    Process {
    	$ex=$null
        do {
            $count++
            
            try {
                Write-Verbose "Attempt $count of $Maximum"
                $ScriptBlock.Invoke()
                return
            } catch {
                $ex = $_
                Write-Warning "Error occurred executing command (on attempt $count of $Maximum): $($ex.Exception.Message)"
                Start-Sleep -Milliseconds $Delay
            }
        } while ($count -lt $Maximum)

        # Throw an error after $Maximum unsuccessful invocations. Doesn't need
        # a condition, since the function returns upon successful invocation.
        throw "Execution failed (after $count attempts): $($ex.Exception.Message)"
    }
}
# End Helper functions
[int]$timeoutSec = $null
[int]$maximum = 1
[int]$delay = 100

if(-not [int]::TryParse($OctopusParameters['Timeout'], [ref]$timeoutSec)) { $timeoutSec = 60 }


If ($OctopusParameters["TeamsPostMessage.RetryPosting"] -eq $True) {
	if(-not [int]::TryParse($OctopusParameters['RetryCount'], [ref]$maximum)) { $maximum = 1 }
	if(-not [int]::TryParse($OctopusParameters['RetryDelay'], [ref]$delay)) { $delay = 100 }
	
    Write-Verbose "Setting maximum retries to $maximum using a $delay ms delay"
}

$payload = @{
    title = $OctopusParameters['Title']
    text = $OctopusParameters['Body'];
    themeColor = $OctopusParameters['Color'];
}

Retry-Command -Maximum $maximum -Delay $delay -ScriptBlock {
	# Declare variable for parameters
    $invokeParameters = @{}
    $invokeParameters.Add("Method", "POST")
    $invokeParameters.Add("Uri", $OctopusParameters['HookUrl'])
    $invokeParameters.Add("Body", ($payload | ConvertTo-Json -Depth 4))
    $invokeParameters.Add("ContentType", "application/json; charset=utf-8")
    $invokeParameters.Add("TimeoutSec", $timeoutSec)
    
    # Check for UseBasicParsing
    if ((Get-Command Invoke-RestMethod).Parameters.ContainsKey("UseBasicParsing"))
    {
    	# Add the basic parsing argument
        $invokeParameters.Add("UseBasicParsing", $true)
    }

	$Response = Invoke-RestMethod @invokeParameters
    Write-Verbose "Response: $Response"
}

Provided under the Apache License version 2.0.

Report an issue

To use this template in Octopus Deploy, copy the JSON below and paste it into the Library → Step templates → Import dialog.

{
  "Id": "110a8b1e-4da4-498a-9209-ef8929c31168",
  "Name": "Microsoft Teams - Post a message",
  "Description": "Posts a message to Microsoft Teams using a general webhook.",
  "Version": 24,
  "ExportedAt": "2023-08-31T20:39:39.222Z",
  "ActionType": "Octopus.Script",
  "Author": "twerthi",
  "Packages": [],
  "Parameters": [
    {
      "Id": "433c8776-2bff-44e0-a903-ab15288cadc8",
      "Name": "HookUrl",
      "Label": "Webhook Url",
      "HelpText": "The specific URL provided by Microsoft Teams when adding an _Incoming WebHook_ connector to a team channel. Copy and paste the full Webhook URL from Microsoft Teams here.",
      "DefaultValue": "",
      "DisplaySettings": {
        "Octopus.ControlType": "SingleLineText"
      }
    },
    {
      "Id": "3a51e22f-1c46-4b07-b91e-d36e70578463",
      "Name": "Title",
      "Label": "Message title",
      "HelpText": "The title of the message that will be posted to your Microsoft Teams channel.",
      "DefaultValue": "#{Octopus.Project.Name} #{Octopus.Release.Number} deployed to #{Octopus.Environment.Name}#{if Octopus.Deployment.Tenant.Id} for #{Octopus.Deployment.Tenant.Name}#{/if}",
      "DisplaySettings": {
        "Octopus.ControlType": "SingleLineText"
      }
    },
    {
      "Id": "11af257b-4c16-4a2a-8b5f-b42ab493d43d",
      "Name": "Body",
      "Label": "Message body",
      "HelpText": "The message body of post being added to your Microsoft Teams channel.",
      "DefaultValue": "For more information, please see [deployment details](#{if Octopus.Web.ServerUri}#{Octopus.Web.ServerUri}#{else}#{Octopus.Web.BaseUrl}#{/if}#{Octopus.Web.DeploymentLink})!",
      "DisplaySettings": {
        "Octopus.ControlType": "MultiLineText"
      }
    },
    {
      "Id": "ad6a1f33-949e-4570-966e-1e2bbdfa8042",
      "Name": "Color",
      "Label": "Color",
      "HelpText": "The color to use for the border on the side of the message.",
      "DefaultValue": "",
      "DisplaySettings": {
        "Octopus.ControlType": "SingleLineText"
      }
    },
    {
      "Id": "2d51e4e8-1f81-444f-934f-21a3051e7423",
      "Name": "Timeout",
      "Label": "Timeout in seconds",
      "HelpText": "The maximum timeout in seconds for each request.",
      "DefaultValue": "60",
      "DisplaySettings": {
        "Octopus.ControlType": "SingleLineText"
      }
    },
    {
      "Id": "b8835767-e7fe-4ef9-9492-893ca98950f6",
      "Name": "TeamsPostMessage.RetryPosting",
      "Label": "Retry posting message",
      "HelpText": "Should retries be made? If this option is enabled, the step will attempt to retry the posting of message to teams up to the set retry count. Default: `False`.",
      "DefaultValue": "False",
      "DisplaySettings": {
        "Octopus.ControlType": "Checkbox"
      }
    },
    {
      "Id": "da4ce68b-4813-5cea-c788-372e82643e93",
      "Name": "TeamsPostMessage.RetryCount",
      "Label": "Retry Count",
      "HelpText": "The maximum number of times to retry the post before allowing failure. Default 1",
      "DefaultValue": "1",
      "DisplaySettings": {
        "Octopus.ControlType": "SingleLineText"
      }
    },
    {
      "Id": "16d42450-c6c5-0b26-92a2-0b3e4eefb28e",
      "Name": "TeamsPostMessage.RetryDelay",
      "Label": "Retry delay in milliseconds",
      "HelpText": "The amount of time in milliseconds to wait between retries. Default 100",
      "DefaultValue": "100",
      "DisplaySettings": {
        "Octopus.ControlType": "SingleLineText"
      }
    }
  ],
  "Properties": {
    "Octopus.Action.Script.ScriptBody": "[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12\n# Helper functions\nfunction Retry-Command {\n    [CmdletBinding()]\n    Param(\n        [Parameter(Position=0, Mandatory=$true)]\n        [scriptblock]$ScriptBlock,\n \n        [Parameter(Position=1, Mandatory=$false)]\n        [int]$Maximum = 5,\n\n        [Parameter(Position=2, Mandatory=$false)]\n        [int]$Delay = 100\n    )\n\n    Begin {\n        $count = 0\n    }\n\n    Process {\n    \t$ex=$null\n        do {\n            $count++\n            \n            try {\n                Write-Verbose \"Attempt $count of $Maximum\"\n                $ScriptBlock.Invoke()\n                return\n            } catch {\n                $ex = $_\n                Write-Warning \"Error occurred executing command (on attempt $count of $Maximum): $($ex.Exception.Message)\"\n                Start-Sleep -Milliseconds $Delay\n            }\n        } while ($count -lt $Maximum)\n\n        # Throw an error after $Maximum unsuccessful invocations. Doesn't need\n        # a condition, since the function returns upon successful invocation.\n        throw \"Execution failed (after $count attempts): $($ex.Exception.Message)\"\n    }\n}\n# End Helper functions\n[int]$timeoutSec = $null\n[int]$maximum = 1\n[int]$delay = 100\n\nif(-not [int]::TryParse($OctopusParameters['Timeout'], [ref]$timeoutSec)) { $timeoutSec = 60 }\n\n\nIf ($OctopusParameters[\"TeamsPostMessage.RetryPosting\"] -eq $True) {\n\tif(-not [int]::TryParse($OctopusParameters['RetryCount'], [ref]$maximum)) { $maximum = 1 }\n\tif(-not [int]::TryParse($OctopusParameters['RetryDelay'], [ref]$delay)) { $delay = 100 }\n\t\n    Write-Verbose \"Setting maximum retries to $maximum using a $delay ms delay\"\n}\n\n$payload = @{\n    title = $OctopusParameters['Title']\n    text = $OctopusParameters['Body'];\n    themeColor = $OctopusParameters['Color'];\n}\n\nRetry-Command -Maximum $maximum -Delay $delay -ScriptBlock {\n\t# Declare variable for parameters\n    $invokeParameters = @{}\n    $invokeParameters.Add(\"Method\", \"POST\")\n    $invokeParameters.Add(\"Uri\", $OctopusParameters['HookUrl'])\n    $invokeParameters.Add(\"Body\", ($payload | ConvertTo-Json -Depth 4))\n    $invokeParameters.Add(\"ContentType\", \"application/json; charset=utf-8\")\n    $invokeParameters.Add(\"TimeoutSec\", $timeoutSec)\n    \n    # Check for UseBasicParsing\n    if ((Get-Command Invoke-RestMethod).Parameters.ContainsKey(\"UseBasicParsing\"))\n    {\n    \t# Add the basic parsing argument\n        $invokeParameters.Add(\"UseBasicParsing\", $true)\n    }\n\n\t$Response = Invoke-RestMethod @invokeParameters\n    Write-Verbose \"Response: $Response\"\n}",
    "Octopus.Action.Script.Syntax": "PowerShell",
    "Octopus.Action.Script.ScriptSource": "Inline"
  },
  "Category": "Microsoft Teams",
  "HistoryUrl": "https://github.com/OctopusDeploy/Library/commits/master/step-templates//opt/buildagent/work/75443764cd38076d/step-templates/microsoft-teams-post-a-message.json",
  "Website": "/step-templates/110a8b1e-4da4-498a-9209-ef8929c31168",
  "Logo": "iVBORw0KGgoAAAANSUhEUgAAAHgAAAB4CAYAAAA5ZDbSAAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAVRAAAFUQHa5EyvAAAAB3RJTUUH4AwNAhIcgn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QTnT4ZKrSdqu+G9F9hxwQCH64EKCSTBBggkSTJBgggQTJJggwSSYIMEECSZIMHEgBc/fkciMwur6Q/PNDy40/6iUJRXMRjyRxuyspJ7KMmMKwYU4aPOagNz84Ewm+/ibLbPyZztSHWxQJiYjSdPNDyZyXB29rV2QtOL5wSTYYKX2t1dvfxiPp7UJR/DamG/YNEnWQSAciSEeT2NxcXPzzkL0oWqtaO0KAMF0qvLpLyS4xrw5EXa+ORF+0i7NymsXDPh+pSWXkqwaMTdffRteBkYOAcerlUsluAa8/c6yhN3LMJTClMwQsMoIVLp8Pwneh46Jt95eblRt+i8DXiu0b5ZhCzKmmQVb+UnitYAE6yj369+c3Mhksi2qOvQ1PcIs1cEGkStJiRZ1x8SHKVx+2udGJbhKsf94917yN1dmWDqdbdEkSrwRHlRJggsQCC5unjrV3FzoOQtz8xJW1+LJ926uSAWec5TnklGeX0gPp9SXGGMYUBZaMQRUB+uEDIykU+CMJJdCdPXMyAx+vduuJLj2pbEHDJ5CK+TIQFgGwkZ6RjAJLhNFXsgM10J1sMkhwSan7BAtM3yNARxkeJBbUNNJt9G4VL2yuSCIXAbgLIA3C3As9/z67nq+KXqt+G4KwaWIl3MlnUOBJ2GT4DoVXIy+i6KHybkQr4j3oLRFsklwPQguRq8gepkS4mXAq5R4Nwk2ieBC8LzYZLXDAwbPfiZ2JNgg4muV2JFgg6JXYkeC64xyEzsSbBKKJXbpFJqNMBqDIAiCIAiCIAiCIAiCIAiCIOqB/wGehFMglNgQpQAAAABJRU5ErkJggg==",
  "$Meta": {
    "Type": "ActionTemplate"
  }
}

History

Page updated on Thursday, August 31, 2023