使用 Python 向 Microsoft Teams 自动发送消息

Send automated messages to Microsoft Teams using Python

我想 运行 一个 Python 的脚本,最后通过 MS Teams

将结果以文本格式发送给几个员工

是否有任何已经构建的库允许我通过 Python 代码在 Microsoft Teams 中发送消息?

1.在 MS Teams

中创建 webhook

将传入的 webhook 添加到 Teams 频道:

  1. 导航到要添加 webhook 的频道,然后从顶部导航栏select (•••) 更多选项
  2. 从下拉菜单中选择 Connectors 并搜索 Incoming Webhook.
  3. Select 配置 按钮,提供名称,并可选择为您的 webhook 上传图像头像。
  4. 对话框 window 将显示一个唯一的 URL 映射到频道。确保复制并保存 URL — 您需要将其提供给外部服务。
  5. Select 完成 按钮。 webhook 将在团队频道中提供。

2。安装 pymsteams

pip install pymsteams

3。创建您的 python 脚本

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

此处提供更多信息:

Add a webook to MS Teams

Python pymsteams library

无需附加包即可发送 Msteams 通知。

一种无需使用任何外部模块即可向团队发送消息的简单方法。这基本上是在 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

这是一个简单的 third-party package-free 解决方案,灵感来自 :

1.在 MS Teams

中创建 webhook

将传入的 webhook 添加到 Teams 频道:

  1. 从顶部导航栏导航到要添加网络钩子和 select (•••) 连接器 的频道。
  2. 搜索 Incoming Webhook,然后添加它。
  3. 单击配置 并为您的 webhook 提供一个名称。
  4. 复制出现的URL,然后点击“确定”。

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)