bolt-python icon indicating copy to clipboard operation
bolt-python copied to clipboard

How can I handle any button press in one single slack-bolt function?

Open MihailovAlexander opened this issue 1 year ago • 1 comments

import os
from slack_bolt import App
from slack_sdk.socket_mode import SocketModeClient
from slack_bolt.adapter.socket_mode import SocketModeHandler

app = App(token=os.environ.get("SLACK_BOT_TOKEN"))

@app.action("button_click")
def action_button_click(body, ack, say):
    ack()
    say(f"<@{body['user']['id']}> clicked the button")

if __name__ == "__main__":
    client = SocketModeClient(app_token=os.environ["SLACK_APP_TOKEN"])
    SocketModeHandler(app, os.environ["SLACK_APP_TOKEN"]).start()

Hello. I have about 10 different buttons with different action_id. How can I make them all handled by one function?

MihailovAlexander avatar Aug 22 '24 09:08 MihailovAlexander

Hi @MihailovAlexander, thanks for asking the question. If you can have prefix for the action_ids (say, expense_workflow_1,2,3), you can pass regexp that matches those action_ids to app.action decorator. Hope this helps.

seratch avatar Aug 22 '24 09:08 seratch

@seratch Thank you! It works:

import os
import re
from slack_bolt import App
from slack_sdk.socket_mode import SocketModeClient
from slack_bolt.adapter.socket_mode import SocketModeHandler

app = App(token=os.environ.get("SLACK_BOT_TOKEN"))

# Regular expression to handle action_id starting with "expense_workflow_"
@app.action(re.compile(r"^expense_workflow_"))
def action_button_click(body, ack, say):
    ack()
    say(f"<@{body['user']['id']}> clicked the button with action_id: {body['actions'][0]['action_id']}")

if __name__ == "__main__":
    client = SocketModeClient(app_token=os.environ["SLACK_APP_TOKEN"])
    SocketModeHandler(app, os.environ["SLACK_APP_TOKEN"]).start()

MihailovAlexander avatar Sep 03 '24 04:09 MihailovAlexander