# -*- coding:UTF-8 -*-
# @Time  : 2020/12/2 14:58
# @File  : send_msg.py
# @email : litao@igengmei.com
# @author : litao
import time
import hmac
import hashlib
import urllib
import base64
import json
import requests


def send_msg_to_dingtalk(msg, mobiles=[],access_token="",secret=""):
    try:
        # secret = "SECba5212dadad3794b3da51c903c828f60ab8342897af2675f1f48fceb8858eb5c"
        timestamp = str(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))

        headers = {"Content-Type": "application/json"}
        data = {"msgtype": "text", "text": {"content": msg}}
        if mobiles:
            data = {"msgtype": "text", "text": {"content": msg}, "at": {"atMobiles": mobiles, "isAtAll": False}}
        json_data = json.dumps(data)
        # "https://oapi.dingtalk.com/robot/send?access_token=df546521ce46bfb35025ca266efc2d7e8d708d1c8ada9b15ae487786ad06ad12&sign={}&timestamp={}"
        url = "https://oapi.dingtalk.com/robot/send?access_token={}&sign={}&timestamp={}".format(access_token,
            sign, timestamp)
        response = requests.post(url=url, data=json_data, headers=headers)
        return str(response.status_code) + " " + str(response.content.decode("utf-8"))
    except Exception as e:
        print(e)
        return str(e)