"""会话列表操作""" from __future__ import annotations import logging import time import uiautomation as uia from ..config import Config logger = logging.getLogger(__name__) class ConversationList: """操作微信左侧会话列表""" def __init__(self, window: uia.WindowControl, config: Config) -> None: self._window = window self.config = config self._list: uia.ListControl | None = None # ------------------------------------------------------------------ # 初始化面板 # ------------------------------------------------------------------ def _ensure_list(self) -> uia.ListControl | None: if self._list is not None and self._list.Exists(maxSearchSeconds=0.5): return self._list try: # 微信会话列表通常是一个 ListControl # 通过搜索树定位第一个 ListControl lst = self._window.ListControl(searchDepth=8) if lst.Exists(maxSearchSeconds=2): self._list = lst return lst except Exception: logger.debug("定位会话列表失败") return None # ------------------------------------------------------------------ # 公开方法 # ------------------------------------------------------------------ def get_items(self) -> list[uia.Control]: """返回会话列表中的所有会话项""" lst = self._ensure_list() if lst is None: return [] try: return lst.GetChildren() except Exception: logger.exception("获取会话列表项失败") return [] def get_current_conversation_name(self) -> str: """获取当前激活的会话名称(聊天窗口顶部标题)""" try: # 聊聊窗口标题区域 edit = self._window.EditControl(searchDepth=8) if edit.Exists(maxSearchSeconds=1): return edit.Name or "" except Exception: pass return "" def click_conversation(self, name: str) -> bool: """点击指定名称的会话""" lst = self._ensure_list() if lst is None: return False try: for item in lst.GetChildren(): if name in (item.Name or ""): item.Click() time.sleep(0.5) logger.info("已切换到会话: %s", name) return True except Exception: logger.exception("点击会话失败: %s", name) logger.warning("未找到会话: %s", name) return False def search_conversation(self, keyword: str) -> bool: """通过搜索框定位会话""" try: search_edit = self._window.EditControl(Name="搜索", searchDepth=8) if not search_edit.Exists(maxSearchSeconds=2): search_edit = self._window.EditControl(searchDepth=3) if search_edit.Exists(maxSearchSeconds=1): search_edit.Click() time.sleep(0.3) search_edit.SendKeys(keyword, interval=0.05) time.sleep(1.0) # 点击第一个搜索结果 result = self._window.ListItemControl(searchDepth=8) if result.Exists(maxSearchSeconds=2): result.Click() time.sleep(0.5) return True except Exception: logger.exception("搜索会话失败: %s", keyword) return False