#!/usr/bin/python
# -*- coding: UTF-8 -*-

import requests
import json
import hashlib
import base64
import hmac
import time
import yaml

with open('./config/config.yaml', 'r', encoding="utf-8") as file:
    config = yaml.safe_load(file)
webhook_url = f"https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key={config['wx_key']}"
# print(webhook_url)
 
def SendToWX(body, header):
    url = webhook_url
    payload = {
        'msgtype': 'markdown',
        'markdown': {
            'content': f'''
# {header}
{body}
'''
        }
    }
    response = requests.post(url, json=payload)
    try:
        response_data = json.loads(response.content)
        if response_data.get('errmsg') == 'ok':
            return f"企业微信发送 {header} 成功"
        else:
            return f"{header} 发送失败: 其他错误，请检查请求参数是否正确！\n原因：{response_data.get('errmsg')}"
    except json.JSONDecodeError as e:
        return f"{header} JSON解析错误: {e}"
    # print(sign)
    # print(response.content)

msg = '''
#### 文章
测试消息
[测试链接](masonliu.com)
'''

if __name__ == '__main__':
    response = SendToWX(msg, "测试消息")
    print(response)
