Skip to content

Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.

feat(bot):enhance Feishu mentions and name display (#1534)

yeshion233334d34025c7664
diff --git a/bot/demo/werewolf/werewolfUI.html b/bot/demo/werewolf/werewolfUI.html
index aec683199..46fd56149 100644
--- a/bot/demo/werewolf/werewolfUI.html
+++ b/bot/demo/werewolf/werewolfUI.html
@@ -1884,6 +1884,7 @@
conversations: null,
botSessions: null,
endOverlayConfirmed: false,
+ endOverlaySource: null,
pendingGameMode: null,
preferredGameMode: localStorage.getItem('ww_preferred_game_mode') || 'all_agents',
};
@@ -2273,17 +2274,30 @@
if (chatAliveText) chatAliveText.textContent = `${alive}/${(players || []).length} alive`;
}
- function updateEndOverlay(info, statusData) {
+ function setEndOverlay({ visible, winnerText = '', statusText = '', source = null }) {
const overlay = document.getElementById('endOverlay');
const winner = document.getElementById('endWinner');
const status = document.getElementById('endStatus');
- const gameEnded = Boolean(statusData && statusData.game_ended);
- if (gameEnded && info.winner && !uiState.endOverlayConfirmed) {
+ if (!overlay || !winner || !status) return;
+ if (visible) {
+ uiState.endOverlaySource = source;
overlay.classList.add('show');
- winner.textContent = '胜利方:' + info.winner;
- } else if (!gameEnded || !info.winner) {
+ winner.textContent = '胜利方:' + (winnerText || '-');
+ status.textContent = statusText || '';
+ } else {
+ if (source && uiState.endOverlaySource && uiState.endOverlaySource !== source) return;
overlay.classList.remove('show');
status.textContent = '';
+ if (!source || uiState.endOverlaySource === source) uiState.endOverlaySource = null;
+ }
+ }
+
+ function updateEndOverlay(info, statusData) {
+ const gameEnded = Boolean(statusData && statusData.game_ended);
+ if (gameEnded && info.winner && !uiState.endOverlayConfirmed) {
+ setEndOverlay({ visible: true, winnerText: info.winner, source: 'live' });
+ } else if (!gameEnded || !info.winner) {
+ setEndOverlay({ visible: false, source: 'live' });
uiState.endOverlayConfirmed = false;
}
}
@@ -2701,21 +2715,19 @@
// Calculate current game score
const winner = info.winner || '';
- // Use the same correct logic as saveGameToLeaderboard
+ // Use the same server-aligned winner interpretation for current-game display
const isWolfWin = winner.includes('狼人胜利') && !winner.includes('死亡') && !winner.includes('好人');
const dead = info.dead || new Set();
if (!isHumanMode && winner) {
if ((isWolfWin && isWolf) || (!isWolfWin && !isWolf)) {
- currentScore += 3;
+ currentScore += 2;
winStatus = '胜利';
} else {
winStatus = '失败';
}
if (!dead.has(i)) {
currentScore += 1;
- } else {
- currentScore -= 1;
}
} else if (winner) {
winStatus = '不计分';
@@ -3766,11 +3778,13 @@ function bindNav() {
// 确认按钮 - 关闭游戏结束界面
const doConfirm = () => {
- uiState.endOverlayConfirmed = true;
- const overlay = document.getElementById('endOverlay');
- if (overlay) {
- overlay.classList.remove('show');
+ if (uiState.endOverlaySource === 'replay') {
+ replayState.endOverlayConfirmed = true;
+ setEndOverlay({ visible: false, source: 'replay' });
+ return;
}
+ uiState.endOverlayConfirmed = true;
+ setEndOverlay({ visible: false, source: 'live' });
};
// 重新开始游戏 - 重新初始化
@@ -4060,98 +4074,6 @@ function bindNav() {
}
- // Track saved sessions to prevent duplicate saves - use localStorage for persistence
- function getSavedSessionIds() {
- try {
- const saved = localStorage.getItem('leaderboard_saved_sessions');
- return saved ? new Set(JSON.parse(saved)) : new Set();
- } catch {
- return new Set();
- }
- }
-
- function addSavedSessionId(sessionId) {
- try {
- const saved = getSavedSessionIds();
- saved.add(sessionId);
- localStorage.setItem('leaderboard_saved_sessions', JSON.stringify(Array.from(saved)));
- } catch {
- // Ignore storage errors
- }
- }
-
- async function saveGameToLeaderboard(data, info, status) {
- if (!info.winner) return;
- if (status && status.game_mode === 'human_player') return;
-
- const sessionId = status ? status.session_id : '';
- // Prevent saving the same session multiple times
- const savedSessionIds = getSavedSessionIds();
- if (sessionId && savedSessionIds.has(sessionId)) {
- console.log('Session already saved to leaderboard:', sessionId);
- return;
- }
-
- const players = data.players || [];
- // Fix: Check for wolf win correctly
- const winnerText = info.winner || '';
- // Only judge as wolf win if explicitly says "狼人胜利"
- const isWolfWin = winnerText.includes('狼人胜利') && !winnerText.includes('死亡') && !winnerText.includes('好人');
- // Judge as good win if says "好人胜利" or "狼人死亡"
- const isGoodWin = winnerText.includes('好人胜利') || winnerText.includes('平民胜利') || (winnerText.includes('狼人') && winnerText.includes('死亡'));
- const dead = info.dead || new Set();
-
- const gamePlayers = players.map((p, i) => {
- const role = String(p.role || '');
- // Support both English and Chinese role names
- const isWolf =
- role === 'Werewolf' || role === 'WhiteWolfKing' || role === 'WolfCub' || role === 'WolfBeauty' ||
- role === '狼人' || role === '白狼王' || role === '狼美人' || role === '狼崽';
- const won = (isWolfWin && isWolf) || (!isWolfWin && !isWolf);
- const isDead = dead.has(i);
-
- let score = 0;
- if (won) score += 3;
- if (!isDead) score += 1;
- else score -= 1;
-
- return {
- id: p.id || `player_${i + 1}`,
- role: role,
- won: won,
- dead: isDead,
- score: score
- };
- });
-
- const gameData = {
- session_id: status ? status.session_id : '',
- game_mode: status ? status.game_mode : '',
- winner: info.winner,
- players: gamePlayers
- };
-
- try {
- const res = await fetch('/api/leaderboard/save', {
- method: 'POST',
- headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify(gameData)
- });
- if (res.ok) {
- console.log('Game saved to leaderboard');
- // Mark session as saved
- if (sessionId) {
- addSavedSessionId(sessionId);
- }
- // Clear leaderboard cache to force reload on next render
- cachedLeaderboard = null;
- cachedLeaderboardTs = 0;
- }
- } catch (e) {
- console.error('Failed to save to leaderboard:', e);
- }
- }
-
async function refreshFromHttp() {
if (uiState.loading) return;
uiState.loading = true;
@@ -4240,10 +4162,10 @@ function bindNav() {
// Ignore chart rendering errors
}
- // Check if game just ended and save to leaderboard
if (statusData.game_ended && info.winner && !uiState.lastGameWinner) {
uiState.lastGameWinner = info.winner;
- saveGameToLeaderboard(data, info, statusData);
+ cachedLeaderboard = null;
+ cachedLeaderboardTs = 0;
} else if (!statusData.game_ended || !info.winner) {
uiState.lastGameWinner = null;
}
@@ -4289,7 +4211,8 @@ function bindNav() {
seatPlayerMap: {},
players: [],
baseInfo: null,
- gameRecord: ''
+ gameRecord: '',
+ endOverlayConfirmed: false
};
function parseReplayTimestamp(sessionId, timeText, fallbackIndex) {
@@ -4456,6 +4379,16 @@ function bindNav() {
}));
}
+ function updateReplayEndOverlay() {
+ const isAtEnd = replayState.events.length > 0 && replayState.currentIndex === replayState.events.length - 1;
+ const winner = String(replayState.baseInfo?.winner || '').trim();
+ if (isAtEnd && winner && !replayState.endOverlayConfirmed) {
+ setEndOverlay({ visible: true, winnerText: winner, source: 'replay' });
+ } else {
+ setEndOverlay({ visible: false, source: 'replay' });
+ }
+ }
+
function withReplayDomBindings(run) {
const bindings = [
['arena', 'replayArena'],
@@ -4554,6 +4487,8 @@ function bindNav() {
replayState.players = replayPlayers;
replayState.gameRecord = String(replayArchive?.game_record || '');
replayState.baseInfo = normalizeReplayBaseInfo(replayArchive?.base_info);
+ replayState.endOverlayConfirmed = false;
+ setEndOverlay({ visible: false, source: 'replay' });
replayState.isPlaying = false;
if (replayState.playInterval) {
clearInterval(replayState.playInterval);
@@ -4629,8 +4564,12 @@ function bindNav() {
function goToReplayIndex(index) {
if (index < -1 || index >= replayState.events.length) return;
replayState.currentIndex = index;
+ if (index < replayState.events.length - 1) {
+ replayState.endOverlayConfirmed = false;
+ }
renderReplayView(index);
updateReplayProgress();
+ updateReplayEndOverlay();
}
function toggleReplayPlay() {
@@ -4641,6 +4580,8 @@ function bindNav() {
if (replayState.isPlaying) {
if (replayState.currentIndex >= replayState.events.length - 1) {
replayState.currentIndex = -1;
+ replayState.endOverlayConfirmed = false;
+ setEndOverlay({ visible: false, source: 'replay' });
}
const speedSelect = document.getElementById('replaySpeed');
diff --git a/bot/demo/werewolf/werewolf_server.py b/bot/demo/werewolf/werewolf_server.py
index 4ec7a3f0d..b975c59c9 100644
--- a/bot/demo/werewolf/werewolf_server.py
+++ b/bot/demo/werewolf/werewolf_server.py
@@ -185,7 +185,7 @@ def extract_content_without_mentions(content: str) -> str:
def is_waiting_like_reply(content: str) -> bool:
"""Check whether god reply is an initialization/paused-state reply."""
text = str(content or "")
- waiting_markers = ["初始化完成", "等待开始", "等待指令", "等待继续"]
+ waiting_markers = ["初始化完成", "初始化已完成", "等待开始", "等待指令", "等待继续",'等待"开始"指令']
return any(marker in text for marker in waiting_markers)
@@ -267,6 +267,136 @@ def is_game_ended_from_record(game_record_path: Path) -> tuple[bool, str]:
return False, None
+def normalize_leaderboard_game_result(game_result: Any) -> str:
+ result = str(game_result or "").strip()
+ if not result:
+ return ""
+ if "狼人胜利" in result:
+ return "狼人胜利"
+ if "好人胜利" in result or "平民胜利" in result or ("狼人" in result and "死亡" in result):
+ return "好人胜利"
+ return result
+
+
+def is_wolf_role_for_leaderboard(role: Any) -> bool:
+ role_str = str(role or "").strip()
+ return role_str in {"Werewolf", "WhiteWolfKing", "WolfCub", "WolfBeauty", "狼人", "白狼王", "狼美人", "狼崽"}
+
+
+def is_dead_status_for_leaderboard(status: Any) -> bool:
+ status_str = str(status or "")
+ return any(token in status_str for token in ("死亡", "出局", "淘汰"))
+
+
+def build_leaderboard_game_from_record(parsed_record: Dict[str, Any], *, session_id: str, game_mode: str) -> Dict[str, Any]:
+ winner = normalize_leaderboard_game_result(parsed_record.get("game_result"))
+ players = []
+ for player in parsed_record.get("players", []):
+ role = player.get("role", "")
+ dead = is_dead_status_for_leaderboard(player.get("status", ""))
+ won = (winner == "狼人胜利" and is_wolf_role_for_leaderboard(role)) or (winner == "好人胜利" and not is_wolf_role_for_leaderboard(role))
+ score = (2 if won else 0) + (1 if not dead else 0)
+ players.append({
+ "id": player.get("id", ""),
+ "role": role,
+ "won": won,
+ "dead": dead,
+ "score": score,
+ })
+
+ return {
+ "session_id": session_id,
+ "game_mode": game_mode,
+ "winner": winner,
+ "players": players,
+ }
+
+
+def get_leaderboard_path(storage_path: Path) -> Path:
+ leaderboard_dir = storage_path / "bot" / "workspace" / "werewolf"
+ leaderboard_dir.mkdir(parents=True, exist_ok=True)
+ return leaderboard_dir / "LEADERBOARD.json"
+
+
+def load_leaderboard(storage_path: Path) -> Dict[str, Any]:
+ leaderboard_path = get_leaderboard_path(storage_path)
+ if leaderboard_path.exists():
+ try:
+ return json.loads(leaderboard_path.read_text(encoding="utf-8"))
+ except Exception:
+ pass
+ return {"games": [], "players": {}}
+
+
+def save_leaderboard(storage_path: Path, data: Dict[str, Any]):
+ leaderboard_path = get_leaderboard_path(storage_path)
+ leaderboard_path.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8")
+
+
+def save_game_to_leaderboard_from_record(
+ *,
+ storage_path: Path,
+ session_id: str,
+ game_mode: str,
+) -> Dict[str, Any]:
+ if str(game_mode or "") == "human_player":
+ return {"success": True, "skipped": True, "reason": "human_player games are excluded from leaderboard"}
+
+ if not session_id:
+ return {"success": False, "error": "missing_session_id"}
+
+ god_record_path = storage_path / "bot" / "workspace" / "bot_api__god" / "GAME_RECORD.md"
+ parsed_record = parse_game_record(god_record_path)
+ if parsed_record.get("game_status") != "游戏结束":
+ return {"success": False, "error": "game_record_not_finished"}
+
+ game_data = build_leaderboard_game_from_record(
+ parsed_record,
+ session_id=session_id,
+ game_mode=game_mode,
+ )
+ if not game_data.get("winner"):
+ return {"success": False, "error": "missing_game_result"}
+ if not game_data.get("players"):
+ return {"success": False, "error": "missing_players"}
+
+ leaderboard = load_leaderboard(storage_path)
+ if any(str(game.get("session_id") or "") == session_id for game in leaderboard.get("games", [])):
+ return {"success": True, "skipped": True, "reason": "already_saved", "leaderboard": leaderboard}
+
+ leaderboard["games"].append({
+ "session_id": session_id,
+ "timestamp": time.time(),
+ "winner": game_data.get("winner", ""),
+ "players": game_data.get("players", []),
+ })
+
+ for player in game_data.get("players", []):
+ player_id = player.get("id", "")
+ if not player_id:
+ continue
+ if player_id not in leaderboard["players"]:
+ leaderboard["players"][player_id] = {
+ "id": player_id,
+ "games_played": 0,
+ "games_won": 0,
+ "total_score": 0,
+ "roles": {},
+ }
+ player_stats = leaderboard["players"][player_id]
+ player_stats["games_played"] += 1
+ if player.get("won", False):
+ player_stats["games_won"] += 1
+ player_stats["total_score"] += player.get("score", 0)
+ role = player.get("role", "未知")
+ if role not in player_stats["roles"]:
+ player_stats["roles"][role] = 0
+ player_stats["roles"][role] += 1
+
+ save_leaderboard(storage_path, leaderboard)
+ return {"success": True, "leaderboard": leaderboard}
+
+
# ============================================================================
# UI File Initialization
# ============================================================================
@@ -1069,6 +1199,19 @@ async def message_router_loop(
save_conversation_to_file(state.storage_path, state.session_id, state.messages)
archive_replay_state(state.storage_path, state.channels, state.session_id, force=True)
+ leaderboard_result = save_game_to_leaderboard_from_record(
+ storage_path=state.storage_path,
+ session_id=state.session_id,
+ game_mode=state.game_mode,
+ )
+ if leaderboard_result.get("success"):
+ if leaderboard_result.get("skipped"):
+ logger.info(f"Leaderboard save skipped: {leaderboard_result.get('reason', 'unknown')}")
+ else:
+ logger.info("Leaderboard saved from authoritative GAME_RECORD.md")
+ else:
+ logger.warning(f"Failed to save leaderboard from GAME_RECORD.md: {leaderboard_result.get('error', 'unknown')}")
+
try:
await send_to_channel(
vikingbot_url=state.vikingbot_url,
@@ -1739,80 +1882,21 @@ def create_fastapi_app(state: GameState) -> FastAPI:
except Exception as e:
return JSONResponse(content={"error": str(e)}, status_code=500)
- def get_leaderboard_path() -> Path:
- """Get the path to the leaderboard file."""
- leaderboard_dir = state.storage_path / "bot" / "workspace" / "werewolf"
- leaderboard_dir.mkdir(parents=True, exist_ok=True)
- return leaderboard_dir / "LEADERBOARD.json"
-
- def load_leaderboard() -> Dict[str, Any]:
- """Load leaderboard data from file."""
- leaderboard_path = get_leaderboard_path()
- if leaderboard_path.exists():
- try:
- return json.loads(leaderboard_path.read_text(encoding="utf-8"))
- except Exception:
- pass
- return {"games": [], "players": {}}
-
- def save_leaderboard(data: Dict[str, Any]):
- """Save leaderboard data to file."""
- leaderboard_path = get_leaderboard_path()
- leaderboard_path.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8")
-
@fastapi_app.get("/api/leaderboard")
async def get_leaderboard():
"""Get leaderboard data."""
- return JSONResponse(content=load_leaderboard())
+ return JSONResponse(content=load_leaderboard(state.storage_path))
@fastapi_app.post("/api/leaderboard/save")
async def save_game_to_leaderboard(game_data: Dict[str, Any]):
- """Save a completed game to leaderboard."""
- if str(game_data.get("game_mode") or "") == "human_player":
- return JSONResponse(content={"success": True, "skipped": True, "reason": "human_player games are excluded from leaderboard"})
-
- leaderboard = load_leaderboard()
-
- # Add game record
- game_record = {
- "session_id": game_data.get("session_id", state.session_id),
- "timestamp": time.time(),
- "winner": game_data.get("winner", ""),
- "players": game_data.get("players", [])
- }
- leaderboard["games"].append(game_record)
-
- # Update player stats
- players_data = game_data.get("players", [])
- for player in players_data:
- player_id = player.get("id", "")
- if not player_id:
- continue
-
- if player_id not in leaderboard["players"]:
- leaderboard["players"][player_id] = {
- "id": player_id,
- "games_played": 0,
- "games_won": 0,
- "total_score": 0,
- "roles": {}
- }
-
- player_stats = leaderboard["players"][player_id]
- player_stats["games_played"] += 1
-
- if player.get("won", False):
- player_stats["games_won"] += 1
-
- player_stats["total_score"] += player.get("score", 0)
-
- role = player.get("role", "未知")
- if role not in player_stats["roles"]:
- player_stats["roles"][role] = 0
- player_stats["roles"][role] += 1
-
- save_leaderboard(leaderboard)
- return JSONResponse(content={"success": True, "leaderboard": leaderboard})
+ """Save a completed game to leaderboard using authoritative GAME_RECORD.md data."""
+ result = save_game_to_leaderboard_from_record(
+ storage_path=state.storage_path,
+ session_id=str(game_data.get("session_id") or state.session_id or ""),
+ game_mode=str(game_data.get("game_mode") or state.game_mode or ""),
+ )
+ status_code = 200 if result.get("success") else 400
+ return JSONResponse(content=result, status_code=status_code)
def scan_directory_tree(root_path: Path, relative_path: str) -> List[Dict[str, Any]]:
"""Recursively scan a directory and build a tree structure."""
diff --git a/bot/vikingbot/agent/context.py b/bot/vikingbot/agent/context.py
index c60a3829e..475f337a0 100644
--- a/bot/vikingbot/agent/context.py
+++ b/bot/vikingbot/agent/context.py
@@ -33,6 +33,7 @@ class ContextBuilder:
workspace: Path,
sandbox_manager: SandboxManager | None = None,
sender_id: str = None,
+ sender_name: str = None,
is_group_chat: bool = False,
eval: bool = False,
):
@@ -42,6 +43,7 @@ class ContextBuilder:
self._memory = None
self._skills = None
self._sender_id = sender_id
+ self._sender_name = sender_name
self._is_group_chat = is_group_chat
self._eval = eval
@@ -172,8 +174,8 @@ Skills with available="false" need dependencies installed first - you can try in
session_context += f"\nChannel: {session_key.type}"
if self._is_group_chat:
session_context += (
- f"\n**Group chat session.** Current user ID: {self._sender_id}\n"
- f"Multiple users can participate in this conversation. Each user message is prefixed with the user ID in brackets like @<user_id>. "
+ f"\n**Group chat session.** Current user: {self._sender_name if self._sender_name else self._sender_id}\n"
+ f"Multiple users can participate in this conversation. Each user message is prefixed with the user's name in brackets like '[张三]: 你好'. "
f"You should pay attention to who is speaking to understand the context. "
)
parts.append(session_context)
@@ -277,6 +279,7 @@ IMPORTANT:
session_key: Optional session key.
ov_tools_enable: Whether to enable OpenViking tools and memory.
profile_user_list: List of additional user IDs to fetch profiles for.
+ memory_user: Optional user ID to fetch memory for.
Returns:
List of messages including system prompt.
diff --git a/bot/vikingbot/agent/loop.py b/bot/vikingbot/agent/loop.py
index 8c8051e1a..210b2cb87 100644
--- a/bot/vikingbot/agent/loop.py
+++ b/bot/vikingbot/agent/loop.py
@@ -579,6 +579,7 @@ class AgentLoop:
message_workspace,
sandbox_manager=self.sandbox_manager,
sender_id=msg.sender_id,
+ sender_name=msg.sender_name,
is_group_chat=is_group_chat,
eval=self._eval,
)
@@ -593,7 +594,7 @@ class AgentLoop:
profile_user_list=profile_user_list,
memory_user=memory_user,
)
- # logger.info(f"New messages: {messages}")
+ # logger.info(f"New messages: {json.dumps(messages, indent=4)}")
# Run agent loop
final_content, tools_used, token_usage, iteration = await self._run_agent_loop(
diff --git a/bot/vikingbot/bus/events.py b/bot/vikingbot/bus/events.py
index fb2f03c1c..8d6493431 100644
--- a/bot/vikingbot/bus/events.py
+++ b/bot/vikingbot/bus/events.py
@@ -27,6 +27,7 @@ class InboundMessage:
content: str # Message text
session_key: SessionKey
timestamp: datetime = field(default_factory=datetime.now)
+ sender_name: str | None = None
need_reply: bool = True
media: list[str] = field(default_factory=list) # Media URLs
metadata: dict[str, Any] = field(default_factory=dict) # Channel-specific data
diff --git a/bot/vikingbot/channels/base.py b/bot/vikingbot/channels/base.py
index 924d3ca2d..afa9c2747 100644
--- a/bot/vikingbot/channels/base.py
+++ b/bot/vikingbot/channels/base.py
@@ -143,6 +143,7 @@ class BaseChannel(ABC):
async def _handle_message(
self,
sender_id: str,
+ sender_name: str,
chat_id: str,
content: str,
need_reply: bool = True,
@@ -175,6 +176,7 @@ class BaseChannel(ABC):
chat_id=chat_id,
),
sender_id=str(sender_id),
+ sender_name=sender_name,
need_reply=need_reply,
content=content,
media=media or [],
diff --git a/bot/vikingbot/channels/feishu.py b/bot/vikingbot/channels/feishu.py
index 451b23b9f..8fe9187b8 100644
--- a/bot/vikingbot/channels/feishu.py
+++ b/bot/vikingbot/channels/feishu.py
@@ -48,6 +48,11 @@ try:
ReplyMessageRequest,
ReplyMessageRequestBody
)
+ from lark_oapi.api.contact.v3 import (
+ GetUserRequest,
+ BatchGetIdUserRequest,
+ BatchGetIdUserRequestBody
+ )
FEISHU_AVAILABLE = True
except ImportError:
@@ -55,6 +60,9 @@ except ImportError:
lark = None
Emoji = None
GetImageRequest = None
+ GetUserRequest = None
+ BatchGetIdUserRequest = None
+ BatchGetIdUserRequestBody = None
# Message type display mapping
MSG_TYPE_MAP = {
@@ -64,6 +72,10 @@ MSG_TYPE_MAP = {
"sticker": "[sticker]",
}
+# Pre-compiled regex patterns
+MENTION_PATTERN = re.compile(r"@_user_\d+")
+OPEN_ID_MENTION_PATTERN = re.compile(r"@ou_[a-f0-9]+")
+
class FeishuChannel(BaseChannel):
"""
@@ -100,6 +112,9 @@ class FeishuChannel(BaseChannel):
self._tenant_access_token: str | None = None
self._token_expire_time: float = 0
self._chat_mode_cache: dict[str, str] = {} # 缓存群类型:group(普通群)/thread(话题群)
+ self._user_name_cache: OrderedDict[str, str] = OrderedDict() # LRU缓存用户ID到姓名的映射
+ self._bot_name_cache: dict[str, str] = {} # 缓存机器人open_id到名称的映射
+ self._MAX_USER_CACHE_SIZE = 1000 # 最大缓存1000个用户
async def _get_tenant_access_token(self) -> str:
"""Get tenant access token for Feishu API."""
@@ -741,26 +756,140 @@ class FeishuChannel(BaseChannel):
return True
chat_mode = await self._get_chat_mode(chat_id)
- if chat_mode != "thread":
- return True
-
- # 话题群处理逻辑
- is_topic_starter = message.root_id == message.message_id or not message.root_id
+ # 普通群和话题群都根据 thread_require_mention 判断
if self.config.thread_require_mention:
- # 模式1:所有消息都需要@才处理
+ # 模式1:所有消息都需要@才处理(普通群和话题群)
if not is_mentioned:
- logger.info(f"Skipping thread message: thread_require_mention is True and not mentioned")
return False
else:
- # 模式2:仅话题首条消息不需要@,后续回复需要@(DEBUG模式除外)
- config = load_config()
- if not is_topic_starter and not is_mentioned and config.mode != BotMode.DEBUG:
- logger.info(f"Skipping thread message: not topic starter and not mentioned")
- return False
+ # 模式2:话题群仅首条消息不需要@,后续回复需要@
+ if chat_mode == "thread":
+ is_topic_starter = message.root_id == message.message_id or not message.root_id
+ config = load_config()
+ if not is_topic_starter and not is_mentioned and config.mode != BotMode.DEBUG:
+ return False
+ # 普通群不需要@,直接处理
return True
+ async def _get_user_name(self, open_id: str) -> str | None:
+ """
+ Get user name from Feishu API by open_id.
+ Returns user name if found, None otherwise.
+ Uses LRU cache to avoid memory issues.
+ """
+ # Check cache first
+ if open_id in self._user_name_cache:
+ # Move to end (most recently used)
+ name = self._user_name_cache.pop(open_id)
+ self._user_name_cache[open_id] = name
+ return name
+
+ try:
+ # Directly get user by open_id
+ if GetUserRequest:
+ # Use open_id directly with user_id_type="open_id"
+ user_request = GetUserRequest.builder().user_id(open_id).user_id_type("open_id").build()
+ user_response = self._client.contact.v3.user.get(user_request)
+
+ if user_response.success() and user_response.data and user_response.data.user:
+ name = user_response.data.user.name
+ if len(self._user_name_cache) >= self._MAX_USER_CACHE_SIZE:
+ self._user_name_cache.popitem(last=False)
+ self._user_name_cache[open_id] = name
+ return name
+ except Exception as e:
+ logger.warning(f"Failed to get user name for {open_id}: {e}")
+
+ return None
+
+ async def _get_bot_name(self, open_id: str) -> str | None:
+ """
+ Get bot name by open_id.
+ First tries to get from cache, then uses config bot_name or "Bot".
+ Returns bot name if found, None otherwise.
+ """
+ # Check cache first
+ if open_id in self._bot_name_cache:
+ return self._bot_name_cache[open_id]
+
+ # Use config bot_name if available, otherwise "Bot"
+ bot_name = self.config.bot_name or "Bot"
+ self._bot_name_cache[open_id] = bot_name
+ return bot_name
+
+ async def _batch_get_user_names(self, open_ids: list[str]) -> dict[str, str]:
+ """
+ Get user names from Feishu API by open_ids (fetches individually with LRU cache).
+ Returns a dict mapping open_id to user name.
+ """
+ if not open_ids:
+ return {}
+
+ result = {}
+ # Check cache first
+ missing_ids = []
+ for open_id in open_ids:
+ if open_id in self._user_name_cache:
+ # Move to end (most recently used)
+ name = self._user_name_cache.pop(open_id)
+ self._user_name_cache[open_id] = name
+ result[open_id] = name
+ else:
+ missing_ids.append(open_id)
+
+ if not missing_ids:
+ return result
+
+ try:
+ # Fetch missing users one by one
+ for open_id in missing_ids:
+ try:
+ name = await self._get_user_name(open_id)
+ if name:
+ result[open_id] = name
+ except Exception as e:
+ logger.warning(f"Failed to get user name for {open_id}: {e}")
+ except Exception as e:
+ logger.warning(f"Failed to get user names: {e}")
+
+ return result
+
+ async def _process_group_message_content(self, content: str, sender_id: str) -> tuple[str, str]:
+ """
+ Process group message content:
+ 1. Get sender name and prepend to content
+ 2. Replace @open_id mentions with @name mentions
+
+ Returns:
+ tuple of (processed_content, sender_name)
+ """
+ mentioned_open_ids = OPEN_ID_MENTION_PATTERN.findall(content)
+ mentioned_open_ids = [mid[1:] for mid in mentioned_open_ids] if mentioned_open_ids else []
+
+ all_ids_to_fetch = list({sender_id} | set(mentioned_open_ids))
+ user_name_map = await self._batch_get_user_names(all_ids_to_fetch)
+
+ processed_content = content
+ if mentioned_open_ids:
+ for open_id in mentioned_open_ids:
+ name = user_name_map.get(open_id)
+ if not name:
+ # If user name not found, try to get bot name
+ name = await self._get_bot_name(open_id)
+ if name:
+ processed_content = processed_content.replace(f"@{open_id}", f"@{name}")
+
+ sender_name = user_name_map.get(sender_id, "")
+ if not sender_name:
+ # If sender name not found, try to get bot name
+ sender_name = await self._get_bot_name(sender_id) or ""
+ if sender_name:
+ processed_content = f"[{sender_name}]: {processed_content}"
+
+ return processed_content, sender_name
+
async def _on_message(self, data: "P2ImMessageReceiveV1") -> None:
"""Handle incoming message from Feishu."""
try:
@@ -811,13 +940,38 @@ class FeishuChannel(BaseChannel):
should_process = await self._check_should_process(chat_type, chat_id, message, is_mentioned)
# 7. 添加已读表情
- config = load_config()
- if config.mode != BotMode.DEBUG and should_process:
- await self._add_reaction(message_id, "MeMeMe")
-
- # 8. 处理@占位符
- mention_pattern = re.compile(r"@_user_\d+")
- content = mention_pattern.sub(f"@{sender_id}", content)
+ if should_process:
+ config = load_config()
+ if config.mode != BotMode.DEBUG:
+ await self._add_reaction(message_id, "MeMeMe")
+
+ # 8. 处理@占位符:从 message.mentions 中直接获取 name 和 id
+ mention_name_map = {}
+ if hasattr(message, 'mentions') and message.mentions:
+ for idx, mention in enumerate(message.mentions):
+ placeholder = f"@_user_{idx + 1}"
+ if hasattr(mention, 'id') and mention.id and placeholder in content:
+ # mention.id 是 UserId 对象,直接取 open_id
+ user_id = mention.id.open_id
+ # 保存 name 供后续使用
+ if hasattr(mention, 'name') and mention.name:
+ mention_name_map[user_id] = mention.name
+ # 先替换成 @open_id 格式
+ content = content.replace(placeholder, f"@{user_id}")
+ if "@_user_" in content:
+ content = MENTION_PATTERN.sub(f"@{sender_id}", content)
+
+ # 8.5 群聊场景:处理用户姓名
+ user_name = ""
+ if chat_type == "group":
+ user_name = mention_name_map.get(sender_id, "")
+ if not user_name:
+ user_name = await self._get_user_name(sender_id) or ""
+ if user_name:
+ content = f"[{user_name}]: {content}"
+ for user_id, name in mention_name_map.items():
+ if name and f"@{user_id}" in content:
+ content = content.replace(f"@{user_id}", f"@{name}")
# 9. 构建会话ID(处理话题群)
reply_to = chat_id if chat_type == "group" else sender_id
@@ -835,6 +989,7 @@ class FeishuChannel(BaseChannel):
logger.info(f"Received message from Feishu: {content}")
await self._handle_message(
sender_id=sender_id,
+ sender_name=user_name,
chat_id=final_chat_id,
content=content,
media=media if media else None,