PyBot/SendCore/FeishuSendBot.py

79 lines
2.4 KiB
Python
Raw Normal View History

2024-12-06 16:32:34 +08:00
# -*- coding: utf-8 -*-
2024-12-03 00:03:14 +08:00
import requests
import json
import hashlib
import base64
import hmac
import time
import yaml
def gen_sign():
with open('./config.yaml', 'r', encoding="utf-8") as file:
2024-12-03 00:03:14 +08:00
config = yaml.safe_load(file)
2024-12-12 13:49:32 +08:00
secret = f"{config['fs_secret']}"
2024-12-03 00:03:14 +08:00
# print(secret)
2024-12-12 13:49:32 +08:00
webhook_url = f"https://open.feishu.cn/open-apis/bot/v2/hook/{config['fs_key']}"
2024-12-03 00:03:14 +08:00
# print(webhook_url)
timestamp = int(time.time())
#拼接timestamp和secret
string_to_sign = '{}\n{}'.format(timestamp, secret)
hmac_code = hmac.new(string_to_sign.encode("utf-8"), digestmod=hashlib.sha256).digest()
# 对结果进行base64处理
sign = base64.b64encode(hmac_code).decode('utf-8')
return webhook_url, timestamp, sign
webhook_url, timestamp, sign = gen_sign()
# 主函数
2024-12-05 12:20:37 +08:00
def SendToFeishu(body, header, webhook_url, timestamp, sign):
2024-12-03 17:33:37 +08:00
msg = {
"timestamp": f"{timestamp}",
"sign": f"{sign}",
"msg_type": "interactive",
"card": {
"elements":
[{
"tag": "markdown",
2024-12-12 13:49:32 +08:00
"content": f"{body}"
2024-12-03 17:33:37 +08:00
}],
"header": {
"title": {
"content": f"{header}",
"tag": "plain_text"
}
}
}
}
2024-12-03 00:03:14 +08:00
# WebHook请求头
headers = {
"Content-Type": "application/json",
}
msg_encode=json.dumps(msg,ensure_ascii=True).encode("utf-8")
response=requests.post(url=webhook_url,data=msg_encode,headers=headers)
try:
# 解析 JSON 字符串
response_data = json.loads(response.content)
# 检查 msg 字段
if response_data.get('msg') == 'success':
2024-12-08 00:18:31 +08:00
return f"飞书发送 {header} 成功"
2024-12-03 00:03:14 +08:00
elif response_data.get('msg') == 'sign match fail or timestamp is not within one hour from current time':
2024-12-08 00:18:31 +08:00
return f"{header} 发送失败: 签名验证错误,请检查签名密钥是否正确!"
2024-12-03 00:03:14 +08:00
else:
2024-12-08 00:18:31 +08:00
return f"{header} 发送失败: 其他错误,请检查请求参数是否正确!\n原因:{response_data.get('msg')}"
2024-12-03 00:03:14 +08:00
except json.JSONDecodeError as e:
2024-12-08 00:18:31 +08:00
return f"{header} JSON解析错误: {e}"
2024-12-03 00:03:14 +08:00
# print(sign)
# print(response.content)
2024-12-12 13:49:32 +08:00
msg = "测试消息"
2024-12-03 17:33:37 +08:00
2024-12-03 00:03:14 +08:00
if __name__ == '__main__':
2024-12-12 13:49:32 +08:00
result = SendToFeishu(msg, "测试消息")
print(result)