#!/usr/bin/env python # -*- coding:utf-8 _*- """ @author:壹拾壹 @Time: 2021/11/12 11:20 """ import time import hmac import hashlib import base64 import json import urllib.parse import urllib.request import os import random class DingDingWebHook(object): def __init__(self, secret=None, url=None): """ :param secret: 安全设置的加签秘钥 :param url: 机器人没有加签的WebHook_url """ if secret is not None: secret = secret else: secret = '' # 加签秘钥 if url is not None: url = url else: url = "" # 无加密的url timestamp = 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)) # 最终签名 self.webhook_url = url + '×tamp={}&sign={}'.format(timestamp, sign) # 最终url,url+时间戳+签名 def send_meassage(self, data): """ 发送消息至机器人对应的群 :param data: 发送的内容 :return: """ header = { "Content-Type": "application/json", "Charset": "UTF-8" } send_data = json.dumps(data) # 将字典类型数据转化为json格式 send_data = send_data.encode("utf-8") # 编码为UTF-8格式 request = urllib.request.Request(url=self.webhook_url, data=send_data, headers=header) # 发送请求 opener = urllib.request.urlopen(request) # 将请求发回的数据构建成为文件格式 print(opener.read()) # 打印返回的结果 if __name__ == '__main__': my_secret = '' my_url = '' my_data = { "msgtype": "markdown", "markdown": {"title": "测试markdown样式", "text": "各位亲爱的兄弟姐妹们,现在是9:15分,早上记得打卡哦!"}, "at": { "atMobiles": [], "isAtAll": True} # 是否@所有人 } dingding = DingDingWebHook(secret=my_secret, url=my_url) dingding.send_meassage(my_data)
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)