飞书机器人告警实现

server/2025/1/12 3:29:41/

功能实现说明

1. 准备好config.json文件,用于存放配置文件信息

2. 准备好config.py用于读取配置文件信息

3. feishu.py用于实现获取临时token以及推送消息至指定机器人并推到指定飞书用户

config.json

{"auth":{"app_id": "cli_xxxxxc","app_secret": "xxxxxxx"},"user_ids":{"replace_your_feishu_user_name":"replace_your_feishu_user_name's_user_id"}
}

config.py

"""
This module provides a Config class for managing configuration settings for the Feishu API integration.It reads configuration data from a JSON file and provides methods to access various settings.
"""import jsonclass Config:"""A class to manage configuration settings for the Feishu API integration.This class reads configuration data from a JSON file and provides methodsto access app credentials and user IDs."""def __init__(self, config_file='config.json'):"""Initialize the Config instance.Args:config_file (str): Path to the configuration JSON file. Defaults to 'config.json'.Raises:FileNotFoundError: If the specified config file is not found.json.JSONDecodeError: If the config file is not valid JSON.KeyError: If expected keys are missing in the config file."""with open(config_file, 'r') as f:config = json.load(f)# Extract configuration valuesself.app_id = config['auth']['app_id']self.app_secret = config['auth']['app_secret']self.user_ids = config['user_ids']def get_app_id(self):"""Get the Feishu app ID.Returns:str: The app ID."""return self.app_iddef get_app_secret(self):"""Get the Feishu app secret.Returns:str: The app secret."""return self.app_secretdef get_user_id(self, name):"""Get a user ID by name.Args:name (str): The name of the user.Returns:str: The user ID if found, None otherwise."""return self.user_ids.get(name)if __name__=='__main__':# Example usage of the Config classconfig = Config()print(config.get_app_id())print(config.get_app_secret())print(config.get_user_id('test'))

feishu.py

飞书机器人消息推送功能实现

import urllib3
import json
import ssl
import warnings
from config import Config# Suppress only the single InsecureRequestWarning from urllib3 needed.
warnings.filterwarnings('ignore', category=urllib3.exceptions.InsecureRequestWarning)class Feishu:"""A class to interact with the Feishu API.This class provides methods to authenticate and communicate with the Feishu API,including obtaining a tenant access token for further API operations."""def __init__(self):"""Initialize the Feishu instance.Sets up the configuration, base URL, and creates a custom SSL contextto allow unverified HTTPS connections (for development purposes only)."""self.config = Config()self.base_url = "https://open.feishu.cn/open-apis"self.tenant_access_token = None# Create a custom SSL contextssl_context = ssl.create_default_context()ssl_context.check_hostname = Falsessl_context.verify_mode = ssl.CERT_NONE# Use the custom SSL context in PoolManagerself.http = urllib3.PoolManager(ssl_context=ssl_context)def get_tenant_access_token(self):"""Obtain a tenant access token from the Feishu API.This method sends a POST request to the Feishu API to get a tenant access token.It uses the app_id and app_secret from the config to authenticate the request.Returns:str: The tenant access token if successful, None otherwise.Raises:Exception: If an error occurs during the API request."""url = f"{self.base_url}/auth/v3/tenant_access_token/internal"headers = {"Content-Type": "application/json"}data = {"app_id": self.config.get_app_id(),"app_secret": self.config.get_app_secret()}try:response = self.http.request("POST", url, headers=headers, body=json.dumps(data))response_data = json.loads(response.data.decode('utf-8'))if response.status == 200:self.tenant_access_token = response_data.get("tenant_access_token")if self.tenant_access_token:return self.tenant_access_tokenelse:print("Error: tenant_access_token not found in the response")else:print(f"Error: HTTP {response.status}")print("Response data:", response_data)except Exception as e:print(f"An error occurred: {str(e)}")return Noneif __name__ == "__main__":feishu = Feishu()token = feishu.get_tenant_access_token()if token:print(f"Successfully obtained tenant access token: {token}")else:print("Failed to obtain tenant access token")


http://www.ppmy.cn/server/157656.html

相关文章

HTML实战课堂之简单的拜年程序

一、目录:  一、目录: 二、祝福 三:代码讲解 (1)详细解释: 1.HTML部分 2. CSS部分 三、运行效果(随机截图): 四、完整代码: 二、祝福…

基于 Boost.Asio 和 Boost.Beast 的异步 HTTP 服务器(学习记录)

已完成功能: 支持 GET 和 POST 请求的路由与回调处理。 解析URL请求。 单例模式 管理核心业务逻辑。 异步 I/O 技术和 定时器 控制超时。 通过回调函数注册机制,可以灵活地为不同的 URL 路由注册处理函数。 1. 项目背景 1.1 项目简介 本项目是一个基于…

2025年第三届“华数杯”国际赛A题解题思路与代码(Matlab版)

游泳竞技策略优化模型代码详解(MATLAB版) 第一题:速度优化模型 本部分使用MATLAB实现游泳运动员在不同距离比赛中的速度分配策略优化。 1. 模型概述 模型包含三个主要文件: speed_optimization.m: 核心优化类plot_speeds.m: …

apache age:22023,42883,等报错信息

apache age 各种类型不匹配 函数找不到 以下是对Apache AGE、PostgreSQL以及Cypher语法的详细介绍: 一、Apache AGE 定义:Apache AGE(A Graph Extension)是一个基于PostgreSQL的图数据库扩展插件。它结合了PostgreSQL的先进SQL查询功能和事务支持,以及图数据库的灵活性和…

551 灌溉

常规解法&#xff1a; #include<bits/stdc.h> using namespace std; int n,m,k,t; const int N105; bool a[N][N],b[N][N]; int cnt; //设置滚动数组来存贮当前和下一状态的条件 //处理传播扩散问题非常有效int main() {cin>>n>>m>>t;for(int i1;i&l…

SQL Server中可以通过扩展事件来自动抓取阻塞

在SQL Server中可以通过扩展事件来自动抓取阻塞&#xff0c;以下是详细流程&#xff1a; 开启阻塞跟踪配置&#xff1a; • 执行以下SQL语句来启用相关配置&#xff1a; EXEC sp_configureshow advanced options, 1; RECONFIGURE; EXEC sp_configure blocked process thresh…

升级 Spring Boot 3 全项目讲解 — 给项目增加聊天对话功能

学会这款 &#x1f525;全新设计的 Java 脚手架 &#xff0c;从此面试不再怕&#xff01; 1. Spring Boot 3 升级指南 在升级 Spring Boot 3 之前&#xff0c;确保你的项目已经迁移到 Java 17&#xff0c;因为 Spring Boot 3 不再支持 Java 8 和 Java 11。接下来&#xff0c;我…

WebSocket 实现指南

WebSocket 实现指南 目录 1. 依赖安装 1.1 安装必要的包 # 安装 gorilla/websocket go get github.com/gorilla/websocket# 安装 gin 框架 go get github.com/gin-gonic/gin1.2 更新 go.mod require (github.com/gin-gonic/gin v1.9.1github.com/gorilla/websocket v1.5.3…