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

Ric*_*aça 22 python microsoft-teams

我想运行一个 Python 脚本,最后通过 MS Teams 将结果以文本格式发送给几个员工

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

AK4*_*K47 62

1. 在 MS Teams 中创建 webhook

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

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

2.安装pymsteams

pip install pymsteams
Run Code Online (Sandbox Code Playgroud)

3.创建你的python脚本

import pymsteams
myTeamsMessage = pymsteams.connectorcard("<Microsoft Webhook URL>")
myTeamsMessage.text("this is my text")
myTeamsMessage.send()
Run Code Online (Sandbox Code Playgroud)

此处提供更多信息:

将电子书添加到 MS Teams

Python pymsteams 库


nir*_*019 23

发送 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()
Run Code Online (Sandbox Code Playgroud)

参考资料: pymsteams


Zev*_*ach 17

这是一个简单的第三方无包解决方案,灵感来自@nirojsshrestha019 的解决方案,步骤更少,并且针对 Microsoft 不断变化的 UI 更新了说明:

\n

1. 在 MS Teams 中创建 webhook

\n

将传入 Webhook 添加到 Teams 频道:

\n
    \n
  1. 导航到要添加 Webhook 的通道,然后从顶部导航栏中选择 (\xe2\x80\xa2\xe2\x80\xa2\xe2\x80\xa2)连接器。
  2. \n
  3. 搜索Incoming Webhook并添加它。
  4. \n
  5. 单击配置并为您的 Webhook 提供名称。
  6. \n
  7. 复制出现的 URL,然后单击“确定”。
  8. \n
\n

2. 制作脚本!

\n
import json\nimport sys\nfrom urllib import request as req\n\n\nclass TeamsWebhookException(Exception):\n    pass\n\n\nWEBHOOK_URL = "https://myco.webhook.office.com/webhookb2/abc-def-ghi/IncomingWebhook/blahblah42/jkl-mno"\n\n\ndef post_message(message: str) -> None:\n    request = req.Request(url=WEBHOOK_URL, method="POST")\n    request.add_header(key="Content-Type", val="application/json")\n    data = json.dumps({"text": message}).encode()\n    with req.urlopen(url=request, data=data) as response:\n        if response.status != 200:\n            raise TeamsWebhookException(response.reason)\n\nif __name__ == "__main__":\n    post_message("hey this is my message")\n
Run Code Online (Sandbox Code Playgroud)\n


小智 7

添加基于 Python 的 requests 库的代码片段以确保完整性。

与其他答案相比,这很有用,因为所有主要的 Linux 发行版都提供了一个python3-requests包,但没有提供一个python3-msteams包。

#!/usr/bin/env python3

import requests

WEBHOOK_URL = "https://..."

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

postTeamsMessage("Hello there")
Run Code Online (Sandbox Code Playgroud)