#!/usr/bin/env python

# -*- coding: utf-8 -*-

import requests

import json

import sys

import os

import datetime

import base64

import hashlib

import hmac

from time import time



class FeiShuNotify:

   def __init__(self, subject, message, access_token=None):

       timestamp, sign = FeiShuNotify.encode(access_token)

       self.content = {'timestamp': timestamp, 'sign': sign}

       self.subject = subject

       self.message = message

       self.timestamp = timestamp

       self.sign = sign


   @staticmethod

   def encode(access_token):

       """

       飞书机器人webhook签名验证加密方法

       :return:

       """

       # timestamp = str(round(time() * 1000))

       timestamp = str(int(time()))

       # 拼接timestamp和secret

       string_to_sign = '{}\n{}'.format(timestamp, access_token)

       hmac_code = hmac.new(string_to_sign.encode("utf-8"), digestmod=hashlib.sha256).digest()

       # 对结果进行base64处理

       sign = base64.b64encode(hmac_code).decode('utf-8')

       return timestamp, sign


   def to_json(self):

       """

       飞书消息卡片返回格式

       :return:

       """

       return {

           "msg_type": "interactive",

           "card": {

               "config": {

                   "wide_screen_mode": True

               },

               "header": {

                   "title": {

                       "tag": "plain_text",

                       "content": self.subject

                   },

                   "template": "blue"

               },

               "elements": [

                   {

                       "tag": "markdown",

                       "content": self.message,

                   }

               ]

           },

           'timestamp': self.timestamp,

           'sign': self.sign

       }



def send_message(message, subject):

   """

   向飞书webhook url发送告警消息

   :param message:

   :param subject:

   :return:

   """

   payload_message = FeiShuNotify(subject, message, access_token="C8tW9fHPXct0S9TDOuNTLb").to_json()

   headers = {

       'Content-Type': 'application/json'

   }


   response = requests.request("POST",

                           "换成你的机器人地址",

                               headers=headers, data=json.dumps(payload_message))

   return response



if __name__ == '__main__':

   text = sys.argv[3]

   subject = sys.argv[2]

   send_message(text, subject)