Microsoft Teams: Send and Receive Notifications

Disclaimer

Your use of this download is governed by Stonebranch’s Terms of Use, which are available at https://www.stonebranch.com/integration-hub/Terms-and-Privacy/Terms-of-Use/.

Overview

This Universal Task allows you to send messages to an existing channel of Microsoft Teams. As a result, you can integrate this solution in UAC to notify users for UAC result or send approval notifications on Microsoft teams.

Key Features

  • Quick reaction time on job failures.

  • Manual task interruptions in workflows can be handled by concerned applications/business team, while workflows in Universal Controller can be resumed simply by responding to the approval notifications on Microsoft Teams.


Software Requirements

Software Requirements for Universal Template and Universal Task

This integration requires an Universal Agent and a Python runtime to execute the Universal Task.

  • Requires Python 3.6 or higher. Tested with the Universal Agent bundled Python distribution.

  • Python modules required:

    • requests

Software Requirements for Universal Agent

  • Universal Agent for Windows x64 Version 6.9.0.0 and later with python options installed

  • Universal Agent for Linux Version 6.9.0.0 and later with python options installed

Software Requirements for Universal Controller

  • Universal Controller Version 6.9.0.0 and later

Software Requirements for the Application to be Scheduled

The Universal Task requires an Incoming Team channel and a Serverless Infrastructure like AWS Lambda or Google Cloud Functions or Microsoft Azure Functions.


Technical Considerations

Adding an Incoming webhook to a Microsoft Teams Channel

Note

If your MS Team's Settings => Member permissions => Allow members to create, update, and remove connectors is selected, any team member can add, modify, or delete a connector.

  1. Navigate to the channel where you want to add the webhook and select (•••) More Options from the top navigation bar.

  2. Choose Connectors from the drop-down menu and search for Incoming webhook.

  3. Select the Configure button, provide a name, and, optionally, upload an image avatar for your webhook.

  4. The dialog window will present a unique URL that will map to the channel. Make sure that you copy and save the URL you will need to provide it to the outside service.

  5. Select the Done button. The webhook will be available in the team channel.

Additional Information on How to Use Approval Notification Feature

Manual tasks are typically used when there is a need for manual intervention of user in a workflow process. Traditionally the Manual Task is completed successfully in the Universal controller by clicking “Set Completed” command.

With this Universal Task for Microsoft Teams, we can provide you with a notification in the Microsoft team incoming webhook  channel, when the workflow reaches the manual task with status “Action Required”.

Upon receiving the notification on the teams channel, users can click on on the “Approve” Button in the interactive message for the workflow to proceed further. This interactive message is sent from the Universal Controller.

When the “Approve” or “Reject” button is clicked in the interactive message, an API call is made to a function where it can handle the event from the Microsoft Teams. For example we use python function in AWS lambda + API gateway or Azure functions or any custom URL where the Teams messaging platform can make an API POST call to handle the user action in the message as a payload and, based on the posted payload data from the Teams, Universal Controller API call will be made to set the manual task either to set complete status or No action in the function. Please refer to the handler.py file in the serverless function folder for a sample serverless function implementation using AWS lambda.

For Approval Notification feature of the Universal Task, the “API Endpoint” provided in the task details could be an end point either in AWS lambda or Azure Function or GCP function or your custom API end point to handle the interactive message from Microsoft Teams.

Below is the sample python code that could be invoked for the Microsoft Teams Approval Notification. In the code below, update the following variables accordingly under def_handler()

  • teams_incoming_webhook = 'XXXX' # The incoming web hook of Microsoft Teams channel
    uname = 'XXXX' # Universal Controller user name
    passwd = 'XXXX' # Universal Controller user password
    uc_url = 'http:// + uname + ':' + passwd + '@XXXXXX/resources/taskinstance/setcompleted' # URL of the Universal Controller


import json
import boto3
import logging
from urllib.parse import parse_qs
import requests

logger = logging.getLogger()
logger.setLevel(logging.INFO)


def lambda_handler(event, context):
    print(str(event))
    logger.info(json.dumps(event))
    payload = event['body']
    print(payload)
    jobname_split = payload.split(':')
    jobname = jobname_split[1]
    team_button = jobname_split[0]
    print(team_button)
    print(jobname)
    ###################### Teams Channel Data ################
    teams_incoming_webhook = 'XXXX'
    ###################### End of Teams Channel Data ################
    ############## Credentials for universal controller ################
    uname = 'XXXX'
    passwd = 'XXXX'
    uc_url = 'http://' + uname + ':' + passwd + \
             '@XXXXXX/resources/taskinstance/setcompleted'
    ############## End of Universal Controller Credentials ################
    # Posting request to Universal Controller
    uc_post_request(team_button, jobname, uc_url, teams_incoming_webhook)
    ################## Teams data parsed -completed ###########################
    body = {
        "message": "Teams Data parsed successfully and Universal controller "
                   "confirmed the job !",
        "input": event
    }
    response = {
        "statusCode": 200,
        "body": json.dumps(body)
    }
    return response


