Skip to content

Commit

Permalink
handle slack error with 422
Browse files Browse the repository at this point in the history
  • Loading branch information
jordotech committed Jul 12, 2023
1 parent df266de commit 0dcd3c0
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 8 deletions.
24 changes: 17 additions & 7 deletions app/api/slack/routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")


Expand Down Expand Up @@ -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",
Expand Down Expand Up @@ -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")}
2 changes: 1 addition & 1 deletion app/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down

0 comments on commit 0dcd3c0

Please sign in to comment.