From 0dcd3c045e702a3115d76b76b163b96110d1a398 Mon Sep 17 00:00:00 2001 From: Jordan Austin Date: Wed, 12 Jul 2023 10:40:41 -0500 Subject: [PATCH] handle slack error with 422 --- app/api/slack/routes.py | 24 +++++++++++++++++------- app/main.py | 2 +- 2 files changed, 18 insertions(+), 8 deletions(-) diff --git a/app/api/slack/routes.py b/app/api/slack/routes.py index 9a8ce03..8bbf385 100644 --- a/app/api/slack/routes.py +++ b/app/api/slack/routes.py @@ -7,7 +7,7 @@ from pydantic import BaseModel from utils import get_logger from config import settings - +from slack.errors import SlackApiError logger = get_logger("app") @@ -51,14 +51,20 @@ def send_to_slack( examples={ "Send plaintext message": { "value": { - "channel": "#test-channel", + "channel": "#testing", "mentions": ["@test-user"], "text": "Hello, World!", }, }, + "422 response for non-existing channel": { + "value": { + "channel": "#not-a-real-channel", + "text": "This will not work!", + }, + }, "Send blocks": { "value": { - "channel": "#test-channel", + "channel": "#testing", "blocks": [ { "type": "section", @@ -121,8 +127,12 @@ def send_to_slack( if any(user_ids): mentions_text = " ".join(f"<@{user_id}>" for user_id in user_ids if user_id) text = f"{mentions_text} {text}" - if text and not blocks: - result = client.chat_postMessage(channel=channel, text=text) - else: - result = client.chat_postMessage(channel=channel, blocks=blocks) + try: + if text and not blocks: + result = client.chat_postMessage(channel=channel, text=text) + else: + result = client.chat_postMessage(channel=channel, blocks=blocks) + except SlackApiError as e: + logger.error(e.response) + raise HTTPException(status_code=422, detail=f"Slack API error: {e.response.get('error')}") return {"result": result.get("ok")} diff --git a/app/main.py b/app/main.py index b878efe..75b0931 100755 --- a/app/main.py +++ b/app/main.py @@ -15,7 +15,7 @@ logger = logging.getLogger("app") dictConfig(log_config) -app_version = "v1.0.0" +app_version = "v0.1.1" app = FastAPI( title="FastAPI Slackbot API", debug=settings.DEBUG,