# 使用飞书消息卡片模板，减少代码硬编码 JSON

- Link: https://www.ixiqin.com/2023/08/22/use-feishu-message-card-template-to-reduce-code-hardcoding/
- Published: 2023-08-22T06:37:48+08:00
- Author: 白宦成

文章目录

 [Toggle](https://www.ixiqin.com/2023/08/22/use-feishu-message-card-template-to-reduce-code-hardcoding/#)

 * [在卡片构建工具中新建卡片](https://www.ixiqin.com/2023/08/22/use-feishu-message-card-template-to-reduce-code-hardcoding/#%e5%9c%a8%e5%8d%a1%e7%89%87%e6%9e%84%e5%bb%ba%e5%b7%a5%e5%85%b7%e4%b8%ad%e6%96%b0%e5%bb%ba%e5%8d%a1%e7%89%87)
    - [一些 Tips](https://www.ixiqin.com/2023/08/22/use-feishu-message-card-template-to-reduce-code-hardcoding/#%e4%b8%80%e4%ba%9b_tips)

在开发短链助手时，一个很大的痛苦的点是我希望通过消息卡片来完成开发者的交互，这意味
着我需要有大量的行为是和消息卡片来完成的。而消息卡片又不同于 HTML，是一个比较明确
的 DSL。消息卡片更多是基于 JSON 提供的一套 Schema，将其放在代码中管理也是一个非常
麻烦的事情。

好在最近飞书开放平台迭代了消息卡片模板的功能，我可以不用把 JSON 存在代码中，而是
只在代码中存一个 Template ID ，从而降低我在代码中维护这段 JSON 的难度。

## 在卡片构建工具中新建卡片

首先，你需要打开[消息卡片搭建工具](https://open.feishu.cn/tool/cardbuilder)，并在
其中创建一个新的卡片（你可以使用其提供的卡片组的能力，来管理你的卡片们）。比如我
就要这个卡片组来管理短链助手和其他场景的卡片。

![](https://postimg.aliavv.com/m1/7rmbt4.png)

创建卡片完成后，你可以在 UI 上点击保存并发布，你就将你的卡片消息模板发布到了飞书
的服务器。

![](https://postimg.aliavv.com/m1/o69het.png)

此时，你就可以在代码中使用了。点击页面中间的 ID，复制消息卡片模板 ID，将你的调用
代码替换为对应的逻辑即可。

![](https://postimg.aliavv.com/m1/lv64d7.png)

使用模板需要注意，将消息卡片中的 Content 从过去的卡片内容，替换为 template 的 JSON。
比如，使用卡片 JSON 发送的时候，我们发送的数据可能是这样的：

    ```shcb-line-numbers
    {
        "receive_id": "oc_820faa21d7ed275b53d1727a0feaa917",
        "content": "{\"config\":{\"wide_screen_mode\":true},\"elements\":[{\"alt\":{\"content\":\"\",\"tag\":\"plain_text\"},\"img_key\":\"img_7ea74629-9191-4176-998c-2e603c9c5e8g\",\"tag\":\"img\"},{\"tag\":\"div\",\"text\":{\"content\":\"你是否曾因为一本书而产生心灵共振，开始感悟人生？\\n你有哪些想极力推荐给他人的珍藏书单？\\n\\n加入 **4·23 飞书读书节**，分享你的**挚爱书单**及**读书笔记**，**赢取千元读书礼**！\\n\\n📬 填写问卷，晒出你的珍藏好书\\n😍 想知道其他人都推荐了哪些好书？马上[入群围观](https://open.feishu.cn/)\\n📝 用[读书笔记模板](https://open.feishu.cn/)（桌面端打开），记录你的心得体会\\n🙌 更有惊喜特邀嘉宾 4月12日起带你共读\",\"tag\":\"lark_md\"}},{\"actions\":[{\"tag\":\"button\",\"text\":{\"content\":\"立即推荐好书\",\"tag\":\"plain_text\"},\"type\":\"primary\",\"url\":\"https://open.feishu.cn/\"},{\"tag\":\"button\",\"text\":{\"content\":\"查看活动指南\",\"tag\":\"plain_text\"},\"type\":\"default\",\"url\":\"https://open.feishu.cn/\"}],\"tag\":\"action\"}],\"header\":{\"template\":\"turquoise\",\"title\":{\"content\":\"📚晒挚爱好书，赢读书礼金\",\"tag\":\"plain_text\"}}}",
        "msg_type": "interactive"
    }
    Code language: JSON / JSON with Comments (json)
    ```

而在使用模板时，我们只需要很短的内容就可以：

    ```shcb-line-numbers
    {
          "receive_id": "ou_7d8a6exxxxccs",
          "msg_type": "interactive",
          "content": "{\"type\": \"template\", \"data\": { \"template_id\": \"ctp_xxxxxxxxxxxx\", \"template_variable\": {\"article_title\": \"这是文章标题内容\"} } }"
      }
    Code language: JSON / JSON with Comments (json)
    ```

这样你就可以把过去又臭又长的 JSON 变为一个简短小巧的 Template ID 来完成。

### 一些 Tips

在使用模板时，如果你的模板比较多，那么管理这些模板会比较成问题，一个比较好的办法
是你可以考虑把 template ID 的编辑链接放在你的代码注释里，这样当你需要编辑 JSON 的
时候，只需要点击代码中的链接就可以跳过来编辑了。

    ```shcb-line-numbers
           client.request({
              method: "POST",
              url: "https://open.feishu.cn/open-apis/im/v1/messages",
              data: {
                receive_id: ctx.body.event.operator.operator_id.open_id,
                msg_type: 'interactive',
                content: JSON.stringify({
                  "type": "template",
                  "data": {
                    "template_id": "ctp_AAmFBFOpYX0S", // https://open.feishu.cn/tool/cardbuilder?templateId=ctp_AAmFBFOpYX0S
                  }
                }),
              },
              params: {
                receive_id_type: 'open_id',
              },
            })
    Code language: CSS (css)
    ```
