开发指南/消息卡片/快速入门/使用自定义机器人发送卡片消息
# 使用自定义机器人发送卡片消息

Lark消息卡片允许通过机器人或应用，以结构化（JSON 数据结构）的方式发送和接收消息。因此，你可以使用消息卡片推送活动通知、业务审批、监控告警以及日程等信息。本文将介绍如何通过群机器人发送消息卡片通知。

## 示例效果

通过本文操作可实现如下图所示的效果，即通过群自定义机器人推送一个示例卡片消息。

![](//sf16-sg.larksuitecdn.com/obj/open-platform-opendoc-sg/a61642e3fad1c9220f8c817b34fe2c30_hH3uZYZEha.png?height=1350&lazyload=true&maxWidth=600&width=2120)

## 操作步骤

### 步骤一：准备工作

本文将使用 Python 代码实现消息卡片的发送，因此需要完成以下准备工作。

1. 在本地开发环境安装 Python 运行环境。

官方安装方式，参见[Python](https://www.python.org/)。

2. 在本地终端内，使用 pip 命令安装 `requests` 包。

Python 版本不同，命令也不同：

- 如果你安装的 Python2，则命令如下所示。

```
        pip install requests
        ```
    - 如果你安装的 Python3，则命令如下所示。

```
        pip3 install requests
        ```

### 步骤二：创建消息卡片

1. 打开[消息卡片搭建工具](https://open.larksuite.com/tool/cardbuilder)页面。

2. 在消息卡片搭建工具页面，单击左侧 **参考案例**，选择消息卡片模版，然后单击 **使用**。

本文选择使用 **活动通知** 模版。

![](//sf16-sg.larksuitecdn.com/obj/open-platform-opendoc-sg/0703dccf7ac75cdb9b930d8fafebbfa7_ekYH8qm4Tg.png?height=1442&lazyload=true&maxWidth=600&width=2882)

3. （可选）编辑卡片内容。

你可以在 **卡片预览** 区域，点击卡片内容进行修改。关于卡片内容构造的相关说明，参见[消息卡片设计规范](https://open.larksuite.com/document/ukTMukTMukTM/ugDOwYjL4gDM24CO4AjN)、[卡片结构介绍](https://open.larksuite.com/document/ukTMukTMukTM/uEjNwUjLxYDM14SM2ATN)。
本示例中，不对 **活动通知** 卡片做任何处理，直接使用该模板进行演示。

![](//sf16-sg.larksuitecdn.com/obj/open-platform-opendoc-sg/99d6a41b10eaa358737ba6f8afd456fc_JdLX6DhWiI.png?height=1418&lazyload=true&maxWidth=600&width=2882)

4. 在页面右上角，点击 **保存并发布**，然后在弹出的对话框中点击 **发布**。

![](//sf16-sg.larksuitecdn.com/obj/open-platform-opendoc-sg/dc05b773eec13b60e816a54ed67ffe94_X9rQwrp3kZ.png?height=1390&lazyload=true&maxWidth=600&width=2882)

### 步骤三：创建群自定义机器人

1. 登录Lark客户端（PC 端）。

2. 选择一个目标群组，在群设置中点击 **群机器人**。

![](//sf16-sg.larksuitecdn.com/obj/open-platform-opendoc-sg/8b428c13cfc712451a4bf00e691ba1df_8hfyh110qu.png?height=1526&lazyload=true&maxWidth=600&width=1814)

3. 点击 **添加机器人**，并选择 **自定义机器人**。

![](//sf16-sg.larksuitecdn.com/obj/open-platform-opendoc-sg/0f985396ea78e017d70bf3af3a7781ad_0Bz9biJxxP.png?height=1528&lazyload=true&maxWidth=600&width=2290)

4. 确认机器人头像、名称与描述，然后点击 **添加**。

![](//sf16-sg.larksuitecdn.com/obj/open-platform-opendoc-sg/57a5eaf0017d148e4227b96def376110_m5zSBQ13y4.png?height=1174&lazyload=true&maxWidth=600&width=1686)

5. 添加后，妥善保管机器人 webhook 地址，并点击 **完成**。    
后续需要向机器人的 webhook 地址发送请求，以发送消息卡片，因此你需要保存该 webhook，并确保数据安全，避免机器人被他人恶意调用。

![](//sf16-sg.larksuitecdn.com/obj/open-platform-opendoc-sg/bfaaf7316f9a5a43db7554da58eb6b8f_g4L2H75YdJ.png?height=1136&lazyload=true&maxWidth=600&width=1664)

### 步骤四：发送消息卡片

1. 在本地创建一个名为 `main.py` 的 Python 文件。

2. 使用本地的代码编辑工具打开 main.py 文件，在文件中添加以下代码，并参考注释手动配置相关参数。
    ```PYTHON
    import requests
    import json
    ## 替换为你的自定义机器人的 webhook 地址。
	url = "https://open.larksuite.com/open-apis/bot/v2/hook/xxxx"
    ## 将消息卡片内容粘贴至此处。
    card_json = r'''
    {
      "config": {
        "wide_screen_mode": true
      },
      "elements": [
        {
          "alt": {
            "content": "",
            "tag": "plain_text"
          },
          "img_key": "img_v2_bfd72a81-1533-4699-995d-12a675708d0g",
          "tag": "img"
        },
        {
          "tag": "div",
          "text": {
            "content": "你是否曾因为一本书而产生心灵共振，开始感悟人生？\n你有哪些想极力推荐给他人的珍藏好书？\n\n加入 **4·23 Lark读书节**，分享你的**挚爱书单**及**读书笔记**，**赢取千元读书礼**！\n\n📬 填写问卷，晒出你的珍藏好书\n😍 想知道其他人都推荐了哪些好书？马上[入群围观](https://open.larksuite.com/)\n📝 用[读书笔记模板](https://open.larksuite.com/)（桌面端打开），记录你的心得体会\n🙌 更有惊喜特邀嘉宾 4月12日起带你共读",
            "tag": "lark_md"
          }
        },
        {
          "actions": [
            {
              "tag": "button",
              "text": {
                "content": "立即推荐好书",
                "tag": "plain_text"
              },
              "type": "primary",
              "url": "https://open.larksuite.com/"
            },
            {
              "tag": "button",
              "text": {
                "content": "查看活动指南",
                "tag": "plain_text"
              },
              "type": "default",
              "url": "https://open.larksuite.com/"
            }
          ],
          "tag": "action"
        }
      ],
      "header": {
        "template": "turquoise",
        "title": {
          "content": "📚晒挚爱好书，赢读书礼金",
          "tag": "plain_text"
        }
      }
    }
    '''
    body = json.dumps({"msg_type": "interactive", "card": card_json})
    headers = {"Content-Type": "application/json"}
    res = requests.post(url=url, data=body, headers=headers)
    print(res.request.body)
    print(res.text)
    ```

参数值配置说明：

- 自定义机器人 webhook 地址：填写你已保存的群机器人 webhook 地址。

- 消息卡片的内容是指卡片的 JSON 数据，获取方式如下：

1. 打开[消息卡片搭建工具](https://open.larksuite.com/tool/cardbuilder)页面。

2. 打开已创建并保存的 **活动通知** 卡片。

3. 在 **编辑卡片** 区域，点击代码图标，获取 JSON 数据。

![](//sf16-sg.larksuitecdn.com/obj/open-platform-opendoc-sg/6938acf0f2a295a39f79c061acc68349_MpTRXqsaGb.png?height=1440&lazyload=true&maxWidth=600&width=2882)

3. 保存文件，并在文件所在路径执行以下命令，运行 `main.py` 文件。

- Python2 环境执行以下命令：

```
        python main.py
        ```

- Python3 环境执行以下命令：

```
        python3 main.py
        ```

4. 在Lark客户端群组中，查看消息卡片信息。

![](//sf16-sg.larksuitecdn.com/obj/open-platform-opendoc-sg/a8a9bb0ad7a5113216504bd98addd51f_GU0FkmwaER.png?height=1634&lazyload=true&maxWidth=600&width=2882)