'Send automated messages to Microsoft Teams using Python

I want to run a script of Python and in the end send the results in a text format to a couple of employees through MS Teams

Is there any already build library that would allow me to send a message in Microsoft Teams through Python code?



Solution 1:[1]

1. Create a webhook in MS Teams

Add an incoming webhook to a Teams channel:

  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.

2. Install pymsteams

pip install pymsteams

3. Create your python script

import pymsteams
myTeamsMessage = pymsteams.connectorcard("<Microsoft Webhook URL>")
myTeamsMessage.text("this is my text")
myTeamsMessage.send()

More information available here:

Add a webook to MS Teams

Python pymsteams library

Solution 2:[2]

Send Msteams notification without an additional package.

A simple way to send messages to teams without using any external modules. This is basically under the hood of pymsteams module. It is more useful when you are using AWS Lambda as you don't have to add layers in Lambda or supply pymsteams module as a deployment package.

import urllib3
import json


class TeamsWebhookException(Exception):
    """custom exception for failed webhook call"""
    pass


class ConnectorCard:
    def __init__(self, hookurl, http_timeout=60):
        self.http = urllib3.PoolManager()
        self.payload = {}
        self.hookurl = hookurl
        self.http_timeout = http_timeout

    def text(self, mtext):
        self.payload["text"] = mtext
        return self

    def send(self):
        headers = {"Content-Type":"application/json"}
        r = self.http.request(
                'POST',
                f'{self.hookurl}',
                body=json.dumps(self.payload).encode('utf-8'),
                headers=headers, timeout=self.http_timeout)
        if r.status == 200: 
            return True
        else:
            raise TeamsWebhookException(r.reason)


if __name__ == "__main__":
    myTeamsMessage = ConnectorCard(MSTEAMS_WEBHOOK)
    myTeamsMessage.text("this is my test message to the teams channel.")
    myTeamsMessage.send()

reference: pymsteams

Solution 3:[3]

Here's a simple, third-party package-free solution inspired by @nirojshrestha019's solution:

1. Create a webhook in MS Teams

Add an incoming webhook to a Teams channel:

  1. Navigate to the channel where you want to add the webhook and select (•••) Connectors from the top navigation bar.
  2. Search for Incoming Webhook, and add it.
  3. Click Configure and provide a name for your webhook.
  4. Copy the URL which appears and click "OK".

2. Make a script!

import json
import sys
from urllib import request as req


class TeamsWebhookException(Exception):
    pass


WEBHOOK_URL = "https://myco.webhook.office.com/webhookb2/abc-def-ghi/IncomingWebhook/blahblah42/jkl-mno"


def post_message(message: str) -> None:
    request = req.Request(url=WEBHOOK_URL, method="POST")
    request.add_header(key="Content-Type", val="application/json")
    data = json.dumps({"text": message}).encode()
    with req.urlopen(url=request, data=data) as response:
        if response.status != 200:
            raise TeamsWebhookException(response.reason)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Joeypencil
Solution 2 Zev Averbach
Solution 3 Zev Averbach