python调用飞书机器人发送文件

当前飞书webhook机器人还不支持发送文件类型的群消息,可以申请创建一个机器人应用来实现群发送文件消息。

创建机器人后,需要开通一系列权限,然后发布。由管理员审核通过后,才可使用。

包括如下的权限,可以获取群的chat_id。

开通权限发布应用后,可以取到两个重要的参数:

app_id

app_secret

使用两个参数可以生成密钥tenant_access_token,

headers = {'Authorization': f'Bearer {get_token()}', ## 获取tenant_access_token, 需要替换为实际的token

python 复制代码
def get_token():
    # 获取tenant_access_token,供上传图片接口使用
    url = "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal"
    headers = {
        "Content-Type": "application/json; charset=utf-8",
    }
    payload_data = {
        "app_id": "cli_xxx",
        "app_secret": "xxx",
    }
    response = requests.post(url=url, data=json.dumps(payload_data), headers=headers).json()
    print(response)
    token = response['tenant_access_token']
    return token```

上传文件

python 复制代码
def upload_file(file_path):
    try:
        file_name = file_path.split(',')[0]
        url = "https://open.feishu.cn/open-apis/im/v1/files"
        form = {'file_type': 'stream',
                'file_name': file_name,
                'file': (file_name, open(file_path, 'rb'),
                         'text/plain')}  # 需要替换具体的path  具体的格式参考  https://www.w3school.com.cn/media/media_mimeref.asp
        multi_form = MultipartEncoder(form)
        headers = {'Authorization': f'Bearer {get_token()}',  ## 获取tenant_access_token, 需要替换为实际的token
                   }
        headers['Content-Type'] = multi_form.content_type
        r = requests.request("POST", url, headers=headers, data=multi_form)
        print(r.json())
        # print(response.headers['X-Tt-Logid'])  # for debug or oncall
        # print(response.content)  # Print Response
        if r.json().get("code") == 0 and r.json().get("msg") == "success":
            logger.info(f"上传文件到飞书成功,msg={r.json()},{file_path=}")
            media_id = r.json().get('data').get('file_key')
            return media_id
        else:
            logger.warning(f"上传文件到飞书异常,{r.json()=},{file_path=}")

        # Press the green button in the gutter to run the script.

    except Exception as e:
        # logger.warning("上传文件到企业微信失败")
        print("上传文件到飞书失败")
        print(e)
        # logger.warning(e)
        pass

发送文件到群

python 复制代码
def send_file(file_path=None, media_id=""):
    """机器人应用上传文件"""
    if not media_id:
        media_id = upload_file(file_path=file_path)
        time.sleep(1)
    url = 'https://open.feishu.cn/open-apis/im/v1/messages?receive_id_type=chat_id'
    msgContent = {
        "file_key": media_id
    }
    form = {
        "content": json.dumps(msgContent),
        "msg_type": "file",
        "receive_id": "oc_xxx"
    }
    headers = {
        'Authorization': 'Bearer ' + get_token()
    }
    response = requests.post(url=url, data=json.dumps(form), headers=headers)
    print(response.json())

获取群的chat_id

python 复制代码
def get_qun_list():
    url = 'https://open.feishu.cn/open-apis/im/v1/chats'
    headers = {
        'Authorization': 'Bearer ' + get_token()
    }
    response = requests.get(url=url, headers=headers)
    print(response.json())
    return response.json()['data']['items']


def get_ _by_name(qun_name):
    items = get_qun_list()
    for i in items:
        if i.get('name') == str(qun_name):
            print(i.get('chat_id'))
            return i.get('chat_id')

发送成功

相关推荐
AI视觉网奇1 小时前
麒麟系统播放图片 速度比较
开发语言·python·pygame
言之。1 小时前
Django REST框架核心:GenericAPIView详解
数据库·python·django
这里有鱼汤1 小时前
别傻了,这些量化策略AI 10 秒就能帮你写好
后端·python
胡耀超1 小时前
机器学习数学基础与商业实践指南:从统计显著性到预测能力的认知升级
人工智能·python·机器学习·数据挖掘·数据分析·数据科学·统计学
杨荧2 小时前
基于Python的反诈知识科普平台 Python+Django+Vue.js
大数据·前端·vue.js·python·数据分析
大模型真好玩2 小时前
深入浅出LangChain AI Agent智能体开发教程(九)—LangChain从0到1搭建知识库
人工智能·python·mcp
MZ_ZXD0017 小时前
springboot汽车租赁服务管理系统-计算机毕业设计源码58196
java·c++·spring boot·python·django·flask·php
A 计算机毕业设计-小途8 小时前
大四零基础用Vue+ElementUI一周做完化妆品推荐系统?
java·大数据·hadoop·python·spark·毕业设计·毕设
念念010711 小时前
数学建模竞赛中评价类相关模型
python·数学建模·因子分析·topsis
云天徽上12 小时前
【数据可视化-94】2025 亚洲杯总决赛数据可视化分析:澳大利亚队 vs 中国队
python·信息可视化·数据挖掘·数据分析·数据可视化·pyecharts