pythonflaskslackslack-apislack-block-kit

how to apply Slack app_home_opened event in Python Flask Slack App


I am currently working on Slack Event API to show the Home tab in the existed Slack App. So, I am struggling to implement app_home_opened from the Slack Event API to the app. The app is developed by Python Flask. And when I tried to show home tab in the dummy app which is not using flask, it was succeed. But I want to implement in Python Flask.

Here is the code I was succeed in my dummy app.

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

...

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

...

@app.event("app_home_opened")
def update_home_tab(client, event, logger):
  try:
    client.views_publish(
      user_id=event["user"],
      view={
        "type": "home",
        "callback_id": "home_view",
        "blocks": [

             ...

        ]
      }
    )
  
  except Exception as e:
    logger.error(f"Error publishing home tab: {e}")

...

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

And I want to apply the code above to the code something like below to show the home tab.

from slack_bolt.adapter.flask import SlackRequestHandler
from flask import Flask

...

app = Flask(__name__)

...

@app.route('/', methods=['GET'])
def main():
    ...

@app.route('/', methods=['POST'])
def slack_events():
    ...

...

if __name__ == '__main__':
    app.run(host='...', port=..., debug=True)

Solution

  • Something like this should work.

    import os
    from slack_bolt import App
    
    ...
    
    app = App(token=os.environ.get("SLACK_BOT_TOKEN"))
    
    ...
    
    @app.event("app_home_opened")
    def update_home_tab(client, event, logger):
      try:
        client.views_publish(
          user_id=event["user"],
          view={
            "type": "home",
            "callback_id": "home_view",
            "blocks": [
    
                 ...
    
            ]
          }
        )
      
      except Exception as e:
        logger.error(f"Error publishing home tab: {e}")
    
    ...
    
    from flask import Flask, request
    from slack_bolt.adapter.flask import SlackRequestHandler
    
    flask_app = Flask(__name__)
    handler = SlackRequestHandler(app)
    
    # endpoint for handling all slack events
    @flask_app.route("/slack/events", methods=["POST"])
    def slack_events():
        return handler.handle(request)
    
    # run flask app
    if __name__ == "__main__":
      flask_app.run(debug=True,host="0.0.0.0", port=8080)
    

    Reference - https://github.com/slackapi/bolt-python/blob/main/examples/flask/app.py