简体   繁体   中英

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?

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

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM