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

Custom endpoints for AsyncSlackRequestHandler

Open ivanrezic opened this issue 1 year ago • 1 comments

Hey, I have been using slack bolt for some time without issues but when I wanted to add custom endpoints I was not able to do it. I followed example following this issue solution but without any success.

The slack_bolt version

slack_bolt==1.20.0 slack_sdk==3.31.0

Python runtime version

Python 3.11.9

OS info

Docker with first 2 lines: FROM python:3.11 RUN apt-get update && apt-get install libpq-dev -y && rm -rf /var/lib/apt/lists/*

Steps to reproduce:

this is my main.py

import re
from contextlib import asynccontextmanager

from api.slack.extract import extract_data
from fastapi import FastAPI, Request
from fastapi.responses import PlainTextResponse
from slack_bolt.adapter.fastapi.async_handler import AsyncSlackRequestHandler
from slack_bolt.async_app import AsyncApp

from prisma import Prisma

prisma = Prisma()


@asynccontextmanager
async def lifespan(app: FastAPI):
    prisma.connect()
    yield
    prisma.disconnect()


api = FastAPI(lifespan=lifespan)
slack = AsyncApp()
app_handler = AsyncSlackRequestHandler(slack)


@slack.command(re.compile("(/extract|test-extract)"))
async def extract(ack, respond, command):
    await ack()

    if not command["text"].isdigit():
        await respond("Invalid question id. Please provide integer value of question/model id.")
        return

    question_id = int(command["text"])
    user_id = command["user_id"]

    client = Prisma()
    client.connect()

    await extract_data(question_id, respond, client, user_id)
    client.disconnect()


@slack.event("app_home_opened")
async def update_home_tab(client, event, logger):
    try:
        await client.views_publish(
            user_id=event["user"],
            view={
                "type": "home",
                "callback_id": "home_view",
                "blocks": [
                    {
                        "type": "section",
                        "text": {"type": "mrkdwn", "text": "*Welcome to your Extraction Workflow's Home tab* :tada:"},
                    },
                    {"type": "divider"},
                    {
                        "type": "section",
                        "text": {
                            "type": "mrkdwn",
                            "text": "To extract cases from metabase question or model "
                            "use `/extract <question/model id>` command. Make sure that question/model contains"
                            " *slug* column.",
                        },
                    },
                ],
            },
        )

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


@api.get("/metrics")
async def get_metrics():
    metrics = prisma.get_metrics(format="prometheus")
    return PlainTextResponse(content=metrics)


@api.post("/slack/events")
async def endpoint(req: Request):
    return await app_handler.handle(req)

and if I run it with uvicorn src.api.main:app it works correctly but doesn't show /metrics endpoint and if I run it with uvicorn src.api.main:api I get error message: ERROR: Error loading ASGI app. Attribute "api" not found in module "src.api.main".

ivanrezic avatar Aug 24 '24 10:08 ivanrezic

Hi @ivanrezic, thanks for asking the question.

Perhaps, something might be wrong with your filepath, filename, variable name (app vs api etc.). Please double-check if there is something unintentional in your code and settings.

Also, trying our examples here: https://github.com/slackapi/bolt-python/tree/main/examples/fastapi may be helpful for identifying what's wrong with your one. I hope you'll figure the cause of your situation out soon!

seratch avatar Aug 25 '24 23:08 seratch

👋 It looks like this issue has been open for 30 days with no activity. We'll mark this as stale for now, and wait 10 days for an update or for further comment before closing this issue out. If you think this issue needs to be prioritized, please comment to get the thread going again! Maintainers also review issues marked as stale on a regular basis and comment or adjust status if the issue needs to be reprioritized.

github-actions[bot] avatar Sep 30 '24 00:09 github-actions[bot]

As this issue has been inactive for more than one month, we will be closing it. Thank you to all the participants! If you would like to raise a related issue, please create a new issue which includes your specific details and references this issue number.

github-actions[bot] avatar Oct 14 '24 00:10 github-actions[bot]