from __future__ import annotations from contextlib import suppress from pyrogram import filters from pyrogram.enums import ChatMemberStatus import wbb from wbb import SUDOERS, app from wbb.services.business_assistant import BusinessAssistantRuntime from wbb.utils.dbassistant import ( get_account_settings, get_business_connection, get_conversation, resume_conversation, ) __MODULE__ = "智能接待" __HELP__ = "Telegram Business 智能接待由 Web 管理后台配置。" _runtime: BusinessAssistantRuntime | None = None async def start_business_assistant_runtime() -> None: global _runtime if _runtime is not None: return session = getattr(wbb, "aiohttpsession", None) token = str(getattr(wbb, "BOT_TOKEN", "")) if not session or not token: wbb.log.error("智能接待未启动:Telegram Bot 会话或令牌不可用。") return _runtime = BusinessAssistantRuntime(token=token, session=session) status = await _runtime.start() if status.get("polling_state") == "running": wbb.log.info("Telegram Business 智能接待已启动。") else: wbb.log.error(f"Telegram Business 智能接待未运行:{status.get('last_error') or '未知原因'}") async def stop_business_assistant_runtime() -> None: global _runtime if _runtime is None: return await _runtime.stop() _runtime = None def get_business_assistant_runtime() -> BusinessAssistantRuntime | None: return _runtime async def _ops_group_admin_allowed(query, settings: dict) -> bool: ops_group_id = int(settings.get("ops_group_id") or 0) if not ops_group_id or not query.message or int(query.message.chat.id) != ops_group_id: return False with suppress(Exception): member = await app.get_chat_member(ops_group_id, query.from_user.id) return member.status in { ChatMemberStatus.OWNER, ChatMemberStatus.ADMINISTRATOR, } return False @app.on_callback_query(filters.regex(r"^ba:resume:[a-f0-9]{32}$"), group=-20) async def resume_business_assistant_callback(_, query): conversation_id = str(query.data).rsplit(":", 1)[-1] conversation = await get_conversation(conversation_id) if not conversation: return await query.answer("会话不存在或已清理。", show_alert=True) connection = await get_business_connection(conversation["connection_id"]) if not connection: return await query.answer("Business 连接不存在。", show_alert=True) settings = await get_account_settings(connection["connection_id"]) owner_id = int((connection.get("user") or {}).get("id") or 0) allowed = ( query.from_user.id == owner_id or query.from_user.id in SUDOERS or await _ops_group_admin_allowed(query, settings) ) if not allowed: return await query.answer("只有账号本人或运营群管理员可以恢复。", show_alert=True) await resume_conversation(conversation_id) with suppress(Exception): await query.message.edit_reply_markup(None) await query.answer("已恢复自动回复。", show_alert=True)