釘釘機器人:python發送消息-加簽模式

看了一下釘釘開發文檔,總體上比較簡單,但是也碰到一個坑。但還是實現了。

1、代碼

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

URL ="https://oapi.dingtalk.com/robot/send?access_token=fe2f8af7f5c534ac74065d8ac2676cf22b5fa4a181b8e9dbb99d78*****"

 # 釘釘機器人文檔說明
 # https://ding-doc.dingtalk.com/doc#/serverapi2/qf2nxq

def get_timestamp_sign():
    timestamp = str(round(time.time() * 1000))
    secret = "SEC6886eee211cce899b269749c312bd38a220ef24b6f82b855c9040a13e6****" # SEC開頭的
    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))
    print("timestamp: ",timestamp)
    print("sign:",sign)
    return (timestamp, sign)


def get_signed_url():
    timestamp, sign = get_timestamp_sign()
    webhook = URL + "&timestamp="+timestamp+"&sign="+sign
    return webhook

def get_webhook(mode):

    if mode == 0: # only 敏感字
       webhook = URL
    elif mode == 1 or  mode ==2 : # 敏感字和加簽 或 # 敏感字+加簽+ip
        # 加簽: https://oapi.dingtalk.com/robot/send?access_token=XXXXXX&timestamp=XXX&sign=XXX
        webhook = get_signed_url()
    else:
        webhook = ""
        print("error! mode:   ",mode,"  webhook :  ",webhook)
    return webhook

def get_message(content,is_send_all):
    # 和類型相對應,具體可以看文檔 :https://ding-doc.dingtalk.com/doc#/serverapi2/qf2nxq 
    # 可以設置某個人的手機號,指定對象發送
    message = {
        "msgtype": "text", # 有text, "markdown"、link、整體跳轉ActionCard 、獨立跳轉ActionCard、FeedCard類型等
        "text": { 
            "content": content # 消息內容
        },
        "at": {
            "atMobiles": [
                 "1862*8*****6", 
             ], 
            "isAtAll": is_send_all # 是否是發送羣中全體成員
        }
    }
    print(message)
    return message

def send_ding_message(content,is_send_all):
    # 請求的URL,WebHook地址
    webhook = get_webhook(1) # 主要模式有 0 : 敏感字 1:# 敏感字 +加簽 3:敏感字+加簽+IP
    print("webhook: ",webhook)
    # 構建請求頭部
    header = {
        "Content-Type": "application/json",
        "Charset": "UTF-8"
    }
    # 構建請求數據
    message = get_message(content,is_send_all)
    # 對請求的數據進行json封裝
    message_json = json.dumps(message)
    # 發送請求
    info = requests.post(url=webhook, data=message_json, headers=header)
    # 打印返回的結果
    print(info.text)

if __name__ == "__main__":
    content     = "test,機器人測試,hello!" 
    is_send_all = False
    send_ding_message(content,is_send_all)

2、幾個坑

(1) secret
在這裏插入圖片描述強烈建議釘釘開發文檔中,在“重置”邊上,加一個複製的功能。如果不加,也在旁邊寫一個請複製。

我的一個問題把secret是弄成了“SEC6886eee211cce899b2697”。其實,後面還有一大段呢。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章