"""Slack Events API: url_verification, team_join, member_joined_channel, member_left_channel.""" import json from fastapi import APIRouter, Depends, Request from fastapi.responses import PlainTextResponse, JSONResponse from sqlmodel import Session, and_, select from app.core.db import get_session from app.managers.team import get_team_by_id from app.models import ChannelMemberChange, JoinTeamMembers router = APIRouter() @router.get("/events") @router.post("/events") async def events(request: Request, session: Session = Depends(get_session)): body = await request.body() if not body: return PlainTextResponse("") req_data = json.loads(body) e_type = req_data.get("type", "") if e_type == "url_verification": return JSONResponse(content={"challenge": req_data["challenge"]}) event = req_data.get("event", {}) event_type = event.get("type") team_id = req_data.get("team_id") team = get_team_by_id(session, team_id) if team_id else None team_name = team.team_name if team else None if not team_name: return JSONResponse(content={"success": False}, status_code=503) if event_type == "team_join": user_id = event["user"]["id"] email = event["user"]["profile"]["email"] session.add( JoinTeamMembers(user_id=user_id, team=team_name, email=email) ) session.commit() return JSONResponse(content={"success": True}) if event_type in ("member_joined_channel", "member_left_channel"): channel_id = event["channel"] user_id = event["user"] stmt = select(ChannelMemberChange).where( and_( ChannelMemberChange.user_id == user_id, ChannelMemberChange.team == team_name, ChannelMemberChange.channel_id == channel_id, ) ) row = session.exec(stmt).first() is_joined = event_type == "member_joined_channel" if row: row.is_joined = is_joined else: session.add( ChannelMemberChange( user_id=user_id, team=team_name, channel_id=channel_id, is_joined=is_joined, ) ) session.commit() return JSONResponse(content={"success": True}) return JSONResponse(content={"success": True})