本文主要是介绍Python脚本实现向飞书发送卡片消息,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
目录
- 1 先创建一个卡片消息
- 2 Python脚本
- 2.1 告警测试
- 2.2 告警恢复
- 总结
1 先创建一个卡片消息
飞书卡片搭建工具
根据自己的需要创建一个消息卡片:
可以在 卡片源代码 中看到这个卡片的代码信息
2 Python脚本
2.1 告警测试
test.py 文件
"""
飞书群机器人发送通知
"""
import time
import urllib3
import datetime
import json
import logging
import requests
from flask import Flask,jsonify,request# 获取当前时间
# current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')# 配置日志记录器
logging.basicConfig(level=logging.INFO)
Logger = logging.getLogger(__name__)urllib3.disable_warnings()
webhook_url="https://open.feishu.cn/open-apis/bot/v2/hook/xxxxx"class FlybookRobotAlert():def __init__(self):self.webhook = webhook_urlself.headers = {"Content-Type": "application/json; charset=UTF-8"}def post_to_robot(self, post_data):'''给飞书机器人发送请求:param data::return:'''try:resp = requests.request(method="POST", url=self.webhook, data=post_data, headers=self.headers).json()if resp.get("StatusCode") == 0 and resp.get("msg") == "success":Logger.info(f"飞书通知发送成功,msg={resp}")else:Logger.warning(f"飞书通知发送失败,{resp}")except Exception as e:Logger.warning("飞书通知发送异常")Logger.warning(e)passdef send_message(self, msg, color):# 飞书通知标题robot_headers = "LibreNMS告警"# msg:告警信息# color:来定义卡片的颜色execute_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")# 定义卡片card = json.dumps({"config": {"wide_screen_mode": True},"i18n_elements": {"zh_cn": [{"tag": "hr"},{"tag": "column_set","flex_mode": "none","horizontal_spacing": "default","background_style": "default","columns": [{"tag": "column","elements": [{"tag": "div","text": {"tag": "plain_text","content": msg,"text_size": "normal","text_align": "left","text_color": "default"}}],"width": "weighted","weight": 1}]}]},"i18n_header": {"zh_cn": {"title": {"tag": "plain_text","content": robot_headers},"subtitle": {"tag": "plain_text","content": "时间:%s"%execute_time},"template": color}}})msg_body = json.dumps({"msg_type": "interactive", "card": card})self.post_to_robot(msg_body)# {'StatusCode': 0, 'StatusMessage': 'success', 'code': 0, 'data': {}, 'msg': 'success'}returndef main():msg="失败!!!"color = "red"if "恢复" in msg:color="green"web = FlybookRobotAlert()web.send_message(msg,color)# 程序入口
if __name__ == "__main__":main()
运行:
# 在执行第一次的时候可能会报错没有模块,根据提示安装即可
# 安装命令: pip install 模块名
python3 test.py
INFO:__main__:飞书通知发送成功,msg={'StatusCode': 0, 'StatusMessage': 'success', 'code': 0, 'data': {}, 'msg': 'success'}
2.2 告警恢复
test.py 文件
"""
飞书群机器人发送通知
"""
import time
import urllib3
import datetime
import json
import logging
import requests
from flask import Flask,jsonify,request# 获取当前时间
# current_time = datetime.now().strftime('%Y-%m-%d %H:%M:%S')# 配置日志记录器
logging.basicConfig(level=logging.INFO)
Logger = logging.getLogger(__name__)urllib3.disable_warnings()
webhook_url="https://open.feishu.cn/open-apis/bot/v2/hook/xxxxx"class FlybookRobotAlert():def __init__(self):self.webhook = webhook_urlself.headers = {"Content-Type": "application/json; charset=UTF-8"}def post_to_robot(self, post_data):'''给飞书机器人发送请求:param data::return:'''try:resp = requests.request(method="POST", url=self.webhook, data=post_data, headers=self.headers).json()if resp.get("StatusCode") == 0 and resp.get("msg") == "success":Logger.info(f"飞书通知发送成功,msg={resp}")else:Logger.warning(f"飞书通知发送失败,{resp}")except Exception as e:Logger.warning("飞书通知发送异常")Logger.warning(e)passdef send_message(self, msg, color):# 飞书通知标题robot_headers = "LibreNMS告警"# msg:告警信息# color:来定义卡片的颜色execute_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")card = json.dumps({"config": {"wide_screen_mode": True},"i18n_elements": {"zh_cn": [{"tag": "hr"},{"tag": "column_set","flex_mode": "none","horizontal_spacing": "default","background_style": "default","columns": [{"tag": "column","elements": [{"tag": "div","text": {"tag": "plain_text","content": msg,"text_size": "normal","text_align": "left","text_color": "default"}}],"width": "weighted","weight": 1}]}]},"i18n_header": {"zh_cn": {"title": {"tag": "plain_text","content": robot_headers},"subtitle": {"tag": "plain_text","content": "时间:%s"%execute_time},"template": color}}})msg_body = json.dumps({"msg_type": "interactive", "card": card})self.post_to_robot(msg_body)# {'StatusCode': 0, 'StatusMessage': 'success', 'code': 0, 'data': {}, 'msg': 'success'}returndef main():msg="失败!!! 恢复了 !!"color = "red"if "恢复" in msg:color="green"web = FlybookRobotAlert()web.send_message(msg,color)# 程序入口
if __name__ == "__main__":main()
运行后的:
# 在执行第一次的时候可能会报错没有模块,根据提示安装即可
# 安装命令: pip install 模块名
python3 test.py
INFO:__main__:飞书通知发送成功,msg={'StatusCode': 0, 'StatusMessage': 'success', 'code': 0, 'data': {}, 'msg': 'success'}
总结
使用python脚本发送卡片信息主要有两步:
- 在飞书上创建一个机器人,获取webhook
- 创建一个消息卡片,可以查到该卡片的代码
- 写python脚本
- 在执行python脚本时注意,最好可以在虚拟环境中执行
- 第一次执行上述脚本时会报错:部分模块没有安装,根据提示安装完成即可
- 安装模块命令: pip install XXXX
可以改进:现在支持通过卡片id来调用模板,不需要在代码中定义,还需要再研究,有想法的欢迎一起讨论。
这篇关于Python脚本实现向飞书发送卡片消息的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!