import base64
import hashlib
import hmac
import json
import time
import urllib

import requests


def send_msg_to_dingtalk(msg, mobiles=[]):
    try:
        secret = "SECffcdd05c1bb9ca2e6268b2593e4891872c5d0a8adf6751915bc77583076ed0b7"
        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)
        url = "https://oapi.dingtalk.com/robot/send?access_token=661cf4d772916d54597d5cd1636fbc6890ef220908dd1f81fe074f44896b6aa2&sign={}&timestamp={}".format(
            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)
