# coding=utf-8 import uiautomator2 as u2 import time import logging import sys import os # 添加项目根目录到 sys.path project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) if project_root not in sys.path: sys.path.append(project_root) # 配置日志 log_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "Logs") if not os.path.exists(log_dir): os.makedirs(log_dir) logging.basicConfig( level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', handlers=[ logging.FileHandler(os.path.join(log_dir, "T1_OpenChat.log"), encoding='utf-8'), logging.StreamHandler() ] ) logger = logging.getLogger("T1_OpenChat") def open_chat(target_name="糖豆爸爸"): logger.info(f"开始执行 T1: 打开微信并进入 '{target_name}' 的对话框...") # 连接设备 try: d = u2.connect() logger.info(f"设备连接成功: {d.info.get('serial')}") except Exception as e: logger.error(f"设备连接失败: {e}") return # 1. 启动微信 logger.info("步骤 1: 启动微信...") d.app_start("com.tencent.mm", stop=True) time.sleep(5) # 获取屏幕尺寸 w, h = d.window_size() logger.info(f"屏幕尺寸: {w}x{h}") # 2. 点击搜索按钮 search_x = int(w * 0.84) search_y = int(h * 0.08) logger.info(f"步骤 2: 点击搜索按钮 (坐标: {search_x}, {search_y})...") d.click(search_x, search_y) time.sleep(2) # 3. 输入搜索内容 logger.info(f"步骤 3: 输入搜索内容 '{target_name}'...") try: d.set_input_ime(True) d.click(int(w * 0.4), int(h * 0.08)) time.sleep(1) d.send_keys(target_name) time.sleep(2) d.set_input_ime(False) except Exception as e: logger.error(f"输入文字失败: {e}") try: d(focused=True).set_text(target_name) except: pass # 4. 点击搜索结果 logger.info("步骤 4: 查找并点击搜索结果...") time.sleep(2) found = False if d(text=target_name).exists: logger.info(f"找到文本为 '{target_name}' 的元素,点击...") d(text=target_name).click() found = True else: logger.warning(f"未找到文本为 '{target_name}' 的元素,尝试模糊匹配或坐标点击...") result_x = int(w * 0.5) result_y = int(h * 0.18) logger.info(f"尝试点击第一个搜索结果位置 ({result_x}, {result_y})...") d.click(result_x, result_y) found = True if found: logger.info("✅ T1 执行完成: 已进入对话框。") else: logger.error("❌ T1 执行失败: 未能进入对话框。") if __name__ == "__main__": open_chat()