Send automated messages to Microsoft Teams using Python

Question:

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?

Asked By: Ricardo Vilaça

||

Answers:

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. 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

Answered By: AK47

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

Answered By: nirojshrestha019

Here’s a simple, third-party package-free solution inspired by @nirojshrestha019’s solution, with fewer steps and updated instructions for Microsoft’s ever-changing UIs:

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)

if __name__ == "__main__":
    post_message("hey this is my message")
Answered By: Zev Averbach

Adding a code snippet based on Python’s requests library for completeness.

Compared to the other answers this is useful as all major Linux distros provide a python3-requests package but not a python3-msteams package.

#!/usr/bin/env python3

import requests

WEBHOOK_URL = "https://..."

def postTeamsMessage(text):
        jsonData = {
          "text": text
        }
        requests.post(WEBHOOK_URL, json=jsonData)

postTeamsMessage("Hello there")
Answered By: NrY
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.