企业飞书应用机器人,使用python发送图文信息到群

企业飞书应用的自动化,需要创建企业应用,应用开通机器人能力,并获取机器人所需的app_idapp_secret(这一部分大家可以在飞书的控制台获取:https://open.feishu.cn/api-explorer/

文章目录

飞书发送图文信息到群需要以下几个步骤:

  1. 使用机器人先上传图片,获取图片对应的file_key
  2. 将图片对应的file_key与文字内容构造成一个富文本(核心)
  3. 在群里发送构造好的富文本

步骤1:上传图片

比如说上传这样的一个图片叫robot.jpg

博主提供一个整理好的工具函数:

py 复制代码
def fs_upload_pic(pic_path, app_id=None, app_secret=None):
    """上传图片"""

    # 创建client
    client = lark.Client.builder().app_id(app_id).app_secret(app_secret).log_level(lark.LogLevel.DEBUG).build()
    # 构造请求对象
    request: CreateImageRequest = CreateImageRequest.builder().request_body(
        CreateImageRequestBody.builder().image_type("message").image(open(pic_path, "rb")).build()).build()
    # 发起请求
    response: CreateImageResponse = client.im.v1.image.create(request)
    # 处理失败返回
    if not response.success():
        lark.logger.error(
            f"client.im.v1.image.create failed, code: {response.code}, msg: {response.msg}, log_id: {response.get_log_id()}")
        return None
    # 处理业务结果
    return eval(lark.JSON.marshal(response.data))['image_key']

使用方法:

py 复制代码
app_id="cli_xxxx",
app_secret="xxxxx",
img_key = fs_upload_pic("robot.jpg", app_id, app_secret)
print(img_key)

成功上传后得到如下img_key

bash 复制代码
img_v3_02xxxxxxxx

步骤2:构造富文本信息

发送富文本的更多信息可以参考:https://open.feishu.cn/document/server-docs/im-v1/message-content-description/create_json

富文本的内容需要构造成字典的格式:

json 复制代码
{
    "zh_cn": {
        "title": "我是一个标题",
        "content": [
            [
                {
                    "tag": "text",
                    "text": "第一行:",
                    "style": ["bold", "underline"]
                },
                {"tag": "a", "href": "http://www.feishu.cn", "text": "超链接", "style": ["bold", "italic"]},
                {"tag": "at", "user_id": "ou_1avnmsbv3k45jnk34j5", "style": ["lineThrough"]}
            ],
        ]
    }}

发送富文本,博主这里提供一个工具函数,其中几个参数:

  1. rich_content:字典格式的富文本内容
  2. chat_id:发送的群id,在API调试台可以直接获取(https://open.feishu.cn/api-explorer/

在工具函数中,富文本会经过处理:str(rich_content).replace("'", "\""),这样处理后的字典格式数据就能直接发送了

py 复制代码
def fs_send_rich_text(rich_content: dict, chat_id, app_id=None, app_secret=None):
    """发送富文本"""
    # 创建client
    client = lark.Client.builder().app_id(app_id).app_secret(app_secret).log_level(lark.LogLevel.DEBUG).build()
    # 构造请求对象
    request: CreateMessageRequest = CreateMessageRequest.builder() \
        .receive_id_type("chat_id") \
        .request_body(CreateMessageRequestBody.builder()
                      .receive_id(chat_id)
                      .msg_type("post")
                      .content(str(rich_content).replace("'", "\""))
                      .build()) \
        .build()
    # 发起请求
    response: CreateMessageResponse = client.im.v1.message.create(request)

    # 处理失败返回
    if not response.success():
        lark.logger.error(
            f"client.im.v1.message.create failed, code: {response.code}, msg: {response.msg}, log_id: {response.get_log_id()}")
        return

    # 处理业务结果
    lark.logger.info(lark.JSON.marshal(response.data, indent=4))

使用方法:

py 复制代码
    img_key = "img_v3_02xxxxxx"
    chat_id = "oc_00xxxxxxx"
    # 构造富文本
    send_info = {
        "zh_cn": {
            "title": f"测试发送富文本信息",
            "content": [
                [
                    {
                        "tag": "text",
                        "text": "下面是图片:",
                        "style": ["bold", "underline"]
                    },
                ],
                [{"tag": "img", "image_key": img_key}],
            ]
        },
    }
    fs_send_rich_text(send_info, chat_id, app_id, app_secret)

发送后的效果如下:

相关推荐
FJW0208141 分钟前
Python装饰器
开发语言·python
Allen_LVyingbo4 分钟前
用Python实现辅助病案首页主诊断编码:从数据清洗到模型上线(下)
开发语言·python·安全·搜索引擎·知识图谱·健康医疗
深蓝电商API4 分钟前
Selenium无头浏览器配置与反检测技巧
爬虫·python·selenium
0思必得05 分钟前
[Web自动化] Selenium浏览器对象方法(操纵浏览器)
前端·python·selenium·自动化·web自动化
叫我:松哥9 分钟前
基于Flask的心理健康咨询管理与智能分析,集成AI智能对话咨询、心理测评(PHQ-9抑郁量表/GAD-7焦虑量表)、情绪追踪记录、危机预警识别
大数据·人工智能·python·机器学习·信息可视化·数据分析·flask
徐先生 @_@|||10 分钟前
JetBrains 公司的产品策略和技术架构(IDEA(Java)和Pycharm(Python)的编辑器)
java·python·架构
AAD5558889913 分钟前
光伏组件检测与识别基于RPN_X101-FPN模型实现含Python源码_1
开发语言·python
飞Link17 分钟前
偏好对齐阶段中的通用模型蒸馏、领域模型蒸馏和模型自我提升
python·数据挖掘
whhzhai17 分钟前
装饰器(跨领域调用时增强异常信息)
python
幻云201019 分钟前
Python深度学习:从筑基与巅峰
前端·javascript·vue.js·人工智能·python