Ric*_*aça 22 python microsoft-teams
我想运行一个 Python 脚本,最后通过 MS Teams 将结果以文本格式发送给几个员工
是否有任何已经构建的库允许我通过 Python 代码在 Microsoft Teams 中发送消息?
AK4*_*K47 62
1. 在 MS Teams 中创建 webhook
将传入的 webhook 添加到 Teams 频道:
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)
此处提供更多信息:
nir*_*019 23
一种无需使用任何外部模块即可向团队发送消息的简单方法。这基本上是在 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 更新了说明:
\n1. 在 MS Teams 中创建 webhook
\n将传入 Webhook 添加到 Teams 频道:
\n2. 制作脚本!
\nimport 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)
归档时间: |
|
查看次数: |
37187 次 |
最近记录: |