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

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()
相关推荐
Είναι η κοπέλα9 小时前
llama.cpp 与 GGUF 格式:本地大模型的“裸引擎“
开发语言·人工智能·pytorch·python·conda
大草原的小灰灰9 小时前
Python面向对象编程
开发语言·python
知识分享小能手9 小时前
C学习教程,从入门到精通,C语言概述 —— 知识点详解(1)
c语言·开发语言·学习
华研前沿标杆游学9 小时前
企业参访入口 | 走进华为坂田基地,深圳华为坂田基地考察游学参访
python
Chen_harmony10 小时前
一、C++入门基础
开发语言·c++
学逆向的10 小时前
远程线程注入
开发语言·jvm·网络安全·win32
朝朝辞暮i10 小时前
VLA 系统学习第 12 课:为什么机器人不能只看一帧?——时间序列、Observation History 与 Action Chunk
人工智能·python·深度学习·神经网络·vla
朝朝辞暮i10 小时前
VLA 系统学习第 8 课:Optimizer 到底在干什么?——从 Learning Rate 到 SGD、Momentum 和 Adam
人工智能·python·深度学习·神经网络·vla
镜子AI10 小时前
教培机构多模态内容跨模态检索系统:基于CLIP的统一表征与图文混合召回算法
人工智能·python·算法·机器学习
落魄大学生之流水线上谋生计10 小时前
Selenium 入门到实战:用 Python 写出稳定的浏览器自动化
python·selenium·自动化