其他分享
首页 > 其他分享> > 发送钉钉消息

发送钉钉消息

作者:互联网


#钉钉:
#钉钉智能群助手,机器人管理 添加机器人-自定义机器人-添加-安全设置-加签(生成秘钥)
#自定义关键词-生成一个接口-复制一下
#群提供接口-调用接口-发消息-返回-查看文档-服务端API-消息通知-普通消息(发送给某个人的)
#群机器人-自定义机器人介入-

# 安全设置-关键字类型
加签-字符串
# 接口发送
# posm调用看下是否通
#
# https://oapi.dingtalk.com/robot/send?access_token=78d41c3d83bb06a4ff3cb25b0bdf1fe67e8dc7f04d2a5c1a058406e3109249fd
# #token是群信息,换个群就换后边
# https://developers.dingtalk.com/document/robots/custom-robot-access


#发送消息
# {
# "at": {
# "atMobiles": [
# "18513112593",
# "15503122090"
# ],
#
# "isAtAll": true #@所有
# },
# "text": {
# "content": "我是机器人,thz"
# },
# "msgtype": "text"
# }

#群发送消息
import requests
url = "https://oapi.dingtalk.com/robot/send"

token = {"access_token":"78d41c3d83bb06a4ff3cb25b0bdf1fe67e8dc7f04d2a5c1a058406e3109249fd"} #定义成字典去改他

data = {
"at": {
"atMobiles":[
"18513112593",
"15503122090"
],

"isAtAll": True
},
"text": {
"content":"我是王帅,thz,这是写代码发送的"
},
"msgtype":"text"
}


r = requests.post(url,params=token,json=data) #请求参数穿到URL里面用 params,json类型接口

print(r.json())


#加签类型的
import time
import hmac
import hashlib
import base64
import urllib.parse
timestamp = str(round(time.time() * 1000)) #时间戳
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))#签名

token = {"access_token":"78d41c3d83bb06a4ff3cb25b0bdf1fe67e8dc7f04d2a5c1a058406e3109249fd","timestamp":timestamp,"sign":sign}


#封装 只需要改下新的:token secret
import requests
import time
import hmac
import hashlib
import base64
import urllib.parse

from loguru import logger #打印日志

def get_dding_sign(secret):#不同的机器人要变把这个secret传进来
timestamp = str(round(time.time() * 1000)) #
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))
return timestamp, sign

def send_dd_msg(msg, token="78d41c3d83bb06a4ff3cb25b0bdf1fe67e8dc7f04d2a5c1a058406e3109249fd",secret="SEC69aaceefa47d21845255b7daed7cbd1a4d2a9930981c21d0ee11ae41a6ca06be", at=None, at_all=False):
url = "https://oapi.dingtalk.com/robot/send"
timestamp, sign = get_dding_sign(secret)
url_params = {"access_token": token, "timestamp": timestamp, "sign": sign}
data = {
"at": {
"atMobiles": at,

"isAtAll": at_all
},
"text": {
"content": msg
},
"msgtype": "text"
}
r = requests.post(url, params=url_params, json=data)
ret = r.json()
if ret.get("errcode") != 0:
logger.warning("钉钉消息发送失败!返回报文是:{}",ret)
return False
logger.info("钉钉消息发送成功")
return True

if __name__ == '__main__':
send_dd_msg("外面风好大,不要外出",at=["18513112593","15503122090"])

标签:enc,string,timestamp,token,sign,发送,secret,消息
来源: https://www.cnblogs.com/wang0211/p/15543104.html