Files
ragflow/api/channels/feishu/channel.py
Kevin Hu b5a426e6e0 Feat: chat channels — connect assistants to external messaging bots (#15850)
### What problem does this PR solve?

#15844

Adds a **Chat channels** capability so a RAGFlow assistant (Dialog) can
be exposed as a bot on external messaging platforms (Feishu/Lark,
Discord, Telegram, Slack, WeCom, LINE, etc.). An admin configures a bot
in the UI, connects it to an assistant, and inbound messages are
answered from that assistant's knowledge base — replies are delivered
back on the channel.

**Feishu/Lark is implemented and tested end-to-end.** Discord, Telegram,
LINE, and WeCom are scaffolded against the same interface; the remaining
listed channels are tracked as follow-ups.

### Design

**Backend**
- New `chat_channel` table (`tenant_id`, `name`, `channel`, `config`
JSON holding `{credential: {...}}`, `dialog_id`, `status`) +
`ChatChannelService` and RESTful CRUD under `/api/v1/chat_channels`.
- Channel framework under `api/channels/`: a `core` registry +
per-channel packages that self-register a builder and implement a common
`Channel` interface (`start`/`stop`/`send` + inbound normalization) over
`IncomingMessage`/`OutgoingMessage`.
- Embedded **reconcile loop** in `ragflow_server`
(`api/channels/bootstrap.py`): loads enabled bots, and
starts/stops/restarts them as rows change (no server restart needed).
Inbound messages run the connected dialog via the non-streaming
completion path, keeping per-end-user conversation history.
- Missing optional channel SDKs degrade gracefully (channel skipped with
a warning; others unaffected). Channel-level errors are logged, not
crashed.
- Feishu's WebSocket client runs in a dedicated thread with its own
event loop to avoid cross-loop/contextvars conflicts with the channel
runtime.

**Frontend**
- **Settings → Chat channels** panel: available-channels grid +
configured-bots list with add/edit/delete and a **Connect assistant**
popup that binds a bot to a dialog.
- Brand icons via simple-icons / reused shared data-source assets, with
colored fallbacks for brands not available.
- Route, sidebar entry, i18n (en/zh), and a top-nav segment-boundary fix
so the settings page no longer highlights the Chat tab.

### Type of change

- [x] New Feature (non-breaking change which adds functionality)

### Notes
- DB: new `chat_channel` table is auto-created; `chat_channel.dialog_id`
is also covered by a `migrate_db` `alter_db_add_column` for existing
installs.
- Channel SDKs (`lark-oapi`, `discord.py`, `python-telegram-bot`,
`line-bot-sdk`, `wechatpy`, `aiohttp`) added to dependencies.
- Screenshots / per-channel credential docs to follow.

<img width="1338" height="1290" alt="Image"
src="https://github.com/user-attachments/assets/042cb2f9-0dad-4e6a-bcf7-43ced4bbd704"
/>

<img width="1344" height="738" alt="Image"
src="https://github.com/user-attachments/assets/373cd08e-ec40-4c67-9c51-4d948b1ba617"
/>

<img width="672" height="887" alt="Image"
src="https://github.com/user-attachments/assets/5a34953f-a9a3-4c1e-869e-5eff0dc64c84"
/>

---------
2026-06-12 18:21:30 +08:00

211 lines
7.3 KiB
Python

from __future__ import annotations
import asyncio
import json
import logging
import threading
from dataclasses import dataclass
from typing import Optional
import lark_oapi as lark
from lark_oapi.api.im.v1 import (
CreateMessageRequest,
CreateMessageRequestBody,
P2ImMessageReceiveV1,
ReplyMessageRequest,
ReplyMessageRequestBody,
)
from ..core.base import Channel, IncomingMessage, OutgoingMessage
from ..core.registry import register_channel
LOGGER = logging.getLogger(__name__)
@dataclass
class FeishuAccount:
account_id: str
app_id: str
app_secret: str
domain: str = "feishu" # "feishu" or "lark"
def _lark_domain(domain: str) -> str:
return lark.FEISHU_DOMAIN if domain != "lark" else lark.LARK_DOMAIN
class FeishuChannel(Channel):
channel_id = "feishu"
def __init__(self, account: FeishuAccount) -> None:
super().__init__()
self.account = account
self.account_id = account.account_id
self._loop: Optional[asyncio.AbstractEventLoop] = None
self._ws_client = None
self._ws_thread: Optional[threading.Thread] = None
self._rest = (
lark.Client.builder()
.app_id(account.app_id)
.app_secret(account.app_secret)
.domain(_lark_domain(account.domain))
.log_level(lark.LogLevel.DEBUG)
.build()
)
async def start(self) -> None:
# The channel loop is the cross-thread dispatch target for inbound events.
self._loop = asyncio.get_running_loop()
LOGGER.info("[feishu:%s] starting WebSocket client", self.account_id)
self._ws_thread = threading.Thread(
target=self._run_ws,
name=f"feishu-ws-{self.account_id}",
daemon=True,
)
self._ws_thread.start()
def _run_ws(self) -> None:
# Everything lark touches must be created and run on THIS thread with its
# own event loop. lark captures the running loop when the handler/client
# are built and when start() runs; building them on the channel daemon
# loop made lark schedule its WebSocket onto that loop, colliding with
# run_channels() ("Leaving task ... does not match" / "cannot enter
# context: already entered"). A dedicated isolated loop avoids that.
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
try:
handler = (
lark.EventDispatcherHandler.builder("", "")
.register_p2_im_message_receive_v1(self._on_message_receive)
.build()
)
self._ws_client = lark.ws.Client(
self.account.app_id,
self.account.app_secret,
domain=_lark_domain(self.account.domain),
event_handler=handler,
log_level=lark.LogLevel.DEBUG,
)
# Blocks, running lark's own connect/reconnect loop on this thread.
self._ws_client.start()
except Exception:
LOGGER.error("[feishu:%s] WebSocket client crashed", self.account_id, exc_info=True)
finally:
try:
loop.close()
except Exception:
pass
async def stop(self) -> None:
# lark's ws client exposes no clean public stop; disconnect best-effort.
client = self._ws_client
if client is not None:
for attr in ("stop", "_disconnect", "disconnect"):
fn = getattr(client, attr, None)
if callable(fn):
try:
fn()
except Exception:
LOGGER.error("[feishu:%s] ws stop error", self.account_id, exc_info=True)
break
self._ws_client = None
self._ws_thread = None
async def send(self, message: OutgoingMessage) -> None:
content = json.dumps({"text": message.text}, ensure_ascii=False)
if message.reply_to_message_id:
req = (
ReplyMessageRequest.builder()
.message_id(message.reply_to_message_id)
.request_body(
ReplyMessageRequestBody.builder()
.content(content)
.msg_type("text")
.build()
)
.build()
)
resp = await asyncio.to_thread(self._rest.im.v1.message.reply, req)
else:
req = (
CreateMessageRequest.builder()
.receive_id_type("chat_id")
.request_body(
CreateMessageRequestBody.builder()
.receive_id(message.chat_id)
.content(content)
.msg_type("text")
.build()
)
.build()
)
resp = await asyncio.to_thread(self._rest.im.v1.message.create, req)
if not resp.success():
LOGGER.error(
"[feishu:%s] send failed: code=%s msg=%s",
self.account_id,
resp.code,
resp.msg,
)
def _on_message_receive(self, data: P2ImMessageReceiveV1) -> None:
# Runs on the lark-oapi WS thread; bounce into asyncio for downstream handlers.
try:
incoming = self._normalize(data)
if self._loop and not self._loop.is_closed():
future = asyncio.run_coroutine_threadsafe(self._dispatch(incoming), self._loop)
future.add_done_callback(self._log_dispatch_result)
except Exception:
LOGGER.error("[feishu:%s] inbound message handling error", self.account_id, exc_info=True)
def _log_dispatch_result(self, future) -> None:
try:
future.result()
except Exception:
LOGGER.error("[feishu:%s] dispatch error", self.account_id, exc_info=True)
def _normalize(self, data: P2ImMessageReceiveV1) -> IncomingMessage:
event = data.event
msg = event.message
sender = event.sender
text = ""
if msg.content:
try:
payload = json.loads(msg.content)
text = payload.get("text", "") if isinstance(payload, dict) else ""
except (json.JSONDecodeError, TypeError):
text = msg.content
sender_id = ""
if sender and getattr(sender, "sender_id", None):
sender_id = getattr(sender.sender_id, "open_id", "") or ""
return IncomingMessage(
channel=self.channel_id,
account_id=self.account_id,
chat_id=msg.chat_id or "",
chat_type=msg.chat_type or "",
message_id=msg.message_id or "",
sender_id=sender_id,
text=text,
raw=data,
)
def _build(account_id: str, cfg: dict) -> Channel:
app_id = cfg.get("app_id")
app_secret = cfg.get("app_secret")
if not app_id or not app_secret:
raise ValueError(
f"feishu account '{account_id}' is missing app_id or app_secret"
)
return FeishuChannel(
FeishuAccount(
account_id=account_id,
app_id=str(app_id),
app_secret=str(app_secret),
domain=str(cfg.get("domain", "feishu")),
)
)
register_channel("feishu", _build)