[英]Send automated messages to Microsoft Teams using Python
我想運行一個 Python 腳本,最后通過 MS Teams 將結果以文本格式發送給幾個員工
是否有任何已經構建的庫可以讓我通過 Python 代碼在 Microsoft Teams 中發送消息?
1. 在 MS Teams 中創建一個 webhook
將傳入 Webhook 添加到 Teams 頻道:
2.安裝pymsteam
pip install pymsteams
3. 創建你的 python 腳本
import pymsteams
myTeamsMessage = pymsteams.connectorcard("<Microsoft Webhook URL>")
myTeamsMessage.text("this is my text")
myTeamsMessage.send()
更多信息可在此處獲得:
一種無需使用任何外部模塊即可向團隊發送消息的簡單方法。 這基本上是在 pymsteams 模塊的底層。 當您使用 AWS Lambda 時,它更有用,因為您不必在 Lambda 中添加層或提供 pymsteams 模塊作為部署包。
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()
參考:pymsteams
這是一個受@nirojshrestha019 的解決方案啟發的簡單的第三方無包解決方案:
1. 在 MS Teams 中創建一個 webhook
將傳入 Webhook 添加到 Teams 頻道:
2. 編寫腳本!
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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.