很多企业内部的交流工具都支持自定义机器人(或者叫做webhook),简单来讲就是可以按照企业交流工具提供的API来自动化的通知、提醒,甚至反馈、执行任务等操作。下面以倍洽(https://bearychat.com)为例,介绍实现通知机器人的方法。
Incoming
按照 BearyChat API 灵活实现自己的服务,并向指定讨论组推送内容
使用说明:
发送一个 JSON 字符串做为 POST 请求的 body, Content-Type 为 application/json
JSON 格式要求
示例:
{
"text": "text, this field may accept markdown",
"markdown": true,
"channel": "bearychat-dev",
"attachments": [
{
"title": "title_1",
"url": "https://bearychat.com",
"text": "attachment_text",
"color": "#ffa500",
"images": [
{"url": "http://img3.douban.com/icon/ul15067564-30.jpg"}
]
}
]
}
简单的描述下这个通知机器人:就是往API提供的接口,按照指定的格式,发送一些字符串。
我们用curl来测试一下:
curl 'https://hook.bearychat.com/=bwIfL/incoming/50bf88375cb3eeba5c6e56ac6e38exxx' \
-H 'Content-Type: application/json' \
-d '{"text":"incoming机器人测试消息"}'
为了便于与具体应用集成,我们把这个功能包装成函数。
import urllib.request
import urllib.parse
import json
import logging as log
#
# txt: contents to be sent
# ch: send to group '所有人' default
#
def send_notice(txt, ch='所有人'):
try:
# txt -> json
params = json.dumps({"text": txt}).encode()
# set headers
headers = {"Content-type": "application/json", "Accept": "text/plain"}
# prepare req data
req = urllib.request.Request('https://hook.bearychat.com/=bwIfL/incoming/50bf88375cb3eeba5c6e56ac6e38exxx',params,headers)
# post data to api url
res = urllib.request.urlopen(req)
# receive feedback data
data = res.read().decode()
print(data)
except Exception as e:
# emit any error
log.error(e)
if __name__ == '__main__':
send_notice("""icknow知识库文章更新:
增加了:
克隆并切换分支的使用方法。
详见下面的链接:
[Mercurial HG Practical Commands](http://192.168.0.116:3000/tutorial/hg)
""")
效果如下: