【保姆式】python调用api通过机器人发送文件到飞书指定群聊

当前飞书webhook机器人还不支持发送文件类型的群消息,它目前仅支持文本,富文本,卡片等文字类型的数据。

我们可以申请创建一个机器人应用来实现群发送文件消息。

创建飞书应用

创建飞书应用、配置权限、添加机器人

  1. 来到飞书开发者后台

创建企业自建应用

输入名称、描述

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

    在上述位置下添加下述权限并开通

  2. 创建机器人

    在上述位置添加好机器人

  3. 在你要发送的群里中添加刚刚创建的机器人(我这的机器人取名为"推送报表")

  4. 最后提交发布, 在凭证和基础信息这里获取

app id

app secret

调用API上传文件

流程顺序如下:通过app_id,app_secret获取token -> 上传文件(获取文件id)-> 获取群聊chat_id -> 通过文件id将文件上传到指定chat_id

  1. 获取token
python 复制代码
def get_token():
    """ 获取飞书 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
    }
    response = requests.post(url, headers=headers, json=data)
    if response.status_code == 200:
        return response.json()["tenant_access_token"]
    else:
        return ""
  1. 上传文件到飞书,并获取文件id
python 复制代码
def upload_file(file_name, file_path):
    """ 上传文件到飞书 """
    
    url = "https://open.feishu.cn/open-apis/im/v1/files"
    headers = {
        "Authorization": "Bearer "+get_token()
    }
    form = {
        "file_type": "stream",
        "file_name": file_name,
        "file": (file_name, open(file_path, "rb"), "text/plain")
    }
    multi_form = MultipartEncoder(form)
    headers["Content-Type"] = multi_form.content_type
    response = requests.post(url, headers=headers, data=multi_form)
    if response.status_code == 200 and response.json().get("code") == 0:
        # print(f"上传文件到飞书成功,msg={response.json()},{file_path=}")
        media_id = response.json().get("data", {}).get("file_key")
        return media_id
    else:
        return "" 
  1. 获取群chat_id
    有两种方式,通过api,或者直接通过平台粘贴对应群聊id,这里使用后者,因为是发送到固定群聊
    去到api调试页面,按照如下操作获取对应群聊chat_id
  2. 发送文件到群里
python 复制代码
def send_file(file_path, media_id=None):
    """机器人应用上传文件"""
    if not media_id:
        media_id = upload_file(file_name=file_path, 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": CHAT_ID
    }
    headers = {
        'Authorization': 'Bearer ' + get_token()
    }
    response = requests.post(url=url, data=json.dumps(form), headers=headers)
    print(response.json())

完成文件发送

相关推荐
数据智能老司机5 小时前
精通 Python 设计模式——分布式系统模式
python·设计模式·架构
数据智能老司机6 小时前
精通 Python 设计模式——并发与异步模式
python·设计模式·编程语言
数据智能老司机6 小时前
精通 Python 设计模式——测试模式
python·设计模式·架构
数据智能老司机6 小时前
精通 Python 设计模式——性能模式
python·设计模式·架构
c8i6 小时前
drf初步梳理
python·django
每日AI新事件6 小时前
python的异步函数
python
这里有鱼汤8 小时前
miniQMT下载历史行情数据太慢怎么办?一招提速10倍!
前端·python
databook17 小时前
Manim实现脉冲闪烁特效
后端·python·动效
程序设计实验室17 小时前
2025年了,在 Django 之外,Python Web 框架还能怎么选?
python
倔强青铜三19 小时前
苦练Python第46天:文件写入与上下文管理器
人工智能·python·面试