mirror of
https://github.com/open-webui/computer.git
synced 2026-11-18 11:51:55 +03:00
refac
This commit is contained in:
@@ -10,6 +10,7 @@ from cptr.routers import (
|
||||
auth_router,
|
||||
automations_router,
|
||||
bridge_router,
|
||||
webhook_router,
|
||||
chat_router,
|
||||
events_router,
|
||||
files_router,
|
||||
@@ -202,6 +203,7 @@ app.include_router(admin_router)
|
||||
app.include_router(auth_router)
|
||||
app.include_router(automations_router)
|
||||
app.include_router(bridge_router)
|
||||
app.include_router(webhook_router)
|
||||
app.include_router(chat_router)
|
||||
app.include_router(events_router)
|
||||
app.include_router(files_router)
|
||||
|
||||
@@ -59,7 +59,10 @@
|
||||
|
||||
const platformHints: Record<string, string> = {
|
||||
telegram: 'Create a bot via @BotFather',
|
||||
discord: 'Create a bot in the Developer Portal'
|
||||
discord: 'Create a bot in the Developer Portal',
|
||||
slack: 'Bot Token | App Token (pipe-separated)',
|
||||
whatsapp: 'Access Token | Phone Number ID (pipe-separated)',
|
||||
signal: 'signal-cli URL | Phone Number (pipe-separated)'
|
||||
};
|
||||
|
||||
async function handleVerify() {
|
||||
@@ -146,6 +149,9 @@
|
||||
>
|
||||
<option value="telegram">Telegram</option>
|
||||
<option value="discord">Discord</option>
|
||||
<option value="slack">Slack</option>
|
||||
<option value="whatsapp">WhatsApp</option>
|
||||
<option value="signal">Signal</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -80,10 +80,10 @@
|
||||
<div>
|
||||
{#each bots as bot}
|
||||
<div class="group flex items-center gap-2 w-full h-7">
|
||||
<!-- Platform badge -->
|
||||
<span class="text-[10px] uppercase tracking-wide w-5 text-center shrink-0
|
||||
<!-- Platform icon -->
|
||||
<span class="shrink-0
|
||||
{bot.is_running ? 'text-gray-400 dark:text-gray-500' : 'text-gray-300 dark:text-gray-700'}">
|
||||
{bot.platform === 'telegram' ? 'TG' : bot.platform === 'discord' ? 'DC' : bot.platform.slice(0, 2).toUpperCase()}
|
||||
<Icon name={bot.platform} size={14} />
|
||||
</span>
|
||||
|
||||
<!-- Name (clickable to edit) -->
|
||||
|
||||
@@ -314,5 +314,24 @@
|
||||
<path d="M12 2L2 7L12 12L22 7L12 2Z" />
|
||||
<path d="M2 17L12 22L22 17" />
|
||||
<path d="M2 12L12 17L22 12" />
|
||||
{:else if name === 'telegram'}
|
||||
<path d="M21 5L2 12.5L9 13.5M21 5L18.5 20L9 13.5M21 5L9 13.5M9 13.5V19L12.2488 15.7229" />
|
||||
{:else if name === 'discord'}
|
||||
<path d="M5.5 16C10.5 18.5 13.5 18.5 18.5 16" />
|
||||
<path d="M15.5 17.5L16.5 19.5C16.5 19.5 20.6713 18.1717 22 16C22 15 22.5301 7.85339 19 5.5C17.5 4.5 15 4 15 4L14 6H12" />
|
||||
<path d="M8.52832 17.5L7.52832 19.5C7.52832 19.5 3.35699 18.1717 2.02832 16C2.02832 15 1.49823 7.85339 5.02832 5.5C6.52832 4.5 9.02832 4 9.02832 4L10.0283 6H12.0283" />
|
||||
<path d="M8.5 14C7.67157 14 7 13.1046 7 12C7 10.8954 7.67157 10 8.5 10C9.32843 10 10 10.8954 10 12C10 13.1046 9.32843 14 8.5 14Z" />
|
||||
<path d="M15.5 14C14.6716 14 14 13.1046 14 12C14 10.8954 14.6716 10 15.5 10C16.3284 10 17 10.8954 17 12C17 13.1046 16.3284 14 15.5 14Z" />
|
||||
{:else if name === 'slack'}
|
||||
<path d="M10 3L6 21" />
|
||||
<path d="M20.5 16H2.5" />
|
||||
<path d="M22 7H4" />
|
||||
<path d="M18 3L14 21" />
|
||||
{:else if name === 'whatsapp'}
|
||||
<path d="M22 12C22 17.5228 17.5228 22 12 22C10.1786 22 8.47087 21.513 7 20.6622L2 21.5L2.83209 16C2.29689 14.7751 2 13.4222 2 12C2 6.47715 6.47715 2 12 2C17.5228 2 22 6.47715 22 12Z" />
|
||||
<path d="M12.9604 13.8683L15.0399 13.4624L17 14.2149V16.0385C17 16.6449 16.4783 17.1073 15.8901 16.9783C14.3671 16.6444 11.5997 15.8043 9.67826 13.8683C7.84859 12.0248 7.22267 9.45734 7.01039 8.04128C6.92535 7.47406 7.3737 7 7.94306 7H9.83707L10.572 8.96888L10.1832 11.0701" />
|
||||
{:else if name === 'signal'}
|
||||
<path d="M8.5 11.5L11.5 14.5L16.5 9.5" />
|
||||
<path d="M5 18L3.13036 4.91253C3.05646 4.39524 3.39389 3.91247 3.90398 3.79912L11.5661 2.09641C11.8519 2.03291 12.1481 2.03291 12.4339 2.09641L20.096 3.79912C20.6061 3.91247 20.9435 4.39524 20.8696 4.91252L19 18C18.9293 18.495 18.5 21.5 12 21.5C5.5 21.5 5.07071 18.495 5 18Z" />
|
||||
{/if}
|
||||
</svg>
|
||||
|
||||
@@ -380,8 +380,19 @@
|
||||
}}
|
||||
>
|
||||
<div class="flex items-center gap-2 px-3 pt-2.5 pb-0.5">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="size-3.5 shrink-0 text-gray-400 dark:text-gray-500">
|
||||
<path stroke-linecap="round" stroke-linejoin="round" d="M19.5 14.25v-2.625a3.375 3.375 0 0 0-3.375-3.375h-1.5A1.125 1.125 0 0 1 13.5 7.125v-1.5a3.375 3.375 0 0 0-3.375-3.375H8.25m2.25 0H5.625c-.621 0-1.125.504-1.125 1.125v17.25c0 .621.504 1.125 1.125 1.125h12.75c.621 0 1.125-.504 1.125-1.125V11.25a9 9 0 0 0-9-9Z" />
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke-width="1.5"
|
||||
stroke="currentColor"
|
||||
class="size-3.5 shrink-0 text-gray-400 dark:text-gray-500"
|
||||
>
|
||||
<path
|
||||
stroke-linecap="round"
|
||||
stroke-linejoin="round"
|
||||
d="M19.5 14.25v-2.625a3.375 3.375 0 0 0-3.375-3.375h-1.5A1.125 1.125 0 0 1 13.5 7.125v-1.5a3.375 3.375 0 0 0-3.375-3.375H8.25m2.25 0H5.625c-.621 0-1.125.504-1.125 1.125v17.25c0 .621.504 1.125 1.125 1.125h12.75c.621 0 1.125-.504 1.125-1.125V11.25a9 9 0 0 0-9-9Z"
|
||||
/>
|
||||
</svg>
|
||||
<span class="text-xs font-medium text-gray-800 dark:text-gray-100"
|
||||
>{artifact.title || 'Artifact'}</span
|
||||
@@ -404,7 +415,7 @@
|
||||
{@const isGroupOpen = expandedGroups.has(groupIdx)}
|
||||
{@const hasPendingApproval = calls.some((c: any) => c.status === 'pending')}
|
||||
|
||||
<div class="w-full min-w-0">
|
||||
<div class="w-full min-w-0 flex flex-col my-0.5">
|
||||
<!-- Group header -->
|
||||
<button
|
||||
class="w-full min-w-0 text-left text-gray-500 hover:text-gray-700 dark:hover:text-gray-300 transition cursor-pointer"
|
||||
@@ -412,7 +423,9 @@
|
||||
aria-expanded={isGroupOpen}
|
||||
onclick={() => toggleGroupExpanded(groupIdx)}
|
||||
>
|
||||
<div class="flex items-center gap-1.5 text-sm min-w-0 {hasPending ? 'shimmer' : ''}">
|
||||
<div
|
||||
class="flex items-center gap-1.5 text-sm min-w-0 {hasPending ? 'shimmer' : ''}"
|
||||
>
|
||||
<!-- Status icon -->
|
||||
{#if hasPending}
|
||||
<div class="flex justify-center text-center">
|
||||
@@ -546,14 +559,16 @@
|
||||
{@const isExpanded = expandedCalls.has(callId)}
|
||||
{@const pairedOutput = outputs.get(item.call_id)}
|
||||
|
||||
<div class="w-full min-w-0">
|
||||
<div class="w-full min-w-0 flex flex-col">
|
||||
<!-- Individual tool call row -->
|
||||
<button
|
||||
class="w-full min-w-0 text-left text-gray-500 hover:text-gray-700 dark:hover:text-gray-300 transition cursor-pointer"
|
||||
onclick={() => toggleCallExpanded(callId)}
|
||||
>
|
||||
<div
|
||||
class="flex items-center gap-1.5 text-sm min-w-0 {isExecuting ? 'shimmer' : ''}"
|
||||
class="flex items-center gap-1.5 text-sm min-w-0 {isExecuting
|
||||
? 'shimmer'
|
||||
: ''}"
|
||||
>
|
||||
<!-- Status icon -->
|
||||
{#if isExecuting}
|
||||
@@ -803,7 +818,8 @@
|
||||
<div class="mt-1 space-y-0.5">
|
||||
{#each calls.filter((c: any) => c.status === 'pending') as item}
|
||||
<div class="flex items-center gap-2 py-1 px-1">
|
||||
<span class="text-xs text-gray-500 dark:text-gray-400 flex-1 min-w-0 line-clamp-1"
|
||||
<span
|
||||
class="text-xs text-gray-500 dark:text-gray-400 flex-1 min-w-0 line-clamp-1"
|
||||
>{toolLabel(item.name, item.arguments || {})}</span
|
||||
>
|
||||
<span class="flex gap-1 shrink-0">
|
||||
@@ -990,12 +1006,15 @@
|
||||
{#each Object.entries(usage) as [key, value]}
|
||||
<div class="flex justify-between gap-4">
|
||||
<span class="text-gray-400 dark:text-gray-400">{formatUsageLabel(key)}</span>
|
||||
<span class="tabular-nums text-white dark:text-gray-200">{formatUsageValue(key, value)}</span>
|
||||
<span class="tabular-nums text-white dark:text-gray-200"
|
||||
>{formatUsageValue(key, value)}</span
|
||||
>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
<!-- Arrow -->
|
||||
<div class="absolute top-full left-1/2 -translate-x-1/2 w-0 h-0
|
||||
<div
|
||||
class="absolute top-full left-1/2 -translate-x-1/2 w-0 h-0
|
||||
border-l-[5px] border-l-transparent
|
||||
border-r-[5px] border-r-transparent
|
||||
border-t-[5px] border-t-gray-900 dark:border-t-gray-800"
|
||||
@@ -1008,5 +1027,3 @@
|
||||
{/if}
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
@@ -4,6 +4,7 @@ from cptr.routers.admin import router as admin_router
|
||||
from cptr.routers.auth import router as auth_router
|
||||
from cptr.routers.automations import router as automations_router
|
||||
from cptr.routers.bridge import router as bridge_router
|
||||
from cptr.routers.bridge import webhook_router
|
||||
from cptr.routers.chat import router as chat_router
|
||||
from cptr.routers.events import router as events_router
|
||||
from cptr.routers.files import router as files_router
|
||||
@@ -20,6 +21,7 @@ __all__ = [
|
||||
"auth_router",
|
||||
"automations_router",
|
||||
"bridge_router",
|
||||
"webhook_router",
|
||||
"chat_router",
|
||||
"events_router",
|
||||
"files_router",
|
||||
|
||||
@@ -236,8 +236,58 @@ async def verify_token(request: Request, body: TokenVerify):
|
||||
info = await dc_verify(body.token)
|
||||
return {"ok": True, "info": {"username": info.get("username"), "id": info.get("id")}}
|
||||
|
||||
elif body.platform == "slack":
|
||||
from cptr.utils.adapters.slack import verify_token as slack_verify
|
||||
info = await slack_verify(body.token)
|
||||
return {"ok": True, "info": {"username": info.get("username"), "id": info.get("id")}}
|
||||
|
||||
elif body.platform == "whatsapp":
|
||||
from cptr.utils.adapters.whatsapp import verify_token as wa_verify
|
||||
info = await wa_verify(body.token)
|
||||
return {"ok": True, "info": {"username": info.get("username"), "id": info.get("id")}}
|
||||
|
||||
elif body.platform == "signal":
|
||||
from cptr.utils.adapters.signal import verify_token as sig_verify
|
||||
info = await sig_verify(body.token)
|
||||
return {"ok": True, "info": {"username": info.get("username"), "id": info.get("id")}}
|
||||
|
||||
else:
|
||||
raise HTTPException(400, f"Unsupported platform: {body.platform}")
|
||||
|
||||
except Exception as e:
|
||||
return {"ok": False, "error": str(e)}
|
||||
|
||||
|
||||
# ── WhatsApp Webhook ─────────────────────────────────────────
|
||||
|
||||
|
||||
webhook_router = APIRouter(prefix="/api/webhooks", tags=["webhooks"])
|
||||
|
||||
|
||||
@webhook_router.get("/whatsapp/{bot_id}")
|
||||
async def whatsapp_webhook_verify(bot_id: str, request: Request):
|
||||
"""Meta webhook verification challenge (GET)."""
|
||||
mode = request.query_params.get("hub.mode")
|
||||
token = request.query_params.get("hub.verify_token")
|
||||
challenge = request.query_params.get("hub.challenge")
|
||||
|
||||
if mode == "subscribe" and challenge:
|
||||
# Accept any verify_token for now — user sets it in Meta dashboard
|
||||
from starlette.responses import PlainTextResponse
|
||||
return PlainTextResponse(challenge)
|
||||
raise HTTPException(403, "Verification failed")
|
||||
|
||||
|
||||
@webhook_router.post("/whatsapp/{bot_id}")
|
||||
async def whatsapp_webhook_inbound(bot_id: str, request: Request):
|
||||
"""Receive inbound WhatsApp messages via webhook."""
|
||||
from cptr.utils.bridge import bot_manager
|
||||
payload = await request.json()
|
||||
|
||||
adapter = bot_manager._adapters.get(bot_id)
|
||||
if adapter:
|
||||
from cptr.utils.adapters.whatsapp import WhatsAppAdapter
|
||||
if isinstance(adapter, WhatsAppAdapter):
|
||||
await adapter.handle_webhook(payload)
|
||||
|
||||
return {"status": "ok"}
|
||||
|
||||
@@ -0,0 +1,218 @@
|
||||
"""Signal adapter — uses signal-cli REST API bridge.
|
||||
|
||||
Requires a running signal-cli-rest-api container:
|
||||
docker run -p 8080:8080 bbernhard/signal-cli-rest-api
|
||||
|
||||
Token format: ``base_url|phone_number`` (pipe-separated).
|
||||
Example: ``http://localhost:8080|+1234567890``
|
||||
|
||||
Uses polling on GET /v1/receive/{number} for inbound messages
|
||||
and POST /v2/send for outbound messages.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
from typing import Optional
|
||||
from urllib.parse import quote
|
||||
|
||||
import httpx
|
||||
|
||||
from cptr.utils.bridge import BaseAdapter, MessageEvent, chunk_message
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
MAX_MESSAGE_LEN = 4096
|
||||
POLL_INTERVAL = 2.0 # seconds between receive polls
|
||||
RECONNECT_BASE_DELAY = 2.0
|
||||
RECONNECT_MAX_DELAY = 60.0
|
||||
|
||||
|
||||
def _parse_token(token: str) -> tuple[str, str]:
|
||||
"""Parse 'base_url|phone_number' format."""
|
||||
if "|" in token:
|
||||
base_url, phone = token.split("|", 1)
|
||||
return base_url.strip().rstrip("/"), phone.strip()
|
||||
raise ValueError("Signal token must be 'base_url|phone_number' (pipe-separated)")
|
||||
|
||||
|
||||
class SignalAdapter(BaseAdapter):
|
||||
"""Signal bot via signal-cli REST API bridge."""
|
||||
|
||||
platform = "signal"
|
||||
|
||||
def __init__(self, token: str) -> None:
|
||||
super().__init__()
|
||||
self._base_url, self._phone = _parse_token(token)
|
||||
self._http: Optional[httpx.AsyncClient] = None
|
||||
self._running = False
|
||||
self._poll_task: Optional[asyncio.Task] = None
|
||||
|
||||
# ── Lifecycle ──────────────────────────────────────────
|
||||
|
||||
async def connect(self) -> bool:
|
||||
self._http = httpx.AsyncClient(timeout=30)
|
||||
|
||||
# Verify by fetching account info
|
||||
try:
|
||||
resp = await self._http.get(f"{self._base_url}/v1/about")
|
||||
data = resp.json()
|
||||
# Also verify the number is registered
|
||||
resp2 = await self._http.get(
|
||||
f"{self._base_url}/v1/identities/{quote(self._phone, safe='')}"
|
||||
)
|
||||
if resp2.status_code == 404:
|
||||
raise ValueError(f"Phone number {self._phone} not registered with signal-cli")
|
||||
logger.info(
|
||||
"Signal adapter connected: %s (signal-cli %s)",
|
||||
self._phone, data.get("versions", {}).get("signal-cli", "?"),
|
||||
)
|
||||
except httpx.ConnectError:
|
||||
logger.error("Cannot connect to signal-cli REST API at %s", self._base_url)
|
||||
await self._http.aclose()
|
||||
self._http = None
|
||||
return False
|
||||
except Exception:
|
||||
logger.exception("Signal verification failed")
|
||||
await self._http.aclose()
|
||||
self._http = None
|
||||
return False
|
||||
|
||||
self._running = True
|
||||
self._poll_task = asyncio.create_task(self._poll_loop())
|
||||
return True
|
||||
|
||||
async def disconnect(self) -> None:
|
||||
self._running = False
|
||||
if self._poll_task and not self._poll_task.done():
|
||||
self._poll_task.cancel()
|
||||
try:
|
||||
await self._poll_task
|
||||
except (asyncio.CancelledError, Exception):
|
||||
pass
|
||||
if self._http:
|
||||
await self._http.aclose()
|
||||
self._http = None
|
||||
|
||||
# ── Sending ────────────────────────────────────────────
|
||||
|
||||
async def send(self, chat_id: str, text: str) -> str | None:
|
||||
if not self._http:
|
||||
return None
|
||||
chunks = chunk_message(text, MAX_MESSAGE_LEN)
|
||||
timestamp = None
|
||||
for chunk in chunks:
|
||||
resp = await self._http.post(
|
||||
f"{self._base_url}/v2/send",
|
||||
json={
|
||||
"message": chunk,
|
||||
"number": self._phone,
|
||||
"recipients": [chat_id],
|
||||
},
|
||||
)
|
||||
data = resp.json()
|
||||
if timestamp is None:
|
||||
# signal-cli returns timestamp as message identifier
|
||||
timestamp = str(data.get("timestamp", ""))
|
||||
return timestamp
|
||||
|
||||
async def edit(self, chat_id: str, message_id: str, text: str) -> None:
|
||||
"""Signal doesn't support message editing. No-op."""
|
||||
pass
|
||||
|
||||
async def send_typing(self, chat_id: str) -> None:
|
||||
"""Send typing indicator via signal-cli."""
|
||||
if not self._http:
|
||||
return
|
||||
try:
|
||||
await self._http.put(
|
||||
f"{self._base_url}/v1/typing-indicator/{quote(self._phone, safe='')}",
|
||||
json={"recipient": chat_id},
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# ── Polling ────────────────────────────────────────────
|
||||
|
||||
async def _poll_loop(self) -> None:
|
||||
delay = RECONNECT_BASE_DELAY
|
||||
while self._running:
|
||||
try:
|
||||
resp = await self._http.get(
|
||||
f"{self._base_url}/v1/receive/{quote(self._phone, safe='')}",
|
||||
timeout=30,
|
||||
)
|
||||
if resp.status_code == 200:
|
||||
messages = resp.json()
|
||||
for msg in messages:
|
||||
try:
|
||||
await self._process_message(msg)
|
||||
except Exception:
|
||||
logger.exception("Error processing Signal message")
|
||||
delay = RECONNECT_BASE_DELAY
|
||||
await asyncio.sleep(POLL_INTERVAL)
|
||||
|
||||
except asyncio.CancelledError:
|
||||
return
|
||||
except (httpx.ConnectError, httpx.ReadError, httpx.WriteError, OSError) as e:
|
||||
logger.warning("Signal poll network error (%s), retrying in %.0fs", type(e).__name__, delay)
|
||||
await asyncio.sleep(delay)
|
||||
delay = min(delay * 2, RECONNECT_MAX_DELAY)
|
||||
except Exception:
|
||||
logger.exception("Signal poll error, retrying in %.0fs", delay)
|
||||
await asyncio.sleep(delay)
|
||||
delay = min(delay * 2, RECONNECT_MAX_DELAY)
|
||||
|
||||
async def _process_message(self, msg: dict) -> None:
|
||||
envelope = msg.get("envelope", {})
|
||||
data_message = envelope.get("dataMessage")
|
||||
if not data_message:
|
||||
return
|
||||
|
||||
text = (data_message.get("message") or "").strip()
|
||||
if not text:
|
||||
return
|
||||
|
||||
source = envelope.get("source", "")
|
||||
source_name = envelope.get("sourceName") or source
|
||||
|
||||
# Use source number as chat_id (DM) or groupId for groups
|
||||
group_info = data_message.get("groupInfo")
|
||||
chat_id = group_info.get("groupId", "") if group_info else source
|
||||
|
||||
event = MessageEvent(
|
||||
platform="signal",
|
||||
chat_id=chat_id,
|
||||
sender_id=source,
|
||||
sender_name=source_name,
|
||||
text=text,
|
||||
)
|
||||
|
||||
if self.on_message:
|
||||
await self.on_message(event)
|
||||
|
||||
|
||||
async def verify_token(token: str) -> dict:
|
||||
"""Verify signal-cli REST API connection and phone number."""
|
||||
base_url, phone = _parse_token(token)
|
||||
|
||||
async with httpx.AsyncClient(timeout=10) as client:
|
||||
try:
|
||||
resp = await client.get(f"{base_url}/v1/about")
|
||||
data = resp.json()
|
||||
except httpx.ConnectError:
|
||||
raise ValueError(f"Cannot connect to signal-cli at {base_url}")
|
||||
|
||||
# Check phone number is registered
|
||||
resp2 = await client.get(
|
||||
f"{base_url}/v1/identities/{quote(phone, safe='')}"
|
||||
)
|
||||
if resp2.status_code == 404:
|
||||
raise ValueError(f"Phone {phone} not registered with signal-cli")
|
||||
|
||||
return {
|
||||
"username": phone,
|
||||
"id": phone,
|
||||
"version": data.get("versions", {}).get("signal-cli", "unknown"),
|
||||
}
|
||||
@@ -0,0 +1,249 @@
|
||||
"""Slack adapter — zero SDK dependencies.
|
||||
|
||||
Uses Socket Mode WebSocket for receiving events (no public URL needed)
|
||||
and the Slack Web API for sending messages via httpx.
|
||||
|
||||
Token format: ``xoxb-bottoken|xapp-apptoken`` (pipe-separated).
|
||||
The bot token is used for API calls, the app-level token for Socket Mode.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import logging
|
||||
from typing import Optional
|
||||
|
||||
import httpx
|
||||
|
||||
from cptr.utils.bridge import BaseAdapter, MessageEvent, chunk_message
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
API_BASE = "https://slack.com/api"
|
||||
MAX_MESSAGE_LEN = 4000 # Slack max is ~4000 for text blocks
|
||||
RECONNECT_BASE_DELAY = 2.0
|
||||
RECONNECT_MAX_DELAY = 60.0
|
||||
|
||||
|
||||
def _parse_token(token: str) -> tuple[str, str]:
|
||||
"""Parse 'bot_token|app_token' format."""
|
||||
if "|" in token:
|
||||
bot, app = token.split("|", 1)
|
||||
return bot.strip(), app.strip()
|
||||
raise ValueError("Slack token must be 'xoxb-...|xapp-...' (pipe-separated)")
|
||||
|
||||
|
||||
class SlackAdapter(BaseAdapter):
|
||||
"""Slack bot via Socket Mode WebSocket + Web API."""
|
||||
|
||||
platform = "slack"
|
||||
|
||||
def __init__(self, token: str) -> None:
|
||||
super().__init__()
|
||||
bot_token, app_token = _parse_token(token)
|
||||
self._bot_token = bot_token
|
||||
self._app_token = app_token
|
||||
self._http: Optional[httpx.AsyncClient] = None
|
||||
self._ws = None
|
||||
self._running = False
|
||||
self._bot_id: str = ""
|
||||
self._gateway_task: Optional[asyncio.Task] = None
|
||||
|
||||
# ── Lifecycle ──────────────────────────────────────────
|
||||
|
||||
async def connect(self) -> bool:
|
||||
self._http = httpx.AsyncClient(
|
||||
timeout=15,
|
||||
headers={"Authorization": f"Bearer {self._bot_token}"},
|
||||
)
|
||||
|
||||
try:
|
||||
resp = await self._http.post(f"{API_BASE}/auth.test")
|
||||
data = resp.json()
|
||||
if not data.get("ok"):
|
||||
raise ValueError(data.get("error", "auth.test failed"))
|
||||
self._bot_id = data.get("user_id", "")
|
||||
logger.info("Slack bot connected: %s (team: %s)", data.get("user", "?"), data.get("team", "?"))
|
||||
except Exception:
|
||||
logger.exception("Slack auth.test failed")
|
||||
await self._http.aclose()
|
||||
self._http = None
|
||||
return False
|
||||
|
||||
self._running = True
|
||||
self._gateway_task = asyncio.create_task(self._socket_mode_loop())
|
||||
return True
|
||||
|
||||
async def disconnect(self) -> None:
|
||||
self._running = False
|
||||
if self._gateway_task and not self._gateway_task.done():
|
||||
self._gateway_task.cancel()
|
||||
try:
|
||||
await self._gateway_task
|
||||
except (asyncio.CancelledError, Exception):
|
||||
pass
|
||||
if self._ws:
|
||||
try:
|
||||
await self._ws.close()
|
||||
except Exception:
|
||||
pass
|
||||
if self._http:
|
||||
await self._http.aclose()
|
||||
self._http = None
|
||||
|
||||
# ── Sending ────────────────────────────────────────────
|
||||
|
||||
async def send(self, chat_id: str, text: str) -> str | None:
|
||||
if not self._http:
|
||||
return None
|
||||
chunks = chunk_message(text, MAX_MESSAGE_LEN)
|
||||
msg_ts = None
|
||||
for chunk in chunks:
|
||||
resp = await self._http.post(
|
||||
f"{API_BASE}/chat.postMessage",
|
||||
json={"channel": chat_id, "text": chunk},
|
||||
)
|
||||
data = resp.json()
|
||||
if msg_ts is None and data.get("ok"):
|
||||
msg_ts = data.get("ts")
|
||||
return msg_ts
|
||||
|
||||
async def edit(self, chat_id: str, message_id: str, text: str) -> None:
|
||||
if not self._http:
|
||||
return
|
||||
await self._http.post(
|
||||
f"{API_BASE}/chat.update",
|
||||
json={
|
||||
"channel": chat_id,
|
||||
"ts": message_id,
|
||||
"text": text[:MAX_MESSAGE_LEN],
|
||||
},
|
||||
)
|
||||
|
||||
async def send_typing(self, chat_id: str) -> None:
|
||||
# Slack doesn't have a direct typing indicator API for bots
|
||||
pass
|
||||
|
||||
# ── Socket Mode ────────────────────────────────────────
|
||||
|
||||
async def _socket_mode_loop(self) -> None:
|
||||
delay = RECONNECT_BASE_DELAY
|
||||
while self._running:
|
||||
try:
|
||||
await self._run_socket_session()
|
||||
delay = RECONNECT_BASE_DELAY
|
||||
except asyncio.CancelledError:
|
||||
return
|
||||
except Exception as e:
|
||||
logger.warning("Slack Socket Mode error (%s), reconnecting in %.0fs", type(e).__name__, delay)
|
||||
await asyncio.sleep(delay)
|
||||
delay = min(delay * 2, RECONNECT_MAX_DELAY)
|
||||
|
||||
async def _run_socket_session(self) -> None:
|
||||
try:
|
||||
import websockets
|
||||
except ImportError:
|
||||
logger.error("Slack adapter requires 'websockets' package. Install: pip install websockets")
|
||||
self._running = False
|
||||
return
|
||||
|
||||
# Get WebSocket URL via apps.connections.open
|
||||
async with httpx.AsyncClient(timeout=10) as client:
|
||||
resp = await client.post(
|
||||
f"{API_BASE}/apps.connections.open",
|
||||
headers={"Authorization": f"Bearer {self._app_token}"},
|
||||
)
|
||||
data = resp.json()
|
||||
if not data.get("ok"):
|
||||
raise RuntimeError(f"apps.connections.open failed: {data.get('error')}")
|
||||
ws_url = data["url"]
|
||||
|
||||
async with websockets.connect(ws_url) as ws:
|
||||
self._ws = ws
|
||||
|
||||
async for raw in ws:
|
||||
if not self._running:
|
||||
return
|
||||
|
||||
payload = json.loads(raw)
|
||||
msg_type = payload.get("type")
|
||||
|
||||
# Acknowledge all envelopes
|
||||
envelope_id = payload.get("envelope_id")
|
||||
if envelope_id:
|
||||
await ws.send(json.dumps({"envelope_id": envelope_id}))
|
||||
|
||||
if msg_type == "disconnect":
|
||||
logger.info("Slack Socket Mode disconnect requested")
|
||||
return
|
||||
|
||||
if msg_type == "events_api":
|
||||
event = payload.get("payload", {}).get("event", {})
|
||||
await self._handle_event(event)
|
||||
|
||||
async def _handle_event(self, event: dict) -> None:
|
||||
if event.get("type") != "message":
|
||||
return
|
||||
# Ignore bot messages, subtypes (edits, joins, etc.)
|
||||
if event.get("bot_id") or event.get("subtype"):
|
||||
return
|
||||
if event.get("user") == self._bot_id:
|
||||
return
|
||||
|
||||
text = (event.get("text") or "").strip()
|
||||
if not text:
|
||||
return
|
||||
|
||||
# Resolve display name
|
||||
user_id = event.get("user", "")
|
||||
sender_name = await self._resolve_name(user_id)
|
||||
|
||||
msg_event = MessageEvent(
|
||||
platform="slack",
|
||||
chat_id=event.get("channel", ""),
|
||||
sender_id=user_id,
|
||||
sender_name=sender_name,
|
||||
text=text,
|
||||
)
|
||||
|
||||
if self.on_message:
|
||||
await self.on_message(msg_event)
|
||||
|
||||
async def _resolve_name(self, user_id: str) -> str:
|
||||
if not self._http or not user_id:
|
||||
return "User"
|
||||
try:
|
||||
resp = await self._http.get(f"{API_BASE}/users.info", params={"user": user_id})
|
||||
data = resp.json()
|
||||
if data.get("ok"):
|
||||
user = data.get("user", {})
|
||||
return user.get("real_name") or user.get("name") or "User"
|
||||
except Exception:
|
||||
pass
|
||||
return "User"
|
||||
|
||||
|
||||
async def verify_token(token: str) -> dict:
|
||||
"""Verify a Slack bot token by calling auth.test."""
|
||||
bot_token, app_token = _parse_token(token)
|
||||
|
||||
async with httpx.AsyncClient(timeout=10) as client:
|
||||
resp = await client.post(
|
||||
f"{API_BASE}/auth.test",
|
||||
headers={"Authorization": f"Bearer {bot_token}"},
|
||||
)
|
||||
data = resp.json()
|
||||
if not data.get("ok"):
|
||||
raise ValueError(data.get("error", "Invalid Slack token"))
|
||||
|
||||
# Also verify app token
|
||||
resp2 = await client.post(
|
||||
f"{API_BASE}/apps.connections.open",
|
||||
headers={"Authorization": f"Bearer {app_token}"},
|
||||
)
|
||||
data2 = resp2.json()
|
||||
if not data2.get("ok"):
|
||||
raise ValueError(f"App token error: {data2.get('error', 'Invalid app token')}")
|
||||
|
||||
return {"username": data.get("user"), "id": data.get("user_id"), "team": data.get("team")}
|
||||
@@ -0,0 +1,203 @@
|
||||
"""WhatsApp adapter — zero SDK dependencies.
|
||||
|
||||
Uses Meta's WhatsApp Cloud API via httpx:
|
||||
- Webhook endpoint for inbound messages (registered via FastAPI)
|
||||
- REST POST to /messages for sending
|
||||
- No native streaming; uses edit-via-context approach
|
||||
|
||||
Token format: ``access_token|phone_number_id`` (pipe-separated).
|
||||
|
||||
Requires a publicly accessible URL for webhook verification.
|
||||
Configure the webhook URL in Meta's WhatsApp dashboard as:
|
||||
https://your-domain/api/webhooks/whatsapp/{bot_id}
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
from typing import Optional
|
||||
|
||||
import httpx
|
||||
|
||||
from cptr.utils.bridge import BaseAdapter, MessageEvent, chunk_message
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
API_BASE = "https://graph.facebook.com/v21.0"
|
||||
MAX_MESSAGE_LEN = 4096
|
||||
|
||||
|
||||
def _parse_token(token: str) -> tuple[str, str]:
|
||||
"""Parse 'access_token|phone_number_id' format."""
|
||||
if "|" in token:
|
||||
access_token, phone_number_id = token.split("|", 1)
|
||||
return access_token.strip(), phone_number_id.strip()
|
||||
raise ValueError("WhatsApp token must be 'access_token|phone_number_id' (pipe-separated)")
|
||||
|
||||
|
||||
class WhatsAppAdapter(BaseAdapter):
|
||||
"""WhatsApp bot via Cloud API + webhook inbound."""
|
||||
|
||||
platform = "whatsapp"
|
||||
|
||||
def __init__(self, token: str, bot_id: str = "") -> None:
|
||||
super().__init__()
|
||||
self._access_token, self._phone_number_id = _parse_token(token)
|
||||
self._bot_id = bot_id
|
||||
self._http: Optional[httpx.AsyncClient] = None
|
||||
self._running = False
|
||||
self._message_queue: asyncio.Queue = asyncio.Queue()
|
||||
self._process_task: Optional[asyncio.Task] = None
|
||||
|
||||
# ── Lifecycle ──────────────────────────────────────────
|
||||
|
||||
async def connect(self) -> bool:
|
||||
self._http = httpx.AsyncClient(
|
||||
timeout=15,
|
||||
headers={"Authorization": f"Bearer {self._access_token}"},
|
||||
)
|
||||
|
||||
# Verify token by fetching phone number info
|
||||
try:
|
||||
resp = await self._http.get(f"{API_BASE}/{self._phone_number_id}")
|
||||
data = resp.json()
|
||||
if "error" in data:
|
||||
raise ValueError(data["error"].get("message", "Invalid token"))
|
||||
display_name = data.get("verified_name") or data.get("display_phone_number", "?")
|
||||
logger.info("WhatsApp bot connected: %s (%s)", display_name, self._phone_number_id)
|
||||
except Exception:
|
||||
logger.exception("WhatsApp token verification failed")
|
||||
await self._http.aclose()
|
||||
self._http = None
|
||||
return False
|
||||
|
||||
self._running = True
|
||||
self._process_task = asyncio.create_task(self._process_loop())
|
||||
return True
|
||||
|
||||
async def disconnect(self) -> None:
|
||||
self._running = False
|
||||
if self._process_task and not self._process_task.done():
|
||||
self._process_task.cancel()
|
||||
try:
|
||||
await self._process_task
|
||||
except (asyncio.CancelledError, Exception):
|
||||
pass
|
||||
if self._http:
|
||||
await self._http.aclose()
|
||||
self._http = None
|
||||
|
||||
# ── Webhook ingestion ──────────────────────────────────
|
||||
|
||||
async def handle_webhook(self, payload: dict) -> None:
|
||||
"""Called by the webhook route to push inbound messages."""
|
||||
for entry in payload.get("entry", []):
|
||||
for change in entry.get("changes", []):
|
||||
value = change.get("value", {})
|
||||
for message in value.get("messages", []):
|
||||
if message.get("type") != "text":
|
||||
continue
|
||||
|
||||
sender = message.get("from", "")
|
||||
text = message.get("text", {}).get("body", "").strip()
|
||||
if not text:
|
||||
continue
|
||||
|
||||
# Resolve sender name from contacts
|
||||
contacts = value.get("contacts", [])
|
||||
sender_name = "User"
|
||||
for c in contacts:
|
||||
if c.get("wa_id") == sender:
|
||||
profile = c.get("profile", {})
|
||||
sender_name = profile.get("name", sender)
|
||||
break
|
||||
|
||||
event = MessageEvent(
|
||||
platform="whatsapp",
|
||||
chat_id=sender, # WhatsApp uses phone number as chat ID
|
||||
sender_id=sender,
|
||||
sender_name=sender_name,
|
||||
text=text,
|
||||
)
|
||||
await self._message_queue.put(event)
|
||||
|
||||
async def _process_loop(self) -> None:
|
||||
"""Process inbound messages from the webhook queue."""
|
||||
while self._running:
|
||||
try:
|
||||
event = await asyncio.wait_for(self._message_queue.get(), timeout=5.0)
|
||||
if self.on_message:
|
||||
await self.on_message(event)
|
||||
except asyncio.TimeoutError:
|
||||
continue
|
||||
except asyncio.CancelledError:
|
||||
return
|
||||
except Exception:
|
||||
logger.exception("Error processing WhatsApp message")
|
||||
|
||||
# ── Sending ────────────────────────────────────────────
|
||||
|
||||
async def send(self, chat_id: str, text: str) -> str | None:
|
||||
if not self._http:
|
||||
return None
|
||||
chunks = chunk_message(text, MAX_MESSAGE_LEN)
|
||||
msg_id = None
|
||||
for chunk in chunks:
|
||||
resp = await self._http.post(
|
||||
f"{API_BASE}/{self._phone_number_id}/messages",
|
||||
json={
|
||||
"messaging_product": "whatsapp",
|
||||
"to": chat_id,
|
||||
"type": "text",
|
||||
"text": {"body": chunk},
|
||||
},
|
||||
)
|
||||
data = resp.json()
|
||||
if msg_id is None:
|
||||
messages = data.get("messages", [])
|
||||
if messages:
|
||||
msg_id = messages[0].get("id")
|
||||
return msg_id
|
||||
|
||||
async def edit(self, chat_id: str, message_id: str, text: str) -> None:
|
||||
"""WhatsApp doesn't support message editing. Send a new message instead."""
|
||||
# WhatsApp has no edit API — for streaming we just send new messages
|
||||
# The stream loop will handle this gracefully
|
||||
pass
|
||||
|
||||
async def send_typing(self, chat_id: str) -> None:
|
||||
"""Send a 'typing' indicator (read receipt + typing)."""
|
||||
if not self._http:
|
||||
return
|
||||
try:
|
||||
# Mark as read (closest to typing indicator)
|
||||
await self._http.post(
|
||||
f"{API_BASE}/{self._phone_number_id}/messages",
|
||||
json={
|
||||
"messaging_product": "whatsapp",
|
||||
"status": "read",
|
||||
"message_id": "placeholder", # Not ideal but API requires it
|
||||
},
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
async def verify_token(token: str) -> dict:
|
||||
"""Verify WhatsApp Cloud API credentials."""
|
||||
access_token, phone_number_id = _parse_token(token)
|
||||
|
||||
async with httpx.AsyncClient(timeout=10) as client:
|
||||
resp = await client.get(
|
||||
f"{API_BASE}/{phone_number_id}",
|
||||
headers={"Authorization": f"Bearer {access_token}"},
|
||||
)
|
||||
data = resp.json()
|
||||
if "error" in data:
|
||||
raise ValueError(data["error"].get("message", "Invalid credentials"))
|
||||
|
||||
return {
|
||||
"username": data.get("verified_name") or data.get("display_phone_number"),
|
||||
"id": phone_number_id,
|
||||
}
|
||||
@@ -304,6 +304,18 @@ class BotManager:
|
||||
from cptr.utils.adapters.discord import DiscordAdapter
|
||||
return DiscordAdapter(token=token)
|
||||
|
||||
if bot["platform"] == "slack":
|
||||
from cptr.utils.adapters.slack import SlackAdapter
|
||||
return SlackAdapter(token=token)
|
||||
|
||||
if bot["platform"] == "whatsapp":
|
||||
from cptr.utils.adapters.whatsapp import WhatsAppAdapter
|
||||
return WhatsAppAdapter(token=token, bot_id=bot["id"])
|
||||
|
||||
if bot["platform"] == "signal":
|
||||
from cptr.utils.adapters.signal import SignalAdapter
|
||||
return SignalAdapter(token=token)
|
||||
|
||||
return None
|
||||
|
||||
# ── Message handling ───────────────────────────────────
|
||||
|
||||
Reference in New Issue
Block a user