使用Python 可以向飞书发送消息,可以将任务插在程序之中,可以进行报警、异常提醒等动作
一、引用的程序包
[Python] 纯文本查看 复制代码 import json
import requests
import logging
import hashlib
import base64
import hmac
import time
二、编写函数
[Python] 纯文本查看 复制代码 def gen_sign(timestamp, secret):
# 拼接timestamp和secret
string_to_sign = f'{timestamp}\n{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 sign
[Python] 纯文本查看 复制代码 def send_fei_msg(webhook, msg, sign, timestamp, title):
"""发送text类型飞书消息通知"""
# 构造钉钉消息头,必须制定utf-8编码
headers = {"Content-Type": "application/json;charset=utf-8"}
# 构造钉钉消息体,拷贝text消息格式
msg_body = {
"timestamp": timestamp,
"sign": sign,
"msg_type": "post",
"content": {
"post": {
"zh_cn": {
"title": title,
"content": [
[{
"tag": "text",
"text": msg
}
]
]
}
}
}
}
# 向hook地址发送post请求
try:
res = requests.post(webhook, data=json.dumps(msg_body), headers=headers)
res = res.json()
except Exception as e:
logging.error("请求异常: %s" % e)
res = None
return res
三、具体使用方法
[Python] 纯文本查看 复制代码 if __name__ == '__main__':
ticks = time.time()
timestamp = int(ticks)
access_token = "群机器人的token"
webhook = f"https://open.feishu.cn/open-apis/bot/v2/hook/{access_token}"
msg = "我是机器人"
title = "项目名称"
secret = '校验码'
sign = gen_sign(timestamp, secret)
s = send_fei_msg(webhook, msg, sign, timestamp, title) |