def uc_post_request(team_button, jobname, uc_url, teams_incoming_webhook):
    header = {'content-type': "application/json"}
    if team_button=="Approved":
        print("Intiating Request to Universal Controller")
        approval_message = {
            "name": jobname,
            "criteria": "Newest Instance"
        }
        print(uc_url)
        post_uc = requests.post(uc_url, data=json.dumps(approval_message),
            headers=header)
        # print(post_uc.text)
        if post_uc.status_code==200:
            format_response = post_uc.json()
            logger.info(format_response)
            if format_response['success'] is False:
                print("Something went wrong")
                error_message = {
                    "@type": "MessageCard",
                    "@context": "https://schema.org/extensions",
                    "summary": "This is the summary property",
                    "themeColor": "#FFFF00",
                    "sections": [
                        {
                            "activityTitle": "**Couldn't not reach**",
                            "activitySubtitle": "Something went wrong, "
                                                "action not completed"
                        }
                    ]
                }
                print("Sending error report to MS Teams Channel")
                uc_response = requests.post(teams_incoming_webhook,
                    data=json.dumps(error_message),
                    headers={'CARD-UPDATE-IN-BODY': 'True',
                             'Content-Type': 'application/json'})
            elif format_response['success'] is True:
                print("Your request is approved")
                approval_response = {
                    "@type": "MessageCard",
                    "@context": "https://schema.org/extensions",
                    "summary": "This is the summary property",
                    "themeColor": "#008000",
                    "sections": [
                        {
                            "activityTitle": "**Approved**",
                            "activitySubtitle": "Request was approved after "
                                                "review"
                        }
                    ]
                }
                header = {
                    'content-type': 'application/json'
                }
                print("Sending Notification to MS Teams Channel")
                uc_response = requests.post(teams_incoming_webhook,
                    data=json.dumps(approval_response), headers=header)
                format_response = json.loads(uc_response.text)
                print(format_response)
    elif team_button=="Rejected":
        print("Reqeust Denied")
        reject_response = {
            "@type": "MessageCard",
            "@context": "https://schema.org/extensions",
            "summary": "This is the summary property",
            "themeColor": "#FF0000",
            "sections": [
                {
                    "activityTitle": "**Rejected**",
                    "activitySubtitle": "Request was rejected after review"
                },
            ]
        }
        print("Sending Notification to MS Teams Channel")
        uc_response = requests.post(teams_incoming_webhook,
            data=json.dumps(reject_response),
            headers={'CARD-UPDATE-IN-BODY': 'True',
                     'Content-Type': 'application/json'})
        print("Teams Response: ", uc_response.status_code)

Microsoft Teams Integration

Key Features

Feature

Description

Send Message

With Send Message function we can send a notification message to the Microsoft Teams channel with the current task instance details such as job failure, late start/run, and other important events.

Approval Notification

With Approval notifications, an interactive message is sent to the Microsoft Teams incoming channel. The user can chose to Approve or Reject the continuation of workflow execution.

Import Microsoft Teams Integration Downloadable Universal Template

To use this downloadable Universal Template, you first must perform the following steps:

  1. This Universal Task requires the Resolvable Credentials feature. Check that the Resolvable Credentials Permitted system property has been set to true.
  2. To import the Universal Template into your Controller, follow the instructions here.
  3. When the files have been imported successfully, refresh the Universal Templates list; the Universal Template will appear on the list.

Configure Microsoft Teams Integration Universal Task

For the new Universal Task type, create a new task, and enter the task-specific details that were created in the Universal Template.


Field Descriptions for Microsoft Teams Integration Universal Task

Field

Description

Send Message

Teams Function

Send Message or Approval Notification.

Job Name

Name of the job, by default it takes the current job name ${ops_task_name}.

Job Status

Status of the job, by default it takes the current job name ${ops_status}.

MS Teams Webhook

The incoming web hook of Microsoft Teams channel.

Execution User

Details of the execution user, by default takes the current user name ${ops_execution_user}.

Job type

Task type of task instance, by default takes the current task instance type ${ops_task_type}.

Message Title

The title of the message sent to Microsoft Teams channel.

Message Text

The text of the message sent to Microsoft Teams channel.

Approval Notification

API Endpoint

URL of the Serverless infrastructure endpoint.


Examples for Microsoft Teams Integration Universal Tasks

Send Message


Approval Notification


Document References

This document references the following documents:

Name

Location

Description

Universal Templates

Universal Templates

User documentation for creating Universal Templates in the Universal Controller user interface.

Universal Tasks

Universal Tasks

User documentation for creating Universal Tasks in the Universal Controller user interface.

Microsoft Teams Wenhooks

https://docs.microsoft.com/en-us/microsoftteams/platform/webhooks-and-connectors/how-to/add-incoming-webhook

User documentation for creating incoming webhooks in Microsoft Teams Channel.

Requests

https://pypi.org/project/requests/#description

Documentation for python requests module.