钉钉飞书群消息推送

2021-04-08  本文已影响0人  柒公子c
# -*- coding: utf-8 -*-
# @Author  : zuoleilei
# @Site    : 
# @File    : 钉钉群消息推送.py

"""
1、设置钉钉群消息助手
2、钉钉群消息提醒Webhook :https://oapi.dingtalk.com/robot/send?access_token=
3、钉钉接口文档:https://developers.dingtalk.com/document/app/document-upgrade-notice

第一种方式:自定义关键词,发送:最多可以设置10个关键词,消息中至少包含其中1个关键词才可以发送成功
第二种方式:加签、发送:
    (1)把timestamp+"\n"+密钥当做签名字符串,使用HmacSHA256算法计算签名,然后进行Base64 encode,最后再把签名参数再进行urlEncode,得到最终的签名(需要使用UTF-8字符集)。
第三种方式:IP段发送
"""

import urllib, time, hashlib, base64, hmac, requests
from urllib.parse import quote, unquote


def createDingSign():
    secret = 'xxxx'
    timestamp = int(time.time() * 1000)  # 获取当前时间戳,并由秒转换为毫秒
    signBefore = ('%s\n%s' % (timestamp, secret)).encode('utf-8')  # 将时间戳+'\n'+加密的字符串
    hsha256 = hmac.new(secret.encode('utf-8'), signBefore, hashlib.sha256)
    signSha256 = hsha256.digest()  #
    base = base64.b64encode(signSha256)  # 进行base64加密,使用decode去掉不必要的
    sign = quote(base)
    return {"timestamp": timestamp, "sign": sign}


def sendMessageDing(msg='大家好,我是钉钉群助手机器人'):
    url = 'https://oapi.dingtalk.com/robot/send?access_token=xxxxx'
    json = {
        "msgtype": "text",
        "text": {
            "content": msg,
        },
        "at": {
            "atMobiles": [
                ""
            ],
            "isAtAll": False
        }
    }
    sign = createDingSign()
    r = requests.post(url=url, params=sign, json=json)
    print(r.json())


if __name__ == "__main__":
    createDingSign()


# -*- coding: utf-8 -*-
# @Site    : 
# @File    : 飞书群消息推送.py


"""
1、设置飞书群消息助手
2、飞书群消息提醒Webhook:
https://open.feishu.cn/open-apis/bot/v2/hook/
3、安全设置:
    (1)、关键字
    (2)、加签:
     签名的算法:把 timestamp + "\n" + 密钥 当做签名字符串,使用 HmacSHA256 算法计算签名,再进行 Base64 编码。
    (3)、IP白名单
"""
import time, hmac, base64, requests, hashlib
from hashlib import sha256


def createFeiSign():
    secret = 'xxx'
    timestamp = int(time.time())  # 获取当前时间戳,单位秒
    secretBefore = ('%s\n%s' % (timestamp, secret)).encode('utf-8')  # 将值转换为byte类型
    msg = ""
    msgEncode = msg.encode('utf-8')
    hsha256 = hmac.new(secretBefore, msgEncode, digestmod=hashlib.sha256).digest()  # 用hashlib.sha256进行计算,得出HmacSHA256
    sign = base64.b64encode(hsha256).decode()  # 先Base64,再decode去掉byte类型,得到sign值
    return {"timestamp": timestamp, "sign": sign}


def sendMessageFei(text='大家好,我是飞书群助手机器人'):
    url = 'https://open.feishu.cn/open-apis/bot/v2/hook/xx'
    json = {
        "timestamp": createFeiSign().get('timestamp'),
        "sign": createFeiSign().get('sign'),  # 获取函数的值,并get到具体值
        "msg_type": "text",
        "content": {
            "text": text  # 推送消息进行实时改动
        }
    }
    r = requests.post(url=url, json=json)
    print(r.json())


if __name__ == "__main__":
    sendMessageFei()

上一篇下一篇

猜你喜欢

热点阅读