可用于发送钉钉消息

import time
import hmac
import hashlib
import base64
import urllib.parse
import requests
import json

class DingDing:
    def __init__(self, webhook: str, secret: str):
        self.webhook = webhook
        self.secret = secret.encode('utf-8')

    def _generate_sign(self) -> str:
        timestamp = str(round(time.time() * 1000))
        string_to_sign = f"{timestamp}\n{self.secret.decode()}"
        string_to_sign_enc = string_to_sign.encode('utf-8')
        hmac_code = hmac.new(self.secret, string_to_sign_enc, digestmod=hashlib.sha256).digest()
        sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))
        return timestamp, sign

    def send_message(self, content: str, is_at_all: bool = True) -> None:
        timestamp, sign = self._generate_sign()
        full_webhook = f"{self.webhook}&timestamp={timestamp}&sign={sign}"
        
        headers = {'Content-Type': 'application/json'}
        data = {
            "msgtype": "text",
            "text": {"content": content},
            "isAtAll": is_at_all
        }

        response = requests.post(full_webhook, data=json.dumps(data), headers=headers)
        print(response.text)

# 使用示例
if __name__ == "__main__":
    webhook = 'https://oapi.dingtalk.com/robot/send?access_token=your_access_token'  # 替换为你的钉钉webhook
    secret = 'your_secret'  # 替换为你的钉钉秘钥
    dingding_bot = DingDing(webhook, secret)
    
    # 发送消息
    dingding_bot.send_message("test message")

标签: python, 钉钉机器人

添加新评论