【python_使用指定应用发送飞书卡片】

import requests
import json

# 飞书应用配置(替换成你自己的)
APP_ID = "XXX"
APP_SECRET = "XXX"

def get_tenant_token():
    """获取飞书凭证(内部调用)"""
    url = "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal"
    res = requests.post(url, json={"app_id": APP_ID, "app_secret": APP_SECRET}).json()
    print(res)
    if res.get("code") != 0:
        raise Exception(f"获取Token失败:{res}")
    return res["tenant_access_token"]

def send_feishu_card(receive_type="chat_id"):
    """
    发送飞书模板卡片消息(通用函数)
    :param receive_id: 接收者ID(群ID/用户ID)
    :param card_template_id: 卡片模板ID
    :param template_variable: 卡片变量 dict,如 {"name":"张三","time":"2025-01-01"}
    :param receive_type: ID类型,默认群聊 chat_id,个人用 open_id
    :return: message_id 消息ID
    """
    token = get_tenant_token()
    
    url = "https://open.feishu.cn/open-apis/im/v1/messages"
    params = {"receive_id_type": receive_type}
    
    headers = {
        "Authorization": f"Bearer {token}",
        "Content-Type": "application/json"
    }

    data={
    "receive_id": "XXX",
    "msg_type": "interactive",
    "content": json.dumps({
        "type": "template",
        "data": {
            "template_id": "XXX",
            "template_variable": {
                "creator_open_id": "XXX",
                "enterprise_name": "内蒙古",
                "customer_problem": "流程报错",
                "on_duty_staff_at_str": "<at id=XXX></at><at id=XXX></at>",
                "ai_feedback": "需要值班技术",
                "record_link": "https://ying-dao.feishu.cn/record/AfkzroiU7e0sYKcEHLXcmeudnwx"
            }
        }
    })
}

    res = requests.post(url, params=params, headers=headers, json=data).json()
    if res.get("code") != 0:
        raise Exception(f"发送失败:{res}")
    
    return res["data"]["message_id"]

if __name__ == "__main__":
    # 配置
    CHAT_ID = "XXX"                # 群聊ID / 个人ID
    CARD_TPL_ID = "XXX"            # 卡片模板ID

    # 发送卡片
    msg_id = send_feishu_card()
    print("发送成功,消息ID:", msg_id)
Logo

小龙虾开发者社区是 CSDN 旗下专注 OpenClaw 生态的官方阵地,聚焦技能开发、插件实践与部署教程,为开发者提供可直接落地的方案、工具与交流平台,助力高效构建与落地 AI 应用

更多推荐