api调用钉钉群机器人发信息

复制代码
class SecretRobot:
    def __init__(self, secret='', webhook=''):
        self.secret = secret
        self.webhook = webhook
        self.timestamp = str(round(time.time() * 1000))
        self.headers = {"Content-Type": "application/json"}
    
    def send(self, message):
        self.get_sign()
        webhook = self.webhook + '&timestamp=' + self.timestamp + '&sign=' + self.sign
        data = {
            "msgtype": "text",
            "text": {
                "content": message
            }
        }
        resp = requests.post(webhook, data=json.dumps(data), headers=self.headers)
        resp.close()
    
    def get_sign(self):
        secret_enc = self.secret.encode('utf-8')
        string_to_sign = '{}\n{}'.format(self.timestamp, self.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()
        self.sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))

def send_dingding_message(message, secret):
    webhook = 'https://oapi.dingtalk.com/robot/send?access_token=XXXXX' #替换为实际的
    
    # 创建 SecretRobot 对象
    robot = SecretRobot(secret=secret, webhook=webhook)
    
    # 发送消息
    robot.send(message) 详细解释每一步骤
  1. 创建SecretRobot类:

    • __init__方法初始化了SecretRobot对象的属性,包括机器人密钥(secret)、Webhook地址(webhook)、时间戳(timestamp)和请求头(headers)。
    • send方法用于发送消息。在发送消息之前,会调用get_sign方法获得签名,然后拼接好带有签名的Webhook地址,并构建消息内容。最后使用requests.post方法发送POST请求,将消息以JSON格式发送到钉钉机器人的Webhook地址。
    • get_sign方法用于生成签名。首先将机器人密钥(secret)进行UTF-8编码,然后将时间戳(timestamp)和密钥拼接,再对拼接后的字符串进行UTF-8编码。接下来使用hmac.new函数计算HMAC摘要,使用SHA256哈希算法和密钥(secret_enc)对拼接后的字符串(string_to_sign_enc)进行摘要计算。最后,对摘要结果进行Base64编码并进行URL转码,得到最终的签名值(sign)。
  2. send_dingding_message函数:

    • 此函数是一个简单的封装,用于向钉钉机器人发送消息。
    • 首先指定钉钉机器人的Webhook地址(webhook)。
    • 然后创建SecretRobot对象,并传入机器人密钥(secret)和Webhook地址(webhook)。
    • 最后调用robot.send方法发送消息。

请注意,代码中的示例Webhook地址是一个伪造的地址,请将webhook替换为你自己钉钉机器人的Webhook地址。

你可以通过以下步骤使用此代码:

  1. 将示例代码复制到你的Python环境中。
  2. 根据实际情况修改send_dingding_message函数中的webhook变量。
  3. 在需要发送钉钉消息的地方调用send_dingding_message函数,并传入消息内容和机器人密钥。

msg = '你要传的信息'

secret = 'XXXXXX' #替换为签

send_dingding_message(msg,secret)

打开钉钉群设置

添加自定义机器人

选择"加签"

获得Secret和Webhook

相关推荐
阿加犀智能1 小时前
重构开发范式?犀牛派 X1 的隐藏实力全解锁
机器人·ai芯片·qcs8550
机器人行业研究员2 小时前
从“看得见”到“摸得着”:六维力/力矩传感器如何成为机器人进化的关键门槛
机器人
jinglong.zha2 小时前
Otto Robot机器人从入门到精通实战教程(二)
人工智能·机器人·ai编程·tuya·tuyaai·otto·otto机器人
汽车仪器仪表相关领域2 小时前
ZRT-II 机器人减速器性能测试系统
功能测试·测试工具·安全·机器人·压力测试·可用性测试
汽车仪器仪表相关领域2 小时前
ZRT-III 机器人减速器出厂检测平台
人工智能·功能测试·安全·机器人·压力测试·可用性测试
苏州知芯传感2 小时前
柔性抓取的“慧眼”:MEMS 3D视觉如何让机器人精准识别无序堆叠的复杂钣金件?
算法·3d·机器人·mems
沫儿笙2 小时前
Kasawaki川崎焊接机器人弧焊气体节约设备
人工智能·机器人
成为你的宁宁2 小时前
【Jenkins添加钉钉通知】
jenkins·钉钉
派葛穆2 小时前
机器人-六轴机械臂的正运动学
人工智能·机器学习·机器人
Deepoch3 小时前
基于PPO强化学习的无人机自主路径规划技术实践
人工智能·机器人·无人机·具身模型·deepoc·deepoc具身智能开拓版