|
1 | 1 | import json |
2 | | -from typing import cast |
3 | 2 |
|
4 | 3 | import httpx |
5 | 4 | import structlog |
|
9 | 8 | from backend.config.settings import settings |
10 | 9 | from backend.workers.tasks.generate_draft import generate_draft_task |
11 | 10 | from backend.workers.tasks.publish_post import publish_post_task |
12 | | -from slack_app.utils.block_builder import build_approval_modal |
| 11 | +from slack_app.utils.block_builder import ( |
| 12 | + build_app_home, |
| 13 | + build_approval_modal, |
| 14 | + build_generation_modal, |
| 15 | +) |
13 | 16 |
|
14 | 17 | logger = structlog.get_logger() |
15 | 18 | router = APIRouter(prefix="/slack", tags=["Slack Integration"]) |
|
19 | 22 | async def slack_slash_command(request: Request): |
20 | 23 | form_data = await request.form() |
21 | 24 | command = form_data.get("command") |
22 | | - text = str(form_data.get("text", "")).strip() |
23 | | - user_id = cast(str, form_data.get("user_id", "")) |
24 | | - channel_id = cast(str, form_data.get("channel_id", "")) |
| 25 | + trigger_id = form_data.get("trigger_id") |
| 26 | + channel_id = str(form_data.get("channel_id")) |
25 | 27 |
|
26 | 28 | if command != "/draft": |
27 | 29 | return {"response_type": "ephemeral", "text": SLACK_UI["cmd_unknown"]} |
28 | 30 |
|
29 | | - if not text: |
30 | | - return {"response_type": "ephemeral", "text": SLACK_UI["cmd_missing_args"]} |
31 | | - |
32 | | - parts = [p.strip() for p in text.split("|")] |
33 | | - topic = parts[0] |
34 | | - platform = parts[1].lower() if len(parts) > 1 else "telegram" |
35 | | - |
36 | | - valid_platforms = ["telegram", "twitter", "threads"] |
37 | | - if platform not in valid_platforms: |
38 | | - return { |
39 | | - "response_type": "ephemeral", |
40 | | - "text": SLACK_UI["cmd_invalid_platform"].format( |
41 | | - platform=platform, valid_platforms=", ".join(valid_platforms) |
42 | | - ), |
43 | | - } |
44 | | - |
45 | | - logger.info( |
46 | | - "slack_command_received", topic=topic, platform=platform, user_id=user_id |
| 31 | + # Відкриваємо модалку замість парсингу тексту |
| 32 | + modal_view = build_generation_modal(channel_id=channel_id) |
| 33 | + slack_token = ( |
| 34 | + settings.SLACK_BOT_TOKEN.get_secret_value() if settings.SLACK_BOT_TOKEN else "" |
47 | 35 | ) |
| 36 | + headers = {"Authorization": f"Bearer {slack_token}"} |
48 | 37 |
|
49 | | - await generate_draft_task.kiq( # type: ignore[call-overload] |
50 | | - topic=topic, platform=platform, user_id=user_id, channel_id=channel_id |
51 | | - ) |
| 38 | + async with httpx.AsyncClient() as client: |
| 39 | + res = await client.post( |
| 40 | + "https://slack.com/api/views.open", |
| 41 | + headers=headers, |
| 42 | + json={"trigger_id": trigger_id, "view": modal_view}, |
| 43 | + ) |
| 44 | + if not res.json().get("ok"): |
| 45 | + logger.error("slack_modal_open_error", error=res.json()) |
52 | 46 |
|
53 | | - return { |
54 | | - "response_type": "in_channel", |
55 | | - "text": SLACK_UI["cmd_accepted"].format(topic=topic, platform=platform), |
56 | | - } |
| 47 | + # Повертаємо 200 OK без тіла, щоб Slack не дублював повідомлення |
| 48 | + return Response(status_code=200) |
57 | 49 |
|
58 | 50 |
|
59 | 51 | @router.post("/interactions") |
@@ -169,34 +161,125 @@ async def slack_interactions(request: Request): |
169 | 161 | }, |
170 | 162 | ) |
171 | 163 |
|
| 164 | + elif action_id == "action_open_generation_modal": |
| 165 | + logger.info("slack_home_generation_btn_clicked", user_id=user_id) |
| 166 | + modal_view = build_generation_modal(channel_id=user_id) |
| 167 | + async with httpx.AsyncClient() as client: |
| 168 | + res = await client.post( |
| 169 | + "https://slack.com/api/views.open", |
| 170 | + headers=headers, |
| 171 | + json={"trigger_id": trigger_id, "view": modal_view}, |
| 172 | + ) |
| 173 | + if not res.json().get("ok"): |
| 174 | + logger.error("slack_modal_error", error=res.json()) |
172 | 175 | return Response(status_code=200) |
173 | 176 |
|
174 | 177 | elif interaction_type == "view_submission": |
175 | 178 | view = payload.get("view", {}) |
| 179 | + callback_id = view.get("callback_id") |
176 | 180 | state_values = view.get("state", {}).get("values", {}) |
177 | 181 |
|
178 | | - draft_content = ( |
179 | | - state_values.get("block_draft_content", {}) |
180 | | - .get("input_draft_content", {}) |
181 | | - .get("value", "") |
182 | | - ) |
183 | | - platform = ( |
184 | | - state_values.get("block_platform_select", {}) |
185 | | - .get("input_platform_select", {}) |
186 | | - .get("selected_option", {}) |
187 | | - .get("value", "telegram") |
188 | | - ) |
| 182 | + # --- СЦЕНАРІЙ 1: Генерація нового драфту --- |
| 183 | + if callback_id == "modal_generate_draft": |
| 184 | + channel_id = view.get("private_metadata") # Дістаємо збережений канал |
| 185 | + topic = ( |
| 186 | + state_values.get("block_topic_input", {}) |
| 187 | + .get("input_topic", {}) |
| 188 | + .get("value", "") |
| 189 | + .strip() |
| 190 | + ) |
| 191 | + platform = ( |
| 192 | + state_values.get("block_platform_select", {}) |
| 193 | + .get("input_platform_select", {}) |
| 194 | + .get("selected_option", {}) |
| 195 | + .get("value", "telegram") |
| 196 | + ) |
189 | 197 |
|
190 | | - logger.info("slack_modal_submitted", user_id=user_id, platform=platform) |
| 198 | + logger.info( |
| 199 | + "slack_generation_modal_submitted", |
| 200 | + user_id=user_id, |
| 201 | + topic=topic, |
| 202 | + platform=platform, |
| 203 | + ) |
191 | 204 |
|
192 | | - await publish_post_task.kiq( |
193 | | - post_id="temp_id", platform=platform, content=draft_content |
194 | | - ) |
| 205 | + # Запускаємо генерацію |
| 206 | + await generate_draft_task.kiq( # type: ignore[call-overload] |
| 207 | + topic=topic, platform=platform, user_id=user_id, channel_id=channel_id |
| 208 | + ) |
195 | 209 |
|
196 | | - return Response( |
197 | | - content=json.dumps({"response_action": "clear"}), |
198 | | - media_type="application/json", |
199 | | - status_code=200, |
| 210 | + # Відправляємо підтвердження в канал |
| 211 | + async with httpx.AsyncClient() as client: |
| 212 | + await client.post( |
| 213 | + "https://slack.com/api/chat.postMessage", |
| 214 | + headers=headers, |
| 215 | + json={ |
| 216 | + "channel": channel_id, |
| 217 | + "text": SLACK_UI["cmd_accepted"].format( |
| 218 | + topic=topic, platform=platform |
| 219 | + ), |
| 220 | + }, |
| 221 | + ) |
| 222 | + |
| 223 | + return Response( |
| 224 | + content=json.dumps({"response_action": "clear"}), |
| 225 | + media_type="application/json", |
| 226 | + status_code=200, |
| 227 | + ) |
| 228 | + |
| 229 | + # --- СЦЕНАРІЙ 2: Збереження відредагованого драфту --- |
| 230 | + elif callback_id == "modal_edit_draft": |
| 231 | + draft_content = ( |
| 232 | + state_values.get("block_draft_content", {}) |
| 233 | + .get("input_draft_content", {}) |
| 234 | + .get("value", "") |
| 235 | + ) |
| 236 | + platform = ( |
| 237 | + state_values.get("block_platform_select", {}) |
| 238 | + .get("input_platform_select", {}) |
| 239 | + .get("selected_option", {}) |
| 240 | + .get("value", "telegram") |
| 241 | + ) |
| 242 | + |
| 243 | + logger.info( |
| 244 | + "slack_edit_modal_submitted", user_id=user_id, platform=platform |
| 245 | + ) |
| 246 | + await publish_post_task.kiq( |
| 247 | + post_id="temp_id", platform=platform, content=draft_content |
| 248 | + ) |
| 249 | + |
| 250 | + return Response( |
| 251 | + content=json.dumps({"response_action": "clear"}), |
| 252 | + media_type="application/json", |
| 253 | + status_code=200, |
| 254 | + ) |
| 255 | + |
| 256 | + return Response(status_code=200) |
| 257 | + |
| 258 | + |
| 259 | +@router.post("/events") |
| 260 | +async def slack_events(request: Request): |
| 261 | + """Обробка Events API (наприклад, відкриття вкладки Home).""" |
| 262 | + data = await request.json() |
| 263 | + |
| 264 | + # 1. Підтвердження URL для Slack (виконується один раз при налаштуванні) |
| 265 | + if data.get("type") == "url_verification": |
| 266 | + return {"challenge": data.get("challenge")} |
| 267 | + |
| 268 | + event = data.get("event", {}) |
| 269 | + user_id = event.get("user") |
| 270 | + |
| 271 | + # 2. Коли користувач відкриває вкладку Home — малюємо йому дашборд |
| 272 | + if event.get("type") == "app_home_opened": |
| 273 | + slack_token = ( |
| 274 | + settings.SLACK_BOT_TOKEN.get_secret_value() |
| 275 | + if settings.SLACK_BOT_TOKEN |
| 276 | + else "" |
200 | 277 | ) |
| 278 | + async with httpx.AsyncClient() as client: |
| 279 | + await client.post( |
| 280 | + "https://slack.com/api/views.publish", |
| 281 | + headers={"Authorization": f"Bearer {slack_token}"}, |
| 282 | + json={"user_id": user_id, "view": build_app_home()}, |
| 283 | + ) |
201 | 284 |
|
202 | 285 | return Response(status_code=200) |
0 commit comments