Diagrama da Arquitetura Multi-Plataforma¶
Arquitetura Geral¶
graph TB
subgraph "Plataformas de Mensageria"
Slack[fa:fa-slack Slack]
Telegram[fa:fa-telegram Telegram]
WhatsApp[fa:fa-whatsapp WhatsApp]
Discord[fa:fa-discord Discord]
end
subgraph "unified_bot.py - FastAPI"
Webhook[Webhook Unificado<br/>/webhook/*]
Router[Router]
Health[Health Check<br/>/]
end
subgraph "Messaging Framework"
Factory[AdapterFactory]
subgraph "Adapters"
SlackAdp[SlackAdapter]
TelegramAdp[TelegramAdapter]
WhatsAppAdp[WhatsAppAdapter]
DiscordAdp[DiscordAdapter]
end
Processor[ConversationProcessor]
end
subgraph "Core"
Runner[ADK Runner]
Agent[root_agent]
Session[SessionService]
Memory[MemoryService]
end
subgraph "Backends"
Redis[(Redis)]
CloudSQL[(CloudSQL)]
end
Slack -->|POST /webhook/slack/events| Webhook
Telegram -->|POST /webhook/telegram/webhook| Webhook
WhatsApp -->|POST /webhook/whatsapp/webhook| Webhook
Discord -->|POST /webhook/discord/webhook| Webhook
Webhook --> Router
Router --> Factory
Factory -.gerencia.-> SlackAdp
Factory -.gerencia.-> TelegramAdp
Factory -.gerencia.-> WhatsAppAdp
Factory -.gerencia.-> DiscordAdp
SlackAdp -->|IncomingMessage| Processor
TelegramAdp -->|IncomingMessage| Processor
WhatsAppAdp -->|IncomingMessage| Processor
DiscordAdp -->|IncomingMessage| Processor
Processor --> Runner
Runner --> Agent
Runner --> Session
Runner --> Memory
Session --> Redis
Memory --> CloudSQL
Processor -->|OutgoingMessage| SlackAdp
Processor -->|OutgoingMessage| TelegramAdp
Processor -->|OutgoingMessage| WhatsAppAdp
Processor -->|OutgoingMessage| DiscordAdp
SlackAdp -->|Resposta| Slack
TelegramAdp -->|Resposta| Telegram
WhatsAppAdp -->|Resposta| WhatsApp
DiscordAdp -->|Resposta| Discord
style Webhook fill:#4CAF50
style Router fill:#2196F3
style Factory fill:#FF9800
style Processor fill:#9C27B0
style Runner fill:#F44336
style Agent fill:#E91E63
Fluxo de Mensagem¶
sequenceDiagram
participant User as 👤 Usuário
participant Platform as Slack/Telegram/etc
participant Webhook as Webhook Unificado
participant Factory as AdapterFactory
participant Adapter as MessagingAdapter
participant Processor as ConversationProcessor
participant Runner as ADK Runner
participant Agent as root_agent
User->>Platform: Envia mensagem
Platform->>Webhook: POST /webhook/{platform}/...
Webhook->>Factory: get_adapter_by_webhook_path()
Factory-->>Webhook: adapter
Webhook->>Adapter: parse_webhook_request()
Adapter-->>Webhook: IncomingMessage
Webhook->>Processor: process_message(message, adapter)
Processor->>Adapter: send_typing_indicator()
Adapter-->>Platform: "🔍 Processando..."
Processor->>Runner: run_async(session_id, user_id, message)
loop Eventos do ADK
Runner->>Agent: Processar
Agent-->>Runner: Event (tool_call)
Runner-->>Processor: Event
Processor->>Adapter: update_message("🔍 Buscando...")
Adapter-->>Platform: Atualiza status
end
Runner-->>Processor: Event (final_response)
Processor->>Adapter: delete_message(status)
Adapter->>Platform: Remove "Processando..."
Processor->>Adapter: send_message(response)
Adapter->>Platform: Envia resposta
Platform->>User: Exibe resposta
Estrutura de Dados¶
classDiagram
class MessagingAdapter {
<<abstract>>
+config: Dict
+setup()
+parse_webhook_request() IncomingMessage
+send_message(OutgoingMessage) bool
+send_typing_indicator()
+update_message()
+delete_message()
+format_text(text) str
+platform_name: str
+webhook_path: str
}
class SlackAdapter {
-bot_app: AsyncApp
-bot_user_id: str
+_clean_mentions()
}
class TelegramAdapter {
-bot: Bot
-bot_username: str
}
class WhatsAppAdapter {
-client: TwilioClient
}
class IncomingMessage {
+platform: str
+user_id: str
+channel_id: str
+thread_id: str
+text: str
+message_type: MessageType
+is_direct_message: bool
+metadata: Dict
}
class OutgoingMessage {
+text: str
+channel_id: str
+thread_id: str
+message_type: MessageType
+metadata: Dict
}
class AdapterFactory {
-_adapters: Dict
+register_from_env()
+register_from_config()
+get_adapter(platform)
+get_adapter_by_webhook_path()
+setup_all()
}
class ConversationProcessor {
-runner: Runner
+process_message()
}
MessagingAdapter <|-- SlackAdapter
MessagingAdapter <|-- TelegramAdapter
MessagingAdapter <|-- WhatsAppAdapter
MessagingAdapter ..> IncomingMessage : creates
MessagingAdapter ..> OutgoingMessage : uses
AdapterFactory o-- MessagingAdapter : manages
ConversationProcessor --> MessagingAdapter : uses
Comparação: Antes vs Depois¶
Antes (slack_bot.py - Monolítico)¶
graph LR
Slack[Slack] --> Bot[slack_bot.py<br/>450+ linhas]
Bot --> ADK[ADK Runner]
style Bot fill:#F44336
Problemas: - ❌ Código acoplado ao Slack - ❌ Impossível adicionar WhatsApp sem reescrever - ❌ Lógica misturada (webhook + processamento + formatação) - ❌ Difícil testar
Depois (unified_bot.py - Modular)¶
graph TB
Slack[Slack] --> SlackAdp[SlackAdapter]
Telegram[Telegram] --> TelegramAdp[TelegramAdapter]
WhatsApp[WhatsApp] --> WhatsAppAdp[WhatsAppAdapter]
SlackAdp --> Processor[ConversationProcessor]
TelegramAdp --> Processor
WhatsAppAdp --> Processor
Processor --> ADK[ADK Runner]
style Processor fill:#4CAF50
style SlackAdp fill:#2196F3
style TelegramAdp fill:#2196F3
style WhatsAppAdp fill:#2196F3
Vantagens: - ✅ Código desacoplado - ✅ Adicionar plataforma = criar 1 adapter (~100 linhas) - ✅ Separação de responsabilidades - ✅ Fácil testar cada componente - ✅ Webhook único
Deploy Multi-Região¶
graph TB
subgraph "Internet"
Users[👥 Usuários]
end
subgraph "Load Balancer"
LB[Cloud Load Balancer]
end
subgraph "us-central1"
Bot1[unified_bot.py]
Redis1[(Redis)]
end
subgraph "europe-west1"
Bot2[unified_bot.py]
Redis2[(Redis)]
end
subgraph "asia-east1"
Bot3[unified_bot.py]
Redis3[(Redis)]
end
subgraph "Global"
CloudSQL[(CloudSQL<br/>Multi-Region)]
end
Users --> LB
LB --> Bot1
LB --> Bot2
LB --> Bot3
Bot1 --> Redis1
Bot2 --> Redis2
Bot3 --> Redis3
Bot1 --> CloudSQL
Bot2 --> CloudSQL
Bot3 --> CloudSQL
style LB fill:#4CAF50
style CloudSQL fill:#FF9800
Ciclo de Vida do Adapter¶
stateDiagram-v2
[*] --> Created: AdapterFactory.register()
Created --> Validated: _validate_config()
Validated --> Initialized: setup()
Initialized --> Ready: Cliente conectado
Ready --> Processing: Webhook recebido
Processing --> Parsing: parse_webhook_request()
Parsing --> Ready: IncomingMessage criado
Ready --> Sending: send_message()
Sending --> Ready: Mensagem enviada
Ready --> Cleaning: cleanup()
Cleaning --> [*]
Validated --> Error: Config inválida
Initialized --> Error: Falha conexão
Error --> [*]
Diagramas criados com Mermaid - Podem ser visualizados em: - GitHub (renderização automática) - VSCode (extensão Mermaid) - mermaid.live