模块安装
$ pip3 install DingtalkChatbot
代码编写
from dingtalkchatbot.chatbot import DingtalkChatbot
import datetime
def dingtalk_robot(wehook, mobiles, text):
ddrobot = DingtalkChatbot(wehook)
ret = ddrobot.send_markdown(title='Python自动化', text=text, is_at_all=False, at_mobiles=mobiles)
print(ret) # {'errcode': 0, 'errmsg': 'ok'}
if __name__ == '__main__':
t = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
url = 'http://example.org/'
mobiles = ['12600110111']
text=('''<font color=\'#FFA500\'>[通知] </font>项目首页报警'''
+ '''\n\n --- \n\n'''
+ '''<font color=\'#778899\' size=2>项目名称:测试项目首页检查</font> \n\n '''
+ '''<font color=\'#708090\' size=2>错误详情:[点击查看错误详情](%s)</font> \n\n '''
+ '''<font color=\'#708090\' size=2>检测分支:QAmain</font> \n\n'''
+ '''<font color=\'#708090\' size=2>bug数量:</font><font color=\'#FF0000\' size=2>0</font> \n\n'''
+ '''<font color=\'#708090\' size=2>相关人员:@%s</font>'''
+ '''\n\n --- \n\n'''
+ '''播报时间:%s''') % ( url, mobiles[0], t)
wehook = 'https://oapi.dingtalk.com/robot/send?access_token=paste_your_token_from_dingtalk'
dingtalk_robot(wehook, mobiles, text)
wehook1参数从钉钉设置里获取。
钉钉设置
PC上打开钉钉->选择一个业务群->打开群设置->点击“智能群助手”->添加机器人,填写如下内容:
- 机器人名称:任意,e.g. Rachel
- 消息推送:开启
- 安全设置:自定义关键词,添加关键词,e.g. QA,Test,Python
- Wehook: 复制链接,比如 https://oapi.dingtalk.com/robot/send?access_token=6862b4f6ec7ae1e4360300dc18c8b15d58fe3248bed9c4394e013ff0b9e40333