【发布时间】:2022-05-12 17:32:17
【问题描述】:
我想运行一个 Python 脚本,最后通过 MS Teams 将结果以文本格式发送给几个员工
是否有任何已经构建的库可以让我通过 Python 代码在 Microsoft Teams 中发送消息?
【问题讨论】:
我想运行一个 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()
更多信息在这里:
【讨论】:
Settings => Member permissions => Allow members to create, update, and remove connectors。如果选择它,任何团队成员都可以添加、修改或删除连接器。
一种无需使用任何外部模块即可向团队发送消息的简单方法。这基本上是在 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
【讨论】:
urllib3)
这是一个受@nirojshrestha019's solution启发的简单的第三方无包解决方案:
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)
【讨论】: