Python3使用钉钉机器人推送消息(签名方式)
import time
import hmac
import hashlib
import base64
import urllib
import json
import requests
import logging try:
JSONDecodeError = json.decoder.JSONDecodeError
except AttributeError:
JSONDecodeError = ValueError def is_not_null_and_blank_str(content):
if content and content.strip():
return True
else:
return False class DingtalkRobot(object):
def __init__(self, webhook, sign=None):
super(DingtalkRobot, self).__init__()
self.webhook = webhook
self.sign = sign
self.headers = {'Content-Type': 'application/json; charset=utf-8'}
self.times = 0
self.start_time = time.time() # 加密签名
def __spliceUrl(self):
timestamp = int(round(time.time() * 1000))
secret = self.sign
secret_enc = secret.encode('utf-8')
string_to_sign = '{}\n{}'.format(timestamp, secret)
string_to_sign_enc = string_to_sign.encode('utf-8')
hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))
url = f"{self.webhook}×tamp={timestamp}&sign={sign}"
return url def send_text(self, msg, is_at_all=False, at_mobiles=[]):
data = {"msgtype": "text", "at": {}}
if is_not_null_and_blank_str(msg):
data["text"] = {"content": msg}
else:
logging.error("text类型,消息内容不能为空!")
raise ValueError("text类型,消息内容不能为空!") if is_at_all:
data["at"]["isAtAll"] = is_at_all if at_mobiles:
at_mobiles = list(map(str, at_mobiles))
data["at"]["atMobiles"] = at_mobiles logging.debug('text类型:%s' % data)
return self.__post(data) def __post(self, data):
"""
发送消息(内容UTF-8编码)
:param data: 消息数据(字典)
:return: 返回发送结果
"""
self.times += 1
if self.times > 20:
if time.time() - self.start_time < 60:
logging.debug('钉钉官方限制每个机器人每分钟最多发送20条,当前消息发送频率已达到限制条件,休眠一分钟')
time.sleep(60)
self.start_time = time.time() post_data = json.dumps(data)
try:
response = requests.post(self.__spliceUrl(), headers=self.headers, data=post_data)
except requests.exceptions.HTTPError as exc:
logging.error("消息发送失败, HTTP error: %d, reason: %s" % (exc.response.status_code, exc.response.reason))
raise
except requests.exceptions.ConnectionError:
logging.error("消息发送失败,HTTP connection error!")
raise
except requests.exceptions.Timeout:
logging.error("消息发送失败,Timeout error!")
raise
except requests.exceptions.RequestException:
logging.error("消息发送失败, Request Exception!")
raise
else:
try:
result = response.json()
except JSONDecodeError:
logging.error("服务器响应异常,状态码:%s,响应内容:%s" % (response.status_code, response.text))
return {'errcode': 500, 'errmsg': '服务器响应异常'}
else:
logging.debug('发送结果:%s' % result)
if result['errcode']:
error_data = {"msgtype": "text", "text": {"content": "钉钉机器人消息发送失败,原因:%s" % result['errmsg']},
"at": {"isAtAll": True}}
logging.error("消息发送失败,自动通知:%s" % error_data)
requests.post(self.webhook, headers=self.headers, data=json.dumps(error_data))
return result if __name__ == '__main__':
URL = "你的钉钉机器人地址"
SIGN = "签名"
ding = DingtalkRobot(URL, SIGN)
print(ding.send_text("Hello World"))
做通知实例,如图:

