首页 > 解决方案 > Java bolt 用于 slack 映射块 json 并将其发送到 slack

问题描述

我试图在 slack 上看到以下消息:

{
    "blocks": [{
        "type": "actions",
        "elements": [{
                "type": "button",
                "text": {
                    "type": "plain_text",
                    "text": "Farmhouse",
                    "emoji": true
                },
                "value": "click_me_123"
            },
            {
                "type": "button",
                "text": {
                    "type": "plain_text",
                    "text": "Kin Khao",
                    "emoji": true
                },
                "value": "click_me_123",
                "url": "https://google.com"
            },
            {
                "type": "button",
                "text": {
                    "type": "plain_text",
                    "text": "Ler Ros",
                    "emoji": true
                },
                "value": "click_me_123",
                "url": "https://google.com"
            }
        ]
    }]
}

现在在 java 端,我使用 gson 将其映射到一个对象,然后使用 ctx.say() 发送它:

List<LayoutBlock> blocks = answers.stream().map(ans -> 
   gson.fromJson(ans.getContent(), LayoutBlock.class)                                 
     ).collect(Collectors.toList());

现在这个映射失败了。如果我尝试使用更简单的 json 它可以工作:

{
          "type": "actions",
          "elements": [
            {
              "type": "button",
              "text": {
                "type": "plain_text",
                "text": "Option 1",
                "emoji": true
              },
              "value": "{ \"name\": \"smalltalk.appraisal.thank_you\", \"entities\": { \"reply\": \"test\", \"option\": \"1\" } }"
            },
            {
              "type": "button",
              "text": {
                "type": "plain_text",
                "text": "Option 2",
                "emoji": true
              },
              "value": "{ \"name\": \"smalltalk.appraisal.thank_you\", \"entities\": { \"reply\": \"test\", \"option\": \"2\" } }"
            }
          ]
        }

基本上我看到的是,当使用 ctx.say() 时,您可以发送一个字符串或一个块列表:

  default ChatPostMessageResponse say(String text) throws IOException, SlackApiException {
        this.verifyChannelId();
        ChatPostMessageResponse response = this.client().chatPostMessage(ChatPostMessageRequest.builder().text(text).channel(this.getChannelId()).build());
        return response;
    }

    default ChatPostMessageResponse say(List<LayoutBlock> blocks) throws IOException, SlackApiException {
        this.verifyChannelId();
        ChatPostMessageResponse response = this.client().chatPostMessage(ChatPostMessageRequest.builder().blocks(blocks).channel(this.getChannelId()).build());
        return response;
    }

我应该如何将 slack block kit builder 中显示的 json 转换为可以使用 ctx.say() 实际发送的 java 对象?

标签: javajsonslack

解决方案


推荐阅读