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?
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:
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:
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, 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:
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")
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")