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')

发送成功

相关推荐
多米Domi01117 分钟前
0x3f第33天复习 (16;45-18:00)
数据结构·python·算法·leetcode·链表
freepopo34 分钟前
天津商业空间设计:材质肌理里的温度与质感[特殊字符]
python·材质
森叶37 分钟前
Java 比 Python 高性能的原因:重点在高并发方面
java·开发语言·python
小二·1 小时前
Python Web 开发进阶实战:混沌工程初探 —— 主动注入故障,构建高韧性系统
开发语言·前端·python
Lkygo1 小时前
LlamaIndex使用指南
linux·开发语言·python·llama
小二·1 小时前
Python Web 开发进阶实战:低代码平台集成 —— 可视化表单构建器 + 工作流引擎实战
前端·python·低代码
Wise玩转AI1 小时前
团队管理:AI编码工具盛行下,如何防范设计能力退化与知识浅薄化?
python·ai编程·ai智能体·开发范式
Deepoch2 小时前
Deepoc具身模型开发板:重新定义机器人智能化的技术底座
人工智能·机器人·具身模型·deepoc
赵谨言2 小时前
Python串口的三相交流电机控制系统研究
大数据·开发语言·经验分享·python
鹿角片ljp3 小时前
Engram 论文精读:用条件记忆模块重塑稀疏大模型
python·自然语言处理·nlp