一、需求背景
在实际业务中,我们经常会遇到这种情况:需要定时的发送一些业务监控结果给相应的负责人。可能有些人会说我可以通过SendEmail来发送邮件啊,或者是通过python的微信模块发送微信给相应的负责人。当然,这些都是可以的。只是对于工作中用钉钉作为交流联系的人来说,钉钉显然是更加方便的。
二、整体架构
业务代码中的定时任务会去数据库中查询业务此时的情况,并将查询的结果写入到一个文件中。
我们要做的就是把这个文件中的内容发送到钉钉群中。
三、获取钉钉群的webhook值
1)先把相关的人员建一个钉钉群
2)点击右上角的"群设置"
3)点击"群机器人"
4)点击"自定义"
5)点击"添加"
6)给机器人起个名字,点击"完成"
7)点击"复制",把webhook的值先粘贴到记事本上备用,并点击"完成"
四、python代码
由于监控文件有两种,一种是根据日期生产的(每天一个),一种是根据日期加小时生成的(每天多个),所以在写文件路径时需要写两种,运行时也需要指定额外的参数(这里是"run1"和"run2")。代码如下,你需要把__init__方法中的self.url换成上面获取的webhook值。
import dingtalkchatbot.chatbot as cb
import datetime
import sys
import platform
Today = datetime.datetime.now().strftime('%Y%m%d')
Hour = datetime.datetime.now().strftime('%Y%m%d%H')
os = platform.system()
if os == 'Windows':
path_day = "C:\\Users\\hehe\\Desktop\\临时\\" + Today + ".txt"
path_hour = "C:\\Users\\hehe\\Desktop\\临时\\" + Hour + ".txt"
else:
path_day = "/home/edsuser/dingding_monitor/" + Today + ".txt"
path_hour = "/home/edsuser/dingding_monitor/" + Hour + ".txt"
class dingRobot():
def __init__(self,filepath):
self.url = "https://oapi.dingtalk.com/robot/send?access_token=c791ce94199b187d1e58c484febfee8f8ea5258d6c933352001e2532eb426aae"
self.path = filepath
def getMessage(self):
message = ""
for line in open(self.path, encoding="utf-8", errors="ignore"):
message = message + line
return message
def dingStart(self):
msg = self.getMessage()
xiaoding = cb.DingtalkChatbot(self.url)
xiaoding.send_text(msg=msg)
if __name__ == "__main__":
if sys.argv[1] == 'run1':
dingding = dingRobot(path_day)
dingding.dingStart()
elif sys.argv[1] == 'run2':
dingding = dingRobot(path_hour)
dingding.dingStart()
else:
print("The argument was wrong! please use 'run1' or 'run2'")
五、写定时任务定时执行python脚本
按自己规划的时间把python脚本的执行写入到crond中。