slack-apislack-commandsslack-block-kit

Passing additional data to the action listeners along with the block_actions payload in Slack Bolt python


I am new to Slack APP development, I am developing the app using Slack bolt python. In my app I have configured the slack interaction using the button click, on clicking the button I am calling the corresponding listener(identified by action_id mentioned in the button). In the listener I am getting the block_actions payload which contains all the state values of the event, but in addition to that I want to some arguments to the listener function. Is it possible in any way that we can send additional arguments to the listeners

@app.action("change_time_period")
def handle_change_time_period(ack, context, body, client, logger, message, say):
   # want the arguments here such as passing email_id from post_data

def post_data(user_id, email_id):
    client = WebClient(token=os.environ.get("SLACK_BOT_TOKEN"))
    result = client.chat_postMessage(
        channel=user_id,
        blocks=[

            {
                "type": "actions",
                "elements": [
                    {
                        "type": "button",
                        "text": {
                            "type": "plain_text",
                            "emoji": True,
                            "text": "Change time period"
                        },
                        "style": "primary",
                        "value": "time_period",
                        "action_id": "change_time_period"
                    }
                ]
            }
        ]

    )


In the code above, I will be calling the post_data which will post the message containing the block kit, once the user clicks the button the handle_change_time_period will be called


Solution

  • Slack block kit buttons do not have a field where we can pass metadata to the interactivity handler. One workaround to achieve this would be to make use of the value field of the button element dict to dump a JSON with the required data. From the Slack API doc, the value field can hold a maximum of 2000 characters. Your value field can be something like

    "value": json.dumps({"actual_value" : "time_period", "email" : "johndoe@abc.com"})
    

    This can be optimized further by reducing the characters in keys. If the extra data you need to pass goes beyond the char limit, you might have to consider caching the data on the server and passing a cache key in the block which can then be used in handler to retrieve the actual data from the cache.