飞书长连接_事件订阅(接收消息,审批任务状态变更)

python 复制代码
import lark_oapi as lark
from lark_oapi.ws import Client
import json
import requests
import time

# 你的凭证
APP_ID = "XXX"
APP_SECRET = "XXX"

# 缓存 tenant_access_token
tenant_access_token = None
token_expire_time = 0

# 获取 tenant_access_token
def get_tenant_access_token():
    global tenant_access_token, token_expire_time
    
    if tenant_access_token and time.time() < token_expire_time:
        return tenant_access_token
    
    url = "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal"
    headers = {"Content-Type": "application/json"}
    data = {"app_id": APP_ID, "app_secret": APP_SECRET}
    
    try:
        response = requests.post(url, headers=headers, json=data)
        result = response.json()
        
        if result.get("code") == 0:
            tenant_access_token = result.get("tenant_access_token")
            token_expire_time = time.time() + result.get("expire", 7200) - 100
            return tenant_access_token
        else:
            print(f"获取token失败: {result}")
            return None
    except Exception as e:
        print(f"获取token异常: {e}")
        return None

# 处理普通消息
def on_recv_msg(event):
    print("=" * 50)
    print("【收到飞书消息】")
    
    event_data = event.event
    sender = event_data.sender
    message = event_data.message
    
    print("发送人 ID:", sender.sender_id.open_id)
    print("消息 ID:", message.message_id)
    
    content = json.loads(message.content)
    print("消息内容:", content.get("text", ""))
    print("=" * 50)

# 获取审批实例详情
def get_approval_instance(instance_code):
    token = get_tenant_access_token()
    if not token:
        print("获取token失败,无法获取审批详情")
        return None
    
    url = f"https://open.feishu.cn/open-apis/approval/v4/instances/{instance_code}"
    headers = {"Authorization": f"Bearer {token}"}
    
    try:
        response = requests.get(url, headers=headers)
        result = response.json()
        
        if result.get("code") == 0:
            return result.get("data")
        else:
            print(f"获取审批详情失败: {result}")
            return None
    except Exception as e:
        print(f"获取审批详情异常: {e}")
        return None

# 解析表单内容
def parse_form_content(form_str):
    try:
        form_data = json.loads(form_str)
        print("\n【表单内容】")
        for field in form_data:
            field_name = field.get('name', '未知字段')
            field_value = field.get('value', '')
            field_type = field.get('type', '')
            
            # 处理特殊类型的字段值
            if isinstance(field_value, dict):
                field_value = json.dumps(field_value, ensure_ascii=False)
            elif isinstance(field_value, list):
                field_value = ', '.join(str(v) for v in field_value)
            
            print(f"  {field_name} ({field_type}): {field_value}")
    except json.JSONDecodeError as e:
        print(f"  表单解析失败: {e}")

# 处理审批状态变更
def on_approval_change(event):
    print("=" * 50)
    print("【收到审批任务事件】")
    
    event_dict = json.loads(lark.JSON.marshal(event))
    event_info = event_dict.get('event', {})
    
    print("审批定义Code:", event_info.get('approval_code', 'N/A'))
    print("审批实例Code:", event_info.get('instance_code', 'N/A'))
    print("审批状态:", event_info.get('status', 'N/A'))
    print("用户ID:", event_info.get('user_id', 'N/A'))
    
    instance_code = event_info.get('instance_code')
    if instance_code:
        print("\n【正在获取审批表单详情...】")
        instance_data = get_approval_instance(instance_code)
        if instance_data:
            print("审批名称:", instance_data.get('approval_name', 'N/A'))
            print("审批单号:", instance_data.get('serial_number', 'N/A'))
            print("创建时间:", instance_data.get('start_time', 'N/A'))
            print("结束时间:", instance_data.get('end_time', 'N/A'))
            print("发起部门:", instance_data.get('department_id', 'N/A'))
            
            # 解析表单内容
            form_str = instance_data.get('form', '')
            if form_str:
                parse_form_content(form_str)
            else:
                print("\n【表单内容】")
                print("  未获取到表单数据")
    
    print("=" * 50)

# 初始化事件处理器
handler = (
    lark.EventDispatcherHandler.builder("", "")
    .register_p2_im_message_receive_v1(on_recv_msg)
    .register_p1_customized_event("approval_task", on_approval_change)
    .build()
)

# 建立长连接
client = Client(APP_ID, APP_SECRET, event_handler=handler)
print("正在连接飞书...")
client.start()
相关推荐
许彰午1 天前
95_Python内存管理与垃圾回收
开发语言·python
多加点辣也没关系1 天前
JavaScript|第13章:原始类型的方法
开发语言·javascript·ecmascript
এ慕ོ冬℘゜1 天前
深入理解 JavaScript 事件体系:Window、鼠标与键盘事件详解
开发语言·javascript·okhttp
骄阳如火1 天前
Python 性能深度剖析:从“被诟病的慢”到“Rust 重塑”的拐点
python
满怀冰雪1 天前
03-第一个 Paddle 程序:Tensor 创建、计算与设备管理
人工智能·python·paddle
CClaris1 天前
大模型量化从0到1(九):用 llama.cpp 把模型转成 GGUF 并跑本地推理
人工智能·pytorch·python·深度学习·llama
学编程的小虎1 天前
SenseVoice微调
人工智能·python·自然语言处理
诸葛说抛光1 天前
国内大型汽车改装展览会定展 佛山改装 佛山汽车赛事
python·汽车
chouchuang1 天前
day-030-综合练习-笔记管理器
开发语言·笔记·python
乖巧的妹子1 天前
Python基础核心知识点详解:内置函数、运算符、字符串方法、数据结构与类型转换
python