Python3使用钉钉机器人推送消息(签名方式)的更多相关文章
- nodejs通过钉钉群机器人推送消息
nodejs 通过钉钉群机器人推送消息 Intro 最近在用 nodejs 写爬虫,之前的 nodejs 爬虫代码用 js 写的,感觉可维护性太差,也没有智能提示,于是把js改用ts(typescri ...
- Java项目中集成钉钉机器人推送消息提醒
前言: 项目中有一个需求,当有新订单产生的时候,希望能够及时通知到业务相关人员进行处理,整体考虑了一下,选用了钉钉机器人提醒功能(公司内部主要也是使用钉钉进行通讯). 操作: 主要分为两部分进行处理: ...
- 极光推送消息——RegistrationID方式
1.工具类 package com.test.util; import cn.jiguang.common.resp.APIConnectionException; import cn.jiguang ...
- 钉钉机器人集成Jenkins推送消息模板自定义发送报告
一.由于公司同样也使用了钉钉.那么在做Jenkins集成自动化部署的时候,也是可以集成钉钉的. 那种Jenkins下载钉钉插件集成,简单设置就可以完成了.我们今天要做的是,定制化的发送消息. 钉钉推送 ...
- 使用PushSharp给iOS应用推送消息
PushSharp是一个C#编写的服务端类库,用于推送消息到各种客户端,支持iOS(iPhone/iPad).Android.Windows Phone.Windows 8.Amazo.Blackbe ...
- android不需要Socket的跨进程推送消息AIDL!
上篇介绍了跨进程实时通讯http://www.cnblogs.com/xiaoxiaing/p/5818161.html 但是他有个缺点就是服务端无法推送消息给客户端,今天这篇文章主要说的就是服务器推 ...
- 使用极光推送(www.jpush.cn)向安卓手机推送消息【服务端向客户端主送推送】C#语言
在VisualStudio2010中新建网站JPushAndroid.添加引用json帮助类库Newtonsoft.Json.dll. 在web.config增加appkey和mastersecret ...
- 用JPUSH极光推送实现服务端向安装了APP应用的手机推送消息(C#服务端接口)
这次公司要我们做一个功能,就是当用户成功注册以后,他登录以后要收到消息,当然这个消息是安装了我们的手机APP应用的手机咯. 极光推送的网站的网址是:https://www.jpush.cn/ 极光推送 ...
- iOS点击推送消息跳到应用指定页面
现在的推送用的越来越频繁,几乎每个应用都开始用到了.其实又有几个用户会去看推送消息呢?没办法,产品经理最大啊,只是苦了我们这一帮程序员啊!闲话少说,进入正题.兄弟我用的是极光推送,自然是以极光推送为例 ...
随机推荐
- storcli 命令(更新Ing)
help [root@centos7]# storcli -h Storage Command Line Tool Ver 007.0606.0000.0000 Mar , (c)Copyright ...
- SpringBoot---SpringMVC关于拦截器的一些问题总结
SpringBoot---SpringMVC关于拦截器的一些问题总结 环境: IDEA :2020.1 Maven:3.5.6 SpringBoot: 2.3.2 1.直接在地址栏输入 http:// ...
- SpringBoot 集成SpringSecurity JWT
目录 1. 简介 1.1 SpringSecurity 1.2 OAuth2 1.3 JWT 2. SpringBoot 集成 SpringSecurity 2.1 导入Spring Security ...
- [PyTorch 学习笔记] 1.1 PyTorch 简介与安装
PyTorch 的诞生 2017 年 1 月,FAIR(Facebook AI Research)发布了 PyTorch.PyTorch 是在 Torch 基础上用 python 语言重新打造的一款深 ...
- java基础-03:注释
1.注释的意义: (1) 为了更好的阅读自己编写的代码,方便日后代码维护,建议添加注释. (2) 有利于团队协作. (3) 代码即文档.程序源代码是程序文档的重要组成部分. 2.注释分类 (1) 单行 ...
- DataNode(面试开发重点)
1 DataNode工作机制 DataNode工作机制,如图所示. 1)一个数据块在DataNode上以文件形式存储在磁盘上,包括两个文件,一个是数据本身,一个是元数据包括数据块的长度,块数据的校验和 ...
- LeetCode 92 | 大公司常考的面试题,翻转链表当中指定部分
今天是LeetCode专题的第58篇文章,我们一起来看看LeetCode 92题,翻转链表II(Reverse LInked List II). 这题的官方难度是Medium,2451个赞同,145个 ...
- k8s 辨析 port、NodePort、targetPort、containerPort 区别
刚接触 k8s 涉及到端口到内容较多,容易混淆,这里整理如下: 目录 nodePort port targetPort containerPort 参考文章 nodePort nodePort 提供了 ...
- Linux下Vim常用操作
linux下Vim的常用操作 linux 首先\(ctrl+Alt+t\)打开小框框 \(./\):相当于手机上的\(home\)键 \(ls\):当前文件夹的东东 \(mkdir\) ...
- LuaProfiler
Lua Profiler机制的源码解析 https://www.jianshu.com/p/f6606b27e9de