简体   繁体   English

单击 Slack 应用程序上的按钮时如何获取字段值?

[英]How to get the field value when clicking on a button on a Slack app?

I've studying Slack Bolt Framework and I created a very simple app that works with a slash command.我研究了 Slack Bolt Framework,并创建了一个非常简单的应用程序,可以使用斜杠命令。 When I type '/cep' the following screen appears:当我键入“/cep”时,会出现以下屏幕:

printscreen打印屏幕

How can I get the input value field when I click the button?单击按钮时如何获取输入值字段?

I'm usind Bolt Framework with Javascript.我在 Javascript 中使用 Bolt 框架。

Here the screen code:这里的屏幕代码:

/ Listen for a slash command invocation 'Busca de CEP'
app.command('/cep', async ({ command, ack, say }) => {
  
  // Acknowledge the command request
  await ack();
  
  await say(
    {
        "blocks": [
            {
                "type": "header",
                "text": {
                    "type": "plain_text",
                    "text": "🔍 Busca de Endereço",
                    "emoji": true
                }
            },
            {
                "type": "divider"
            },
            {
                "type": "section",
                "text": {
                    "type": "plain_text",
                    "text": "Digite o CEP que deseja pesquisar:",
                    "emoji": true
                }
            },
            {
                "type": "input",
                "element": {
                    "type": "plain_text_input",
                    "action_id": "plain_text_input-action"
                },
                "label": {
                    "type": "plain_text",
                    "text": " ",
                    "emoji": true
                }
            },
            {
                "type": "actions",
                "elements": [
                    {
                        "type": "button",
                        "text": {
                            "type": "plain_text",
                            "text": "Buscar",
                            "emoji": true
                        },
                        "value": "submitCEPButton",
                        "action_id": "submitCEPButton"
                    }
                ]
            }
        ]
    }
  )
  
});

Here the slash command code:这里是斜杠命令代码:

/ Action listener function called when an interactive component with action_id of “click_me_button” is triggered
app.action('submitCEPButton', async ({ ack, body, client, say }) => {
  // Acknowledge action request before anything else
  await ack();
  
  let channelID = body.channel.id
  let userID = body.user.id
  
  // Respond to action with an ephemeral message
  await client.chat.postEphemeral({
    channel: channelID,
    user: userID,
    text: `<@${userID}> clicked the button! 🎉`
  });
});

UPDATE更新

Screen code when I type the slash command '/cep'键入斜杠命令“/cep”时的屏幕代码

app.command('/cep', async ({ command, ack, say }) => {
  
  // Acknowledge the command request
  await ack();
  
  await say(
    {
        "blocks": [
            {
                "type": "header",
                "block_id": "headerBlock",
                "text": {
                    "type": "plain_text",
                    "text": "🔍 Busca de Endereço",
                    "emoji": true
                }
            },
            {
                "type": "divider",
                "block_id": "dividerBlock",
            },
            {
                "type": "section",
                "block_id": "sectionBlock",
                "text": {
                    "type": "plain_text",
                    "text": "Digite o CEP que deseja pesquisar:",
                    "emoji": true
                }
            },
            {
                "type": "input",
                "block_id": "inputBlock",
                "element": {
                    "type": "plain_text_input",
                    "action_id": "inputCEP"
                },
                "label": {
                    "type": "plain_text",
                    "text": " ",
                    "emoji": false
                }
            },
            {
                "type": "actions",
                "block_id": "submitBlock",
                "elements": [
                    {
                        "type": "button",
                        "text": {
                            "type": "plain_text",
                            "text": "Buscar",
                            "emoji": true
                        },
                        "value": "submitCEPButton",
                        "action_id": "submitCEPButton"
                    }
                ]
            }
        ]
    }
  )
  
});

The command when I click the button单击按钮时的命令

// Action listener function called when an interactive component with action_id of “click_me_button” is triggered
app.action('submitCEPButton', async ({ ack, body, client, say }) => {
  // Acknowledge action request before anything else
  await ack();
  
  let channelID = body.channel.id
  let userID = body.user.id
  console.log(body.state.values)
});

The result printed in console:控制台打印的结果:

{
  njQfY: {
    'plain_text_input-action': { type: 'plain_text_input', value: 'abc123' }
  }
}


you need to view.state.values from the view_submission payload.您需要从view.state.values有效负载中查看.state.values。


Refrence: https://api.slack.com/reference/interaction-payloads/views参考: https://api.slack.com/reference/interaction-payloads/views

You need to focus on block_id & action_id as that can be tricky.您需要关注block_id 和 action_id因为这可能很棘手。

I've some same question and I find the offical document is very helpful.我有一些相同的问题,我发现官方文档非常有帮助。

The link: https://slack.dev/bolt-js/concepts#action-listening链接: https://slack.dev/bolt-js/concepts#action-listening

  1. we should have app.action to listen for the input action我们应该有 app.action 来监听输入动作
  2. we should get the data from the body.我们应该从身体中获取数据。

here are two examples这里有两个例子

  1. use a constraints object to listen to callback_ids, block_ids, and action_ids :使用约束 object 来监听callback_ids, block_ids, and action_ids
// Your listener function will only be called when the action_id matches 'select_user' AND the block_id matches 'assign_ticket'
app.action({ action_id: 'select_user', block_id: 'assign_ticket' },
  async ({ body, client, ack, logger }) => {
    await ack();
    try {
      // Make sure the action isn't from a view (modal or app home)
      if (body.message) {
        const result = await client.reactions.add({
          name: 'white_check_mark',
          timestamp: body.message.ts,
          channel: body.channel.id
        });

        logger.info(result);
      }
    }
    catch (error) {
      logger.error(error);
    }
  });
  1. only listen to action id只听 action id
  app.action('reply_input_action', replyGptBlockActionCallback)

inside the function replyGptBlockActionCallback function里面回复replyGptBlockActionCallback

export async function replyGptBlockActionCallback ({ ack, say, body, client }: any): Promise<void> {
  try {
    await ack()

    const question = body.state.values.reply_block.reply_input_action.value
    await say(question)

  } catch (error) {
    console.error(error)
  }
}


Pay more attention to the input block, which should has action_id and block_id .多注意input块,它应该有action_id and block_id

const dispatchActionInput = {
  dispatch_action: true,
  type: 'input',
  block_id: 'reply_block',
  element: {
    type: 'plain_text_input',
    action_id: 'reply_input_action'
  },
  label: {
    type: 'plain_text',
    text: 'reply',
    emoji: true
  }
}

Here is the data structure for body这是body的数据结构

{
  type: 'block_actions',
  user: {
    id: 'U04F78MRW0K',
    username: 'sherwin.water3',
    name: 'sherwin.water3',
    team_id: 'T04F9RH6ZTN'
  },
  api_app_id: 'A04ESSBBNS3',
  token: 'jDlakpUvYsAZvF5ePimZ7oQK',
  container: {
    type: 'message',
    message_ts: '1672858267.740819',
    channel_id: 'D04FL2JQM0R',
    is_ephemeral: false
  },
  trigger_id: '4595382578642.4519867237940.0d111b689bf06a995d8b5f35d2d49c3c',
  team: { id: 'T04F9RH6ZTN', domain: 'chat2022' },
  enterprise: null,
  is_enterprise_install: false,
  channel: { id: 'D04FL2JQM0R', name: 'directmessage' },
  message: {
    bot_id: 'B04F7D6S63U',
    type: 'message',
    text: "This content can't be displayed.",
    user: 'U04F79VBPRR',
    ts: '1672858267.740819',
    app_id: 'A04ESSBBNS3',
    blocks: [ [Object], [Object] ],
    team: 'T04F9RH6ZTN'
  },
  state: { values: { gpt_conversation_block: [Object] } },
  response_url: 'https://hooks.slack.com/actions/T04F9RH6ZTN/4595268069731/XyH12GdoZOya8yXmdq7cysRr',
  actions: [
    {
      type: 'plain_text_input',
      block_id: 'gpt_conversation_block',
      action_id: 'gpt_input_action',
      value: 'hello',
      action_ts: '1672858271.476569'
    }
  ]
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM