diff --git a/.cursor/worktrees.json b/.cursor/worktrees.json new file mode 100644 index 0000000..77e9744 --- /dev/null +++ b/.cursor/worktrees.json @@ -0,0 +1,5 @@ +{ + "setup-worktree": [ + "npm install" + ] +} diff --git a/CHANGELOG.md b/CHANGELOG.md deleted file mode 100644 index aecb93b..0000000 --- a/CHANGELOG.md +++ /dev/null @@ -1,17 +0,0 @@ -# 更新记录(Changelog) - -本项目采用“版本号 + 日期 + 变更点”的方式记录。 - -## V3.3.1 (2025-12-14) - -- 高价值福袋:预约从单个 reserved 改为 reservations 队列(按开奖时间排序),支持队列上限与溢出淘汰最低价值。 -- 高价值福袋:队列满时回退到“开奖时间最早”的预约项等待,临近开奖前 N 秒回退参与。 -- 预约回退:修复参与窗口内等待不及时(remain<=0 时不再长时间等待,改为 1 秒促发回退参与)。 -- 回退定位:回退校验失败不再清空整个队列;增加上下微调搜索以提升回退命中率。 -- 回退校验:加入直播间名 OCR 辅助判断(用于更快识别是否回到目标直播间),并更新识别坐标。 -- OCR:倒计时识别更稳健(按框坐标排序拼接;默认前两位为分、后两位为秒;详情倒计时分割 OCR 纠错与兜底)。 -- Web GUI:统一日志落盘到 logs/unified.log,并增加实时截图卡片轮询 pic/screenshot.png。 -- 工具:tools/pick_coords.py 支持手动打开图片(文件选择对话框、菜单“文件→打开…”,Ctrl+O)。 -- 工程化:新增 version.py;多个入口脚本启动时打印版本号。 - -> 注:如果你需要更细颗粒度的提交级记录,可以在此版本下继续追加子条目。 diff --git a/README.md b/README.md index 1b2cd3e..0f7f8d7 100644 --- a/README.md +++ b/README.md @@ -1,230 +1,1263 @@ -# 功能展示 -用于在抖音直播间自动挂机领取福袋,只要手机不关机就能24小时无限刷福袋 -一个月即使运气非常差,中10来个奖品还是很轻松的! -部分奖品: -image - -# 使用方法 -1.手机打开“手势导航”,开启【屏幕内三键导航】,把3个按键显示出来 -2.手机连接电脑,开启开发者选项,usb调试打开,电脑上CMD命令提示行中输入adb devices命令能找到设备ID -3.手机页面初始化位置,打开抖音->个人中心->关注->直播中->随意进一个直播间 -4.然后执行douyin_guaji.py文件即可 -5.要是完全不知道咋弄或者运行后有什么问题,你都可以到B站找到叼哥,会帮你答疑或者私有化部署 +# 抖音福袋挂机脚本 - 详细文档 -## 可视化界面(推荐) -新增了一个可视化控制台,方便你改配置、选择设备、一键运行/停止,并实时看日志。 +
-GUI 里可以直接调:最低奖品价值、参与人数范围、倒计时太短(秒)自动跳过、粉丝团门槛策略等。 +**一个功能完善的抖音直播间福袋自动挂机工具** -另外也支持: -1) 切换直播间达到 N 次后,自动在当前直播间页下滑回退到本轮第一个直播间; +基于 ADB + OCR + 像素检测 + 模板匹配技术 -界面里带「截图预览」页,可以直接查看 `pic/fudai_value.png` 等截图,方便确认奖品价值/倒计时是否被完整截取。 +[![Version](https://img.shields.io/badge/version-V3.3.1-blue.svg)](version.py) +[![Python](https://img.shields.io/badge/python-3.10+-green.svg)](https://www.python.org/) +[![Platform](https://img.shields.io/badge/platform-Windows-lightgrey.svg)](https://www.microsoft.com/windows) -1. 安装 GUI 依赖(更美观): +
+ +--- + +## 📖 目录 + +- [项目简介](#项目简介) +- [核心功能](#核心功能) +- [技术架构](#技术架构) +- [环境要求与安装](#环境要求与安装) +- [快速开始](#快速开始) +- [详细配置说明](#详细配置说明) +- [使用指南](#使用指南) +- [工作原理](#工作原理) +- [代码结构](#代码结构) +- [故障排查](#故障排查) +- [开发指南](#开发指南) +- [常见问题 FAQ](#常见问题-faq) +- [版本历史](#版本历史) +- [免责声明](#免责声明) + +--- + +## 📖 项目简介 + +**抖音福袋挂机脚本(douyin_guaji)** 是一个专为抖音直播间设计的自动化工具,通过 ADB(Android Debug Bridge)连接安卓设备,结合 OCR(光学字符识别)、像素检测和模板匹配技术,实现全自动的福袋寻找、筛选、参与和领奖流程。 + +### 主要特点 + +- ✅ **全自动化**:无需人工干预,24小时持续运行 +- ✅ **智能筛选**:根据价值、参与人数、关键词等多维度条件筛选福袋 +- ✅ **高价值预约**:自动预约高价值福袋,提前参与抽奖 +- ✅ **风控优化**:支持推荐页养号行为,降低账号风险 +- ✅ **多界面支持**:提供桌面 GUI、Web GUI 和命令行三种使用方式 +- ✅ **模块化设计**:代码结构清晰,易于维护和扩展 +- ✅ **详细日志**:完整的运行日志记录,便于问题排查 + +### 适用场景 + +- 需要长时间挂机抢福袋的用户 +- 希望自动筛选高价值福袋的用户 +- 需要批量管理多个账号的用户 +- 希望降低人工操作频率的用户 + +--- + +## ✨ 核心功能 + +### 1. 自动寻找福袋 + +- 在直播间内自动检测福袋图标 +- 支持多种分辨率设备(自动适配) +- 可配置检测重试次数和等待时间 +- 智能处理福袋图标加载延迟 + +### 2. 智能筛选系统 + +**价值筛选** +- 设置最低奖品价值阈值 +- 自动跳过低价值福袋 + +**参与人数筛选** +- 设置参与人数范围(最小/最大) +- 避免竞争过于激烈的福袋 + +**关键词筛选** +- 支持"想要"关键词列表(白名单) +- 支持"不想要"关键词列表(黑名单) +- 自动匹配福袋内容描述 + +**倒计时筛选** +- 跳过倒计时过短的福袋(避免来不及参与) +- 跳过倒计时过长的福袋(切换到其他直播间) + +### 3. 自动参与抽奖 + +- 自动点击参与按钮 +- 处理"参与成功"、"还需看播"等提示 +- 自动处理粉丝团门槛(可选) +- 处理各种弹窗和异常情况 + +### 4. 自动领奖系统 + +- 自动识别开奖结果(中奖/未中奖) +- 中奖后自动领取奖品 +- 处理订单确认页面 +- 自动关闭各种弹窗和提示 + +### 5. 高价值福袋预约 + +- 自动识别高价值福袋(可配置阈值) +- 记录福袋开奖时间 +- 提前返回直播间参与抽奖 +- 支持多个预约同时管理 +- 防止回退过远导致异常 + +### 6. 高价值直播间回访 + +- 记录高价值直播间信息 +- 定时回访高价值直播间 +- 支持仅本次运行回访或持久化回访 + +### 7. 推荐页养号功能 + +- 自动点赞(可配置概率) +- 自动收藏(可配置概率) +- 自动评论(可配置概率和内容) +- 模拟真实用户行为,降低风控风险 +- 支持关键词触发(仅对特定内容点赞/收藏) + +### 8. 人机验证处理 + +- 自动检测人机验证弹窗 +- 支持滑块验证(自动计算距离) +- 支持图片点击验证 +- 支持人脸识别验证 +- 失败后自动重试 + +### 9. 弹窗处理 + +- 自动关闭优惠券弹窗 +- 自动关闭购物红包弹窗 +- 处理各种系统提示弹窗 + +### 10. 直播间切换 + +- 支持上划切换直播间 +- 可配置切换策略(倒计时阈值) +- 支持切换N次后回到第一个直播间(循环模式) +- 智能处理直播结束、网络异常等情况 + +--- + +## 🏗️ 技术架构 + +### 核心技术栈 + +- **Python 3.10+**:主要编程语言 +- **ADB(Android Debug Bridge)**:设备连接和控制 +- **PaddleOCR**:OCR 文字识别引擎 +- **OpenCV(cv2)**:图像处理和模板匹配 +- **Pillow(PIL)**:图像处理库 +- **NumPy**:数值计算和数组操作 + +### 检测技术 + +1. **像素检测** + - 基于颜色和像素模式的快速检测 + - 用于检测弹窗背景、按钮区域等 + - 速度快,资源占用低 + +2. **模板匹配** + - 使用 OpenCV 的模板匹配算法 + - 用于识别图标、按钮等UI元素 + - 支持多分辨率适配 + +3. **OCR 识别** + - 使用 PaddleOCR 识别文字内容 + - 用于识别福袋内容、倒计时、价值等 + - 支持中英文识别 + +4. **阶段诊断** + - 综合使用像素检测、模板匹配和OCR + - 判断当前页面状态(直播间、推荐页、详情页等) + - 支持并行检测,提高效率 + +### 架构设计 + +``` +┌─────────────────────────────────────────┐ +│ GUI / Web GUI / CLI │ +│ (用户界面层) │ +└──────────────┬──────────────────────────┘ + │ +┌──────────────▼──────────────────────────┐ +│ douyin_fudai.py │ +│ (核心调度器 - 主流程控制) │ +└──────────────┬──────────────────────────┘ + │ + ┌──────────┼──────────┐ + │ │ │ +┌───▼───┐ ┌───▼───┐ ┌───▼───┐ +│阶段诊断│ │福袋核心│ │弹窗处理│ +│stage │ │core │ │popups │ +└───────┘ └───────┘ └───────┘ + │ │ │ + └──────────┼──────────┘ + │ +┌──────────────▼──────────────────────────┐ +│ Underlying_Operations.py │ +│ (底层操作封装 - ADB/OCR) │ +└──────────────┬──────────────────────────┘ + │ +┌──────────────▼──────────────────────────┐ +│ ADB / PaddleOCR │ +│ (系统底层接口) │ +└─────────────────────────────────────────┘ +``` + +--- + +## 💻 环境要求与安装 + +### 系统要求 + +- **操作系统**:Windows 10/11(64位) +- **Python**:3.10 或更高版本(推荐 3.10-3.12) +- **内存**:至少 4GB RAM(推荐 8GB+) +- **存储**:至少 2GB 可用空间 + +### 必需软件 + +1. **Python 3.10+** + - 下载地址:https://www.python.org/downloads/ + - 安装时勾选"Add Python to PATH" + +2. **ADB(Android Debug Bridge)** + - 下载 Android SDK Platform Tools:https://developer.android.com/studio/releases/platform-tools + - 解压后添加到系统 PATH,或放在项目目录下 + - 验证安装:在命令行运行 `adb version` + +3. **Android 设备** + - 安卓手机或平板(Android 5.0+) + - 已开启开发者模式和 USB 调试 + - 已安装抖音 APP + +### 安装步骤 + +#### 1. 克隆或下载项目 ```bash +# 如果使用 Git +git clone +cd douyin_guaji-main + +# 或直接下载 ZIP 文件并解压 +``` + +#### 2. 创建虚拟环境(推荐) + +```bash +# 创建虚拟环境 +python -m venv .venv + +# 激活虚拟环境 +# Windows PowerShell: +.venv\Scripts\Activate.ps1 +# Windows CMD: +.venv\Scripts\activate.bat +``` + +#### 3. 安装 Python 依赖 + +```bash +# 安装核心依赖 +pip install pillow paddlepaddle paddleocr numpy opencv-python + +# 如果 paddlepaddle 安装失败,可以尝试: +# CPU 版本(推荐) +pip install paddlepaddle==2.5.2 -i https://pypi.tuna.tsinghua.edu.cn/simple + +# 或 GPU 版本(需要 CUDA) +pip install paddlepaddle-gpu==2.5.2 -i https://pypi.tuna.tsinghua.edu.cn/simple + +# 安装 GUI 依赖(可选) pip install ttkbootstrap + +# 安装 Web GUI 测试工具依赖(可选) +pip install playwright +python -m playwright install chromium ``` -2. 运行 GUI: +#### 4. 验证安装 ```bash -python gui_app.py +# 检查 Python 版本 +python --version + +# 检查 ADB +adb version + +# 检查设备连接 +adb devices +# 应该能看到你的设备,状态为 "device" ``` -GUI 会读写 `config.json`,并通过 `run_cli.py` 启动挂机进程。 +#### 5. 配置设备 -## 日志(便于排错) -默认会把所有运行日志追加写入统一文件:`logs/unified.log`(不设行数上限,按磁盘容量为准)。 +1. **开启开发者模式** + - 进入手机"设置" → "关于手机" + - 连续点击"版本号"7次 + - 返回设置,找到"开发者选项" -相关配置在 `config.json`: -- `log_unified_enabled`: 是否启用统一日志文件 -- `log_unified_path`: 统一日志文件路径(相对项目目录或绝对路径) -- `webgui_log_capacity`: Web GUI 内存里保留多少行日志(`0` 表示不限制;建议长时间运行时设为 `2000` 左右,避免占用过多内存) -## 注意 -6.缺少各种python三方库文件的需要自己安装一下,运行下面的命令: -pip install pillow paddlepaddle paddleocr numpy -从粉丝反馈来看,最新版的paddlepaddle可能会有问题 -7.根据自己设备的情况,修改douyin_guaji.py文件中y轴的像素偏移值,可正可负,通常调整区间在【-50,50】 -默认手机分辨率是1080*2400的像素,即使是相同的分辨率,可能也会因为手机顶部的刘海不一样,以及是否使用了底部导航按钮,导致存在Y轴的偏移 -![image](https://github.com/user-attachments/assets/e99dbd11-137b-407f-a37f-92a7b8235f90) -8.将会在4.0版本自动识别偏移值,后续不再需要调整任何参数,全自动识别、运行(叼哥B站达到1.5W粉发布) -9.基本上大部分问题,都能从这篇文章找到答案和建议:https://www.bilibili.com/opus/1104972369516036117 +2. **开启 USB 调试** + - 进入"开发者选项" + - 开启"USB 调试" + - 开启"USB 安装"(部分机型) -# 版本更新&预更新内容 - V1.0 - 支持无限循环挂机直播间 - 1.判断直播间福袋内容是否是想要的,如果不想要则切换直播间 - 2.直播间倒计时是否还有很久,太久则切换直播间 - 3.当直播间开奖后,立马切换直播间去别的直播间挂机 +3. **连接电脑** + - 使用 USB 线连接手机和电脑 + - 在手机上选择"文件传输"或"MTP"模式 + - 首次连接时,手机会弹出授权提示,选择"允许" - V1.1 - 1.对人机弹窗做判定,适当滑动解锁 - 2.对截图函数做优化,处理无法截图的情况 - 3.优化不切换直播间时的逻辑 +4. **验证连接** +```bash +adb devices + # 应该显示:xxxxxxx device +``` - V1.2 - 1.判定划动图片验证的人机校验,自动滑动一定距离处理人机验证 - 2.优化直播间判定逻辑,增加直播停留时间减少被人机的概率 - 3.增加直播间等待时间的参数,控制直播停留时间减少被人机的概率 - 4.增加对当前时间的判定,不同时间段对抽奖的内容做不同的处理 +--- - V1.3 - 1.增加直播已结束的判定 - 2.增加是否在直播列表页面的判定 - 3.增加回到直播列表重新进入直播的逻辑 - 4.增加点亮粉丝团抽奖的特殊处理 - 5.直播提早开奖补充截图内容获取,用于debug +## 🚀 快速开始 - V1.4 - 1.兼容了一下直播间忽然弹出来618红包弹窗导致页面一直卡在直播间的问题 - 2.修复进入直播间列表的功能异常的问题 - 3.优化挂机的时候直播间关闭的判定 - 4.兼容 同时存在参与条件+参与任务的抽奖 - 5.增加判断是否在个人中心的关注页面 - 6.修复领完奖后回到直播间判断不在直播间的问题 - 7.增加上划切换到直播间直播间已关闭的判断 - 8.兼容福袋参与抽奖的文案为:参与抽奖 +### 方式一:桌面 GUI(推荐新手) - V1.5 - 1.优化设备未识别的处理逻辑 - 2.优化图片文件夹不存在创建文件夹的逻辑 +1. **启动 GUI** +```bash + python gui_app.py + ``` - V1.6 - 1.增加日志内容同步输出到log文件中,方便问题排查 - 2.修复了到凌晨个别直播间提早关闭会导致直播判定卡住的问题 - 3.调整不切换直播间挂机的逻辑,现在会一直等待到直播间关闭才会切换 +2. **配置参数** + - 在"设备"下拉框选择你的设备 + - 设置 Y 偏移(首次使用可设为 0) + - 在"运行设置"中配置基本参数 + - 在"筛选设置"中配置福袋筛选条件 - V1.7 - 1.修复单独挂一个直播间,判定直播间已关闭后,不切换直播间的问题 - 2.增加全局的监控,无论发生什么情况,只要长时间判定为没有福袋,则重置整个挂机流程 +3. **开始运行** + - 点击"开始运行"按钮 + - 在右侧日志窗口查看运行状态 + - 点击"截图"按钮可查看实时截图 - V2.0 - 1.做了不同分辨率手机的兼容,现在不是1080*2400的手机也能挂机了 - 2.优化了从直播间列表进直播间连刷新2次的问题 - 3.优化了领奖完成后返回直播间领奖界面依旧没关闭的情况 - 4.修复了过了凌晨之后直播间一直没有福袋的判定问题 +4. **停止运行** + - 点击"停止"按钮 + - 或点击"强制停止"按钮(如果普通停止无效) - V2.1 - 1.修复节假日出现的直播红包弹窗一直无法被退出关闭的问题 - 2.兼容操控通过wifi直连到笔记本电脑上的手机 - 3.优化弹窗人机验证后,点击返回无法退出验证的情况 - 4.加入手机电量验证逻辑 - 5.增加手机电量不足时进入待机模式的逻辑,避免手机直接关机 - 6.兼容领奖完成后,判定关闭中奖弹窗后还有一个提醒领奖窗口的情况 - 7.优化凌晨后整个直播列表无直播间导致无法刷新的问题 +### 方式二:命令行(适合高级用户) - V2.2 - 1.优化日志打印逻辑 - 2.增加点击福袋无法打开,被系统限制参与抽奖的判定逻辑 - 3.修复在固定直播间挂机会忽然切换直播间的问题 - 4.修复:没有抽中,点击:我知道了,关闭弹窗,弹窗未关闭的问题 - 5.修复进入没有加入粉丝团的直播间,无法抽奖但没有切换直播间的问题 - 6.增加一个抽奖按钮的判定:活动已结束 - 7.增加了切换到未加入店铺的直播间的抽奖判定 - 8.修复:中奖后下单,回到直播间依旧存在中奖弹窗提醒关不掉的问题 +```bash +# 基本用法 +python run_cli.py --needswitch --wait-minutes 5 - V2.3 - 1.兼容任意分辨率的手机,增加横轴对应的分辨率设置 - 2.优化代码,抽象一部分方法,去除冗余代码 - 3.修复当直播间列表为空时,点击返回退出到关注中心,判定页面失效,无法回到直播间列表的问题 - 4.开奖结束后增加一个随机时长等待,减小风控风险 - 5.补充逻辑处理:直播间因为状态栏高度的不同,导致关闭的判定不同 - 6.调整挂机逻辑,到后半夜固定时间区间时,不再参与抽奖 +# 完整参数示例 +python run_cli.py \ + --device-id MB75DEFQZHZTGMLJ \ + --y-pianyi 0 \ + --needswitch \ + --wait-minutes 5 \ + --min-prize-value-yuan 200.0 \ + --min-participants 100 \ + --skip-if-countdown-lt-seconds 5 +``` - V2.4 - 1.调整偏移值逻辑,填任意正负数都会进行双重匹配,自动确认适宜的偏移值 - 2.调整长时间无法识别到福袋的逻辑,避免重复打开都是无福袋的直播间导致被风控 - 3.优化代码,抽象剩余部分方法,去除冗余代码 - 4.修复偶尔出现中奖后,领奖完成返回到直播间,结果页面退回到了视频首页的问题 - 5.补充下完单后,在购买成功页面的验证逻辑 +**常用参数说明**: +- `--device-id`:设备 ID(可省略,自动选择第一个) +- `--y-pianyi`:Y 轴偏移(-200~200,通常 -50~50) +- `--needswitch`:允许切换直播间 +- `--wait-minutes`:倒计时超过 N 分钟时切换 +- `--min-prize-value-yuan`:最低奖品价值(元) +- `--min-participants`:最少参与人数 +- `--skip-if-countdown-lt-seconds`:跳过倒计时少于 N 秒的福袋 - V3.0 - 1.引入百度PaddleOCR图像识别库,替换掉pytesseract,大幅提升文字识别准确度 - 2.优化代码,拆分基础操作函数到单独库做引用 - 3.执行脚本,不再需要手动设置手机分辨率参数,会自动设置手机对应的值 - 4.兼容人脸检测的人机验证弹窗的判定 - - V3.1 - 1.修复新账号中奖后,下完单返回到直播间,因为弹出一个'添加抖音商城到桌面'的弹窗,导致页面还卡在'购买成功'页面的问题 - 2.修复偶尔退出直播间,直接退到了个人中心,进而没有正确打开关注列表的问题 - 3.补充部分操作后的随机时长等待,规避被监控风险 - - V3.2 - 1.调整开奖后弹窗的点击判定,避免没有成功关闭弹窗的情况 - 2.兼容开奖后没有中奖,但是给了会员专属优惠券的情况 - 3.优化开奖后判定是否中奖及后续的逻辑 - - V3.3 - 1.将哪些福袋想要、不想要的配置移动到json文件中进行 - 2.在关注列表页面补充一个vivo手机断开充电的判定 - 3.调整开奖后未中奖,但发了一张优惠券的处理逻辑 - 4.适当调大关键截图的区间,方便判定 - +### 方式三:Web GUI(适合远程控制) - # 以下为预更新版本内容 - - V4.0(叼哥B站到1.5W粉丝发布 或 第三档充电提早获取) - 1.不再需要填写偏移值等任何参数,直接运行,会自动找到合适的偏移值进行后续操作 - 2.调整页面判断逻辑,实时记录当前所在页面的类型(直接间、直播列表、个人中心、订单页等) - 3.优化是否有福袋的判定逻辑 - 4.重做福袋详情弹窗内容判定逻辑 - 5.大幅调整代码逻辑,优化代码结构和性能 - 6.增加参与抽奖文案为'不满足参与条件'的情况的处理 - 7.补充刷新直播间列表逻辑,避免过于频繁刷新直播间导致被风控 - - V4.1 - 1.调整打开福袋详情判定异常后的关闭福袋弹窗位置,避免关闭弹窗实则是打开 - 2.调整参与抽奖内容为加入粉丝团(1钻石)的判定和处理逻辑 - 3.增加文件关闭机制,降低内存泄漏风险 - 4.修复在直播间判定是否存在福袋次数减少的问题 - - V4.2(最高档充电提早获取) - 1.模拟用户操作,在抖音商城中进行浏览、下单流程(创建订单但不付钱) - 2.模拟用户操作,到停止挂机时间段退出抖音,到开始挂机时间再启动抖音 - 3.模拟用户操作,在视频首页刷一会视频,并随机加评论、点赞 - 4.优化是否存在福袋的逻辑,只检测固定间隔的位置 - 5.调整了凌晨关闭抖音后等待时长的逻辑,统一等待到8点继续挂机 - 6.修复了福袋内容不想要多次切换直播间后,后续无法参与新福袋抽奖的问题 - - V4.3 - 1.调整对极速版的直播列表的判定 - 2.兼容部分直播间,在评论完后还要再点击‘观看直播’才能参与抽奖的情况 - 3.兼容开奖后,点击‘知道了’偶发弹窗未成功关闭的情况 - 4.将设备初次识别成功的偏移值存下来,后续运行改成直接读取保存的值 - - V4.4 - 1.重写判定福袋详情高度的逻辑 - 2.重写判定福袋详情和倒计时的方法,做到可以适配任意分辨率的手机 - 3.修复报错:UnicodeEncodeError: 'gbk' codec can't encode character - - V4.5 - 1.修复开局挂机的直播间没有福袋,导致执行报错的问题 - 2.调整参与福袋抽奖图标的截取逻辑,做到可以适配任意分辨率的手机 - 3.调整开奖结果弹窗内容的截取逻辑,做到可以适配任意分辨率的手机 - 3.增加对顶部状态栏高度的判定 - 4.调整是否在某些指定页面的判定逻辑,做到可以适配任意分辨率的手机 - 5.修复连续切换N个直播间,退出返回直播列表,多次循环后判定不到直播间的问题 - 6.增加抽奖次数统计 - - V4.6 - 1.移除偏移值的设定,改为动态自动查询 - 2.将设备初次识别成功的顶部状态栏高度存下来,后续运行改成直接读取保存的值 - 3.优化福袋参与抽奖按钮文字的二次判定逻辑 - 4.调整人机验证弹窗的判定 - 5.优化到凌晨时段,无法关闭抖音,卡在了直播关注列表的情况 - - 未来更新 - 1.获取直播间名字,关联奖品和倒计时,加入判定队列 - 2.完全自动处理防沉迷验证 - 3.兼容挂机过程中弹出的:开通特惠省钱卡的弹窗 - 4.增加钻石福袋挂机模式,在直播列表刷钻石 - 5.处理异常操作导致弹窗:账号存在风险的验证 - 6.兼容IOS系统,苹果手机也能挂机 - 7.增加直播间瞎逛模式,无限切换,发现想要的福袋就抽一下 - 8.其他来自充电粉丝们的建议,额外需要的功能 - 9.支持个性化定制操作时间,模拟你的个人使用习惯,让操作更像真人(规避风控) - 10.兼容最新版本的paddleOCR +1. **启动 Web 服务** +```bash + # 方式1:双击运行 + 一键启动WebGUI.bat -# 看到最后了,白嫖成功记得点个星,或者B站找叼哥进QQ群! + # 方式2:命令行运行 + python webgui_launcher.py + ``` + +2. **访问界面** + - 打开浏览器访问:`http://127.0.0.1:8000/` + - 如果是远程访问,使用:`http://<服务器IP>:8000/` + +3. **配置和运行** + - 点击"刷新设备"获取设备列表 + - 在各个配置标签页中设置参数 + - 点击"开始运行"启动脚本 + - 实时查看日志和截图 + +4. **停止服务** + ```bash + # 双击运行 + 停止WebGUI服务.bat + + # 或在 Web 界面点击"停止"按钮 + ``` + +--- + +## ⚙️ 详细配置说明 + +所有配置保存在 `config.json` 文件中,可通过 GUI 界面修改,也可以直接编辑 JSON 文件。 + +### 运行设置 + +| 参数名 | 类型 | 默认值 | 说明 | +|--------|------|--------|------| +| `needswitch` | boolean | `true` | 是否允许上划切换直播间 | +| `wait_minutes` | integer | `5` | 倒计时超过该分钟数时切换直播间(仅在 needswitch=true 时生效) | +| `skip_if_countdown_lt_seconds` | integer | `5` | 跳过倒计时少于该秒数的福袋(避免来不及参与) | +| `reset_after_swipes_enabled` | boolean | `true` | 是否启用"切换N次后回到第一个直播间"功能 | +| `reset_after_swipes` | integer | `30` | 切换直播间达到该次数后,下滑回退到第一个直播间 | +| `fudai_find_max_attempts` | integer | `10` | 找福袋图标的最大尝试次数 | +| `fudai_icon_retry_delay_seconds` | float | `0.6` | 找福袋图标的重试间隔(秒) | +| `fudai_icon_max_wait_seconds` | float | `5.0` | 找福袋图标的最大等待时间(秒),实际识别常见 4-6 秒 | +| `live_room_match_threshold` | float | `0.8` | 直播间检测阈值(0.0~1.0),值越高越严格,建议≥0.8 | +| `stage_diag_max_time` | float | `15.0` | 阶段诊断的最大耗时(秒) | +| `stage_diag_max_step_time` | float | `4.0` | 阶段诊断单步的最大耗时(秒) | + +### 福袋筛选设置 + +| 参数名 | 类型 | 默认值 | 说明 | +|--------|------|--------|------| +| `min_prize_value_yuan` | float | `0.0` | 最低奖品价值(元),低于该价值不参与,0 表示不启用 | +| `min_participants` | integer | `0` | 最少参与人数,低于该人数不参与,0 表示不启用 | +| `max_participants` | integer | `0` | 最多参与人数,高于该人数不参与,0 表示不启用 | +| `contains_want` | array | `[]` | 想要的关键词列表(白名单),福袋内容包含任一关键词则参与 | +| `contains_not_want` | array | `[]` | 不想要的关键词列表(黑名单),福袋内容包含任一关键词则跳过 | + +**示例**: +```json +{ + "min_prize_value_yuan": 200.0, + "min_participants": 100, + "max_participants": 10000, + "contains_want": ["手机", "现金", "红包"], + "contains_not_want": ["袜子", "优惠券", "代金券"] +} +``` + +### 粉丝团设置 + +| 参数名 | 类型 | 默认值 | 说明 | +|--------|------|--------|------| +| `auto_join_fansclub` | boolean | `true` | 是否自动加入粉丝团(谨慎:可能消耗钻石) | +| `fansclub_fail_action` | string | `"switch"` | 粉丝团加入失败后的策略:`"stay"`=停留当前直播间,`"switch"`=切换直播间 | + +### 高价值福袋预约 + +| 参数名 | 类型 | 默认值 | 说明 | +|--------|------|--------|------| +| `high_value_fudai_enabled` | boolean | `true` | 是否启用高价值福袋预约功能 | +| `high_value_fudai_threshold_yuan` | float | `500.0` | 高价值福袋的阈值(元),价值≥该值则预约 | +| `high_value_fudai_join_ahead_seconds` | integer | `120` | 提前参与秒数,开奖前 N 秒返回直播间参与 | +| `high_value_fudai_max_swipe_back` | integer | `35` | 最多回退直播间次数,防止回退过远导致异常 | +| `high_value_fudai_max_reservations` | integer | `3` | 最多同时记录的预约数量,超过后丢弃最晚开奖的 | +| `high_value_fudai_after_action` | string | `"continue"` | 完成预约后的动作:`"stay"`=停留,`"continue"`=继续抢福袋 | +| `reservation_back_verify_enabled` | boolean | `false` | 是否启用预约回退验证(回退后验证是否在目标直播间) | +| `reservation_back_swipe_delay` | float | `0.6` | 预约回退时的滑动延迟(秒) | +| `reservation_preempt_min_value` | float | `0.0` | 预约抢占最小价值(元),低于该价值的预约不会抢占当前任务 | + +### 高价值直播间回访 + +| 参数名 | 类型 | 默认值 | 说明 | +|--------|------|--------|------| +| `high_value_room_revisit_enabled` | boolean | `false` | 是否启用高价值直播间回访 | +| `high_value_room_revisit_only_current_run` | boolean | `false` | 是否仅本次运行回访(true=仅本次,false=持久化记录) | + +### 推荐页养号设置 + +| 参数名 | 类型 | 默认值 | 说明 | +|--------|------|--------|------| +| `yanghao_enabled` | boolean | `false` | 是否启用推荐页养号功能 | +| `yanghao_enable_actions` | boolean | `false` | 是否启用养号动作(点赞/收藏/评论) | +| `yanghao_recommend_duration_seconds` | integer | `216` | 推荐页停留时长(秒) | +| `yanghao_recommend_interval_seconds` | integer | `600` | 推荐页养号间隔(秒),0 表示不间隔 | +| `yanghao_like_prob` | float | `1.0` | 点赞概率(0.0~1.0),1.0 表示 100% 点赞 | +| `yanghao_fav_prob` | float | `0.85` | 收藏概率(0.0~1.0) | +| `yanghao_comment_prob` | float | `1.0` | 评论概率(0.0~1.0) | +| `yanghao_icon_roi_size` | integer | `240` | 图标检测区域大小(像素) | +| `yanghao_icon_match_threshold` | float | `0.72` | 图标匹配阈值(0.0~1.0) | +| `yanghao_step_screenshot` | boolean | `false` | 是否在养号步骤中截图(用于调试) | +| `yanghao_like_roi_offset_x` | integer | `0` | 点赞图标 ROI X 偏移 | +| `yanghao_like_roi_offset_y` | integer | `-50` | 点赞图标 ROI Y 偏移 | +| `yanghao_fav_roi_offset_x` | integer | `40` | 收藏图标 ROI X 偏移 | +| `yanghao_fav_roi_offset_y` | integer | `0` | 收藏图标 ROI Y 偏移 | +| `yanghao_like_icon_x` | integer | `0` | 点赞图标 X 坐标(0 表示自动检测) | +| `yanghao_like_icon_y` | integer | `-1` | 点赞图标 Y 坐标(-1 表示自动检测) | +| `yanghao_fav_icon_x` | integer | `-1` | 收藏图标 X 坐标 | +| `yanghao_fav_icon_y` | integer | `0` | 收藏图标 Y 坐标 | +| `yanghao_like_template_path` | string | `"assets/like.png"` | 点赞图标模板路径 | +| `yanghao_fav_template_path` | string | `"assets/fav.png"` | 收藏图标模板路径 | +| `yanghao_after_dwell_swipe_direction` | string | `"up"` | 停留后的滑动方向:`"up"`=上滑,`"down"`=下滑 | +| `yanghao_after_dwell_swipe_distance_px` | integer | `900` | 停留后的滑动距离(像素) | +| `yanghao_comment_btn_x` | integer | `0` | 评论按钮 X 坐标 | +| `yanghao_comment_btn_y` | integer | `0` | 评论按钮 Y 坐标 | +| `yanghao_comment_input_x` | integer | `0` | 评论输入框 X 坐标 | +| `yanghao_comment_input_y` | integer | `0` | 评论输入框 Y 坐标 | +| `yanghao_comment_send_x` | integer | `0` | 评论发送按钮 X 坐标 | +| `yanghao_comment_send_y` | integer | `-1` | 评论发送按钮 Y 坐标 | +| `yanghao_comment_close_x` | integer | `0` | 评论关闭按钮 X 坐标 | +| `yanghao_comment_close_y` | integer | `0` | 评论关闭按钮 Y 坐标 | +| `yanghao_comment_texts` | array | `[]` | 评论内容列表,随机选择一条评论 | +| `yanghao_like_keywords` | array | `[]` | 点赞关键词列表,内容包含关键词才点赞 | +| `yanghao_fav_keywords` | array | `[]` | 收藏关键词列表,内容包含关键词才收藏 | + +### 静默时段设置 + +| 参数名 | 类型 | 默认值 | 说明 | +|--------|------|--------|------| +| `fudai_quiet_hours_enabled` | boolean | `true` | 是否启用静默时段(该时段内不抢福袋) | +| `fudai_quiet_start_hour` | integer | `2` | 静默时段开始时间(小时,0-23) | +| `fudai_quiet_end_hour` | integer | `6` | 静默时段结束时间(小时,0-23) | + +**说明**:静默时段内脚本会跳过福袋,但仍可执行养号等操作。 + +--- + +## 📚 使用指南 + +### 首次使用步骤 + +1. **准备工作** + - 确保手机已开启 USB 调试 + - 连接手机到电脑 + - 验证 `adb devices` 能看到设备 + +2. **启动脚本** + - 使用 GUI 或命令行启动脚本 + - 首次运行建议使用 GUI,便于观察日志 + +3. **调整 Y 偏移** + - 如果发现点击位置不准确,调整 Y 偏移值 + - 通常范围在 -50~50 之间 + - 可以通过"截图"功能查看实际截图位置 + +4. **配置筛选条件** + - 根据需求设置价值、参与人数等筛选条件 + - 建议首次使用设置较宽松的条件,观察效果 + +5. **观察运行** + - 查看日志输出,确认脚本正常工作 + - 观察是否出现误判或异常情况 + - 根据实际情况调整配置参数 + +### 日常使用建议 + +1. **定期检查日志** + - 查看 `logs/unified.log` 了解运行情况 + - 关注错误和警告信息 + +2. **调整配置** + - 根据实际效果调整筛选条件 + - 优化高价值预约阈值 + - 调整养号参数降低风控风险 + +3. **保持设备连接** + - 确保手机不断网、不关机 + - 定期检查 USB 连接是否稳定 + - 建议使用 USB 3.0 接口 + +4. **监控账号状态** + - 定期检查账号是否正常 + - 关注是否出现人机验证 + - 如频繁出现验证,降低运行频率或启用养号 + +### 高级使用技巧 + +1. **多账号管理** + - 可以为每个账号创建独立的配置目录 + - 使用不同的 `config.json` 文件 + - 通过命令行参数覆盖配置 + +2. **定时任务** + - 使用 Windows 任务计划程序定时启动脚本 + - 结合静默时段配置,实现自动化运行 + +3. **远程控制** + - 使用 Web GUI 实现远程控制 + - 配置端口转发,实现外网访问 + +4. **性能优化** + - 调整阶段诊断时间参数,平衡速度和准确性 + - 优化 OCR 缓存设置,减少重复识别 + - 根据设备性能调整截图频率 + +--- + +## 🔍 工作原理 + +### 主流程 + +``` +开始 + │ + ├─> 初始化(加载配置、连接设备) + │ + ├─> 阶段诊断(判断当前页面) + │ ├─> 直播间? + │ │ ├─> 是 → 检测福袋图标 + │ │ │ ├─> 找到福袋 → 打开详情页 + │ │ │ └─> 未找到 → 切换直播间(如果启用) + │ │ └─> 否 → 导航到直播间 + │ │ + │ ├─> 福袋详情页? + │ │ ├─> 读取福袋信息(内容、倒计时、价值、参与人数) + │ │ ├─> 筛选判断(价值、人数、关键词) + │ │ ├─> 通过 → 参与抽奖 + │ │ └─> 不通过 → 关闭详情页 + │ │ + │ ├─> 抽奖结果页? + │ │ ├─> 中奖 → 自动领奖 + │ │ └─> 未中奖 → 关闭弹窗 + │ │ + │ └─> 其他页面 → 导航到直播间 + │ + ├─> 处理弹窗(优惠券、红包等) + │ + ├─> 处理人机验证 + │ + └─> 循环执行 +``` + +### 阶段诊断流程 + +阶段诊断是脚本的核心功能,用于判断当前页面状态: + +1. **直播间检测**(优先级最高) + - 使用模板匹配检测右上角关闭/心形图标 + - 阈值可配置(默认 0.8) + +2. **像素检测**(并行执行) + - 检测抽奖结果弹窗(大片红色区域) + - 检测参与按钮红色区域 + - 检测粉丝团加入红色区域 + - 检测优惠券/购物红包背景 + +3. **OCR 检测**(可选,当前默认关闭) + - 识别推荐页标签栏 + - 识别关注列表标签 + - 识别直播列表标签 + - 识别福袋详情内容 + +4. **综合判断** + - 根据检测结果返回当前阶段 + - 支持多阶段优先级判断 + +### 福袋检测流程 + +1. **图标检测** + - 在直播间内搜索福袋图标 + - 使用模板匹配算法 + - 支持多次重试(可配置) + +2. **详情页识别** + - 点击福袋图标进入详情页 + - 使用像素检测确认是否在详情页 + - 处理各种弹窗干扰 + +3. **信息提取** + - OCR 识别福袋内容区域 + - OCR 识别倒计时区域 + - OCR 识别价值区域 + - OCR 识别参与人数区域 + +4. **信息解析** + - 解析倒计时文本(支持多种格式) + - 提取奖品价值(元) + - 提取参与人数 + - 提取福袋内容描述 + +### 筛选判断流程 + +``` +福袋信息 + │ + ├─> 价值筛选 + │ ├─> 价值 < min_prize_value_yuan → 跳过 + │ └─> 通过 + │ + ├─> 参与人数筛选 + │ ├─> 人数 < min_participants → 跳过 + │ ├─> 人数 > max_participants → 跳过 + │ └─> 通过 + │ + ├─> 倒计时筛选 + │ ├─> 倒计时 < skip_if_countdown_lt_seconds → 跳过 + │ └─> 通过 + │ + ├─> 关键词筛选 + │ ├─> 包含 contains_not_want → 跳过 + │ ├─> contains_want 为空 → 通过 + │ ├─> 包含 contains_want → 通过 + │ └─> 不包含 contains_want → 跳过 + │ + └─> 通过所有筛选 → 参与抽奖 +``` + +### 高价值预约流程 + +1. **识别高价值福袋** + - 价值 ≥ `high_value_fudai_threshold_yuan` + - 记录福袋信息和开奖时间 + +2. **继续寻找其他福袋** + - 不立即参与,继续切换直播间 + - 记录当前直播间位置 + +3. **提前返回** + - 开奖前 `high_value_fudai_join_ahead_seconds` 秒 + - 回退到目标直播间 + - 参与抽奖 + +4. **预约管理** + - 最多同时记录 `high_value_fudai_max_reservations` 个预约 + - 超过后丢弃最晚开奖的预约 + +--- + +## 📁 代码结构 + +### 核心模块 + +#### `douyin_fudai.py` +- **职责**:核心调度器,主流程控制 +- **主要类**:`fudai_analyse` +- **主要方法**: + - `fudai_choujiang()`:主循环入口 + - `run_once_basic()`:单次循环执行 + - `load_config()`:加载配置 + - `_diagnose_stage_from_current_screen()`:阶段诊断入口 + - `_check_in_live_room_by_icon()`:直播间检测 + +#### `douyin_stage.py` +- **职责**:阶段诊断模块 +- **主要函数**:`diagnose_stage_from_current_screen()` +- **检测阶段**: + - `IN_LIVE_ROOM`:直播间 + - `RECOMMEND_PAGE`:推荐页 + - `FOLLOW_LIST`:关注列表 + - `LIVE_LIST`:直播列表 + - `FUDai_DETAIL`:福袋详情页 + - `FUDai_RESULT`:抽奖结果页 + - `FANSCLUB_JOIN`:粉丝团加入页 + - `LIVE_CLOSED`:直播已结束 + +#### `douyin_pixel.py` +- **职责**:像素检测模块 +- **主要功能**: + - 检测弹窗背景颜色 + - 检测按钮区域颜色 + - 并行采集像素特征 + +#### `douyin_fudai_core.py` +- **职责**:福袋核心业务逻辑 +- **主要函数**: + - `get_fudai_contain()`:获取福袋信息 + - `check_contain()`:检查福袋内容 + - `attend_choujiang()`:参与抽奖 + - `check_lucky_draw_result()`:检查开奖结果 + - `get_reward()`:领取奖品 + +#### `douyin_popups.py` +- **职责**:弹窗检测与处理 +- **主要函数**: + - `check_coupon_popup()`:检测优惠券弹窗 + - `check_shopping_redpacket_popup()`:检测购物红包弹窗 + +#### `douyin_robot.py` +- **职责**:人机验证处理 +- **主要函数**: + - `check_have_robot_analyse()`:检测人机验证 + - `deal_robot_analyse()`:处理人机验证 + - `deal_swipe_robot_analyse()`:处理滑块验证 + +#### `douyin_yanghao.py` +- **职责**:推荐页养号逻辑 +- **主要功能**: + - 点赞操作 + - 收藏操作 + - 评论操作 + - 关键词触发 + +#### `douyin_reservation.py` +- **职责**:高价值福袋预约管理 +- **主要功能**: + - 预约记录管理 + - 高价值直播间记录 + - 状态持久化 + +#### `Underlying_Operations.py` +- **职责**:底层操作封装 +- **主要类**:`underlying_operations` +- **主要方法**: + - `get_screenshot()`:获取截图 + - `click()`:点击操作 + - `swipe()`:滑动操作 + - `analyse_pic_word()`:OCR 识别 + +### 界面模块 + +#### `gui_app.py` +- **职责**:桌面 GUI 应用 +- **技术栈**:tkinter + ttkbootstrap +- **主要功能**: + - 设备选择和管理 + - 配置参数设置 + - 实时日志显示 + - 截图预览 + +#### `web_gui.py` +- **职责**:Web GUI 服务 +- **技术栈**:Python HTTP Server +- **主要功能**: + - RESTful API + - 实时日志推送 + - 配置管理 + - 统计信息 + +#### `webui/` +- **职责**:Web GUI 前端 +- **文件**: + - `index.html`:页面结构 + - `styles.css`:样式文件 + - `app.js`:前端逻辑 + +### 工具模块 + +#### `run_cli.py` +- **职责**:命令行入口 +- **主要功能**: + - 参数解析 + - 配置覆盖 + - 进程管理 + +#### `tools/` +- **职责**:开发和测试工具 +- **主要脚本**: + - `test_web_gui.py`:Web GUI 自动化测试 + - `pick_coords.py`:坐标选择工具 + +### 配置文件 + +#### `config.json` +- **职责**:所有配置参数 +- **格式**:JSON +- **说明**:详见"详细配置说明"章节 + +#### `version.py` +- **职责**:版本信息管理 +- **内容**:版本号、发布日期等 + +### 资源文件 + +#### `assets/` +- **内容**:模板图片 + - `x.png`:直播间关闭图标模板 + - `xin.png`:直播间心形图标模板 + - `like.png`:点赞图标模板 + - `fav.png`:收藏图标模板 + - `desktop.png`:桌面图标模板 + +#### `pic/` +- **内容**: + - `screenshot.png`:最新截图 + - `ocr/`:OCR 区域示例图片 + +#### `logs/` +- **内容**: + - `unified.log`:统一日志文件 + +#### `state/` +- **内容**: + - `reservations.json`:预约记录 + - `high_value_rooms.json`:高价值直播间记录 + +--- + +## 🔧 故障排查 + +### 设备连接问题 + +**问题**:`adb devices` 显示 `unauthorized` 或 `offline` + +**解决方案**: +1. 检查手机是否弹出授权提示,选择"允许" +2. 重新插拔 USB 线 +3. 重启 ADB 服务:`adb kill-server && adb start-server` +4. 检查 USB 驱动是否安装正确 + +**问题**:设备列表为空 + +**解决方案**: +1. 确认已开启 USB 调试 +2. 检查 USB 线是否支持数据传输(有些线只能充电) +3. 尝试更换 USB 接口 +4. 检查手机是否选择"文件传输"模式 + +### 识别错误问题 + +**问题**:点击位置不准确 + +**解决方案**: +1. 调整 Y 偏移值(`--y-pianyi` 参数) +2. 检查设备分辨率是否正确识别 +3. 查看截图确认实际位置 +4. 检查是否有系统导航栏影响 + +**问题**:无法识别福袋图标 + +**解决方案**: +1. 增加 `fudai_icon_max_wait_seconds`(福袋加载需要时间) +2. 检查 `assets/` 目录下的模板图片是否存在 +3. 查看日志确认检测过程 +4. 尝试手动截图,检查福袋图标是否可见 + +**问题**:阶段诊断错误 + +**解决方案**: +1. 调整 `live_room_match_threshold`(直播间检测阈值) +2. 检查模板图片是否匹配当前抖音版本 +3. 增加 `stage_diag_max_time`(给诊断更多时间) +4. 查看 `pic/ocr/` 目录下的调试图片 + +### OCR 识别问题 + +**问题**:OCR 识别错误或失败 + +**解决方案**: +1. 检查 PaddleOCR 是否正常安装 +2. 确认截图清晰度足够 +3. 检查识别区域是否正确 +4. 尝试更新 PaddleOCR 版本 + +**问题**:OCR 识别速度慢 + +**解决方案**: +1. 减少 OCR 识别频率 +2. 启用 OCR 缓存(如果支持) +3. 优化识别区域大小 +4. 使用 GPU 版本的 PaddleOCR(如果有 GPU) + +### 运行异常问题 + +**问题**:脚本频繁报错或崩溃 + +**解决方案**: +1. 查看 `logs/unified.log` 了解详细错误信息 +2. 检查 Python 版本是否兼容 +3. 检查依赖包版本是否正确 +4. 尝试重新安装依赖包 + +**问题**:脚本卡住不动 + +**解决方案**: +1. 检查网络连接是否正常 +2. 查看日志确认卡在哪一步 +3. 尝试手动截图,检查当前页面状态 +4. 重启脚本或设备 + +### 风控问题 + +**问题**:频繁出现人机验证 + +**解决方案**: +1. 启用推荐页养号功能 +2. 降低运行频率(增加延迟) +3. 配置静默时段(夜间只养号) +4. 调整养号参数,模拟真实用户行为 + +**问题**:账号被限制 + +**解决方案**: +1. 立即停止脚本运行 +2. 手动操作账号,恢复正常使用 +3. 降低脚本运行频率 +4. 增加随机延迟和人工操作 + +### 性能问题 + +**问题**:CPU 占用过高 + +**解决方案**: +1. 减少截图频率 +2. 优化 OCR 识别区域 +3. 使用 GPU 版本的 PaddleOCR +4. 调整阶段诊断时间参数 + +**问题**:内存占用过高 + +**解决方案**: +1. 限制日志文件大小 +2. 清理旧的截图文件 +3. 优化 OCR 缓存设置 +4. 重启脚本定期清理内存 + +--- + +## 🛠️ 开发指南 + +### 开发环境设置 + +1. **克隆项目** + ```bash + git clone + cd douyin_guaji-main + ``` + +2. **创建虚拟环境** + ```bash + python -m venv .venv + .venv\Scripts\activate + ``` + +3. **安装开发依赖** + ```bash + pip install -r requirements.txt + pip install pytest black flake8 mypy # 开发工具 + ``` + +### 代码规范 + +- **Python 风格**:遵循 PEP 8 +- **类型提示**:使用类型注解 +- **文档字符串**:使用 Google 风格 +- **命名规范**: + - 类名:大驼峰(`CamelCase`) + - 函数/变量名:小写下划线(`snake_case`) + - 常量:大写下划线(`UPPER_SNAKE_CASE`) + +### 添加新功能 + +1. **创建新模块** + - 在项目根目录创建 `douyin_xxx.py` + - 实现核心功能 + - 添加类型提示和文档字符串 + +2. **集成到主流程** + - 在 `douyin_fudai.py` 中导入新模块 + - 在适当位置调用新功能 + - 添加配置参数(如需要) + +3. **添加 GUI 支持** + - 在 `gui_app.py` 中添加 UI 控件 + - 在 `webui/index.html` 中添加配置项 + - 在 `webui/app.js` 中添加默认值 + +4. **测试** + - 编写单元测试(如需要) + - 手动测试新功能 + - 更新文档 + +### 调试技巧 + +1. **使用日志** +```python + self._log_kv("模块名", "操作", key1=value1, key2=value2) + ``` + +2. **使用截图** + ```python + self.operation.get_screenshot(self.device_id) + # 查看 pic/screenshot.png + ``` + +3. **使用 GUI 截图功能** + - 在 GUI 中点击"截图"按钮 + - 查看实时截图和 OCR 结果 + +4. **使用测试模式** + ```bash + python run_cli.py --test-yanghao-flow + ``` + +### 提交代码 + +1. **代码检查** + ```bash + black . --check + flake8 . + mypy . + ``` + +2. **提交信息格式** + ``` + 类型: 简短描述 + + 详细说明(可选) + ``` + + 类型包括:`feat`(新功能)、`fix`(修复)、`docs`(文档)、`refactor`(重构)等 + +--- + +## ❓ 常见问题 FAQ + +### Q1: 脚本支持哪些设备? + +**A**: 支持所有 Android 5.0+ 的设备,包括手机和平板。脚本会自动适配分辨率,但不同机型可能需要微调 Y 偏移值。 + +### Q2: 需要 Root 权限吗? + +**A**: 不需要 Root 权限,只需要开启 USB 调试即可。 + +### Q3: 可以同时运行多个账号吗? + +**A**: 可以,但需要: +1. 每个账号使用不同的设备或模拟器 +2. 每个账号使用不同的配置目录或配置文件 +3. 通过 `--device-id` 参数指定不同设备 + +### Q4: 脚本会被抖音检测吗? + +**A**: 脚本通过模拟真实用户操作实现自动化,但任何自动化工具都存在被检测的风险。建议: +1. 启用养号功能,模拟真实用户行为 +2. 不要运行过于频繁 +3. 配置静默时段 +4. 定期手动操作账号 + +### Q5: 如何提高中奖率? + +**A**: 中奖率主要取决于福袋本身,脚本无法提高中奖率,但可以: +1. 筛选参与人数较少的福袋 +2. 快速参与,避免错过 +3. 同时管理多个账号 + +### Q6: 脚本运行需要网络吗? + +**A**: 手机需要连接网络(WiFi 或移动数据),电脑不需要网络(除了下载依赖包时)。 + +### Q7: 可以自定义筛选条件吗? + +**A**: 可以,通过 `config.json` 中的 `contains_want` 和 `contains_not_want` 配置关键词列表。 + +### Q8: 高价值预约功能如何工作? + +**A**: +1. 脚本识别到高价值福袋(价值≥阈值) +2. 记录福袋信息和开奖时间 +3. 继续寻找其他福袋 +4. 开奖前提前返回参与抽奖 + +### Q9: 如何查看运行日志? + +**A**: +1. GUI/Web GUI 界面实时显示日志 +2. 查看 `logs/unified.log` 文件 +3. 命令行运行时直接在终端查看 + +### Q10: 脚本卡住了怎么办? + +**A**: +1. 查看日志确认卡在哪一步 +2. 使用 GUI 的"截图"功能查看当前页面 +3. 尝试点击"强制停止"按钮 +4. 重启脚本或设备 + +### Q11: 如何更新脚本? + +**A**: +1. 备份 `config.json` 和 `state/` 目录 +2. 下载最新版本 +3. 替换文件(保留配置和状态文件) +4. 检查 `config.json` 是否有新增配置项 + +### Q12: 支持 iOS 设备吗? + +**A**: 目前不支持 iOS 设备,因为 iOS 需要越狱才能使用类似 ADB 的工具。 + +--- + +## 📜 版本历史 + +### V3.3.1 (2025-12-14) + +**当前版本** + +- ✨ 新增:直播间检测阈值可配置(`live_room_match_threshold`) +- ✨ 新增:福袋图标检测等待时间可配置 +- 🐛 修复:修复直播间检测模板文件路径警告 +- 🔧 优化:优化阶段检测流程,优先使用像素检测 +- 🔧 优化:合并阶段 1.5 和阶段 3 的 OCR 检测 +- 📝 更新:完善文档和 README + +### V3.3.0 (2025-12-XX) + +- 🔄 重构:模块化重构,代码结构优化 +- ✨ 新增:像素检测优先策略 +- ✨ 新增:GUI 截图+OCR 功能 +- ✨ 新增:强制停止按钮 +- 🐛 修复:修复各种已知问题 + +### V3.2.0 + +- ✨ 新增:高价值福袋预约功能 +- ✨ 新增:高价值直播间回访功能 +- 🔧 优化:推荐页养号逻辑优化 + +### V3.1.0 + +- ✨ 新增:推荐页养号功能 +- 🔧 优化:OCR 识别准确率提升 + +### V3.0.0 + +- 🔄 重大更新:引入 PaddleOCR 替换 pytesseract +- ✨ 新增:自动分辨率适配 +- 🐛 修复:修复大量已知问题 + +### V2.x + +- 多分辨率支持 +- 稳定性提升 +- 各种 bug 修复 + +### V1.x + +- 基础功能实现 +- 福袋检测和参与 +- 自动领奖 + +--- + +## ⚠️ 免责声明 + +1. **本工具仅供学习交流使用**,请勿用于商业用途。 + +2. **使用本工具产生的任何后果由使用者自行承担**,包括但不限于: + - 账号被封禁或限制 + - 数据丢失或泄露 + - 设备损坏 + - 其他法律风险 + +3. **请遵守抖音平台相关规则**,不要使用本工具进行违法违规操作。 + +4. **作者不对使用本工具造成的任何损失负责**。 + +5. **使用本工具即表示您已阅读并同意本免责声明**。 + +--- + +## 📞 支持与反馈 + +如有问题或建议,欢迎: + +- 📧 提交 Issue +- 💬 加入交流群 +- 📖 查看详细文档 + +--- + +
+ +**感谢使用抖音福袋挂机脚本!** + +如果这个项目对你有帮助,欢迎 Star ⭐ + +
\ No newline at end of file diff --git a/Start-WebGUI.bat b/Start-WebGUI.bat deleted file mode 100644 index cdfea61..0000000 --- a/Start-WebGUI.bat +++ /dev/null @@ -1,14 +0,0 @@ -@echo off -setlocal -cd /d "%~dp0" -cd /d "c:\Users\12742\Desktop\douyin_guaji-main" - -:: 可修改为你需要的端口,例如 8001 -set PORT=8000 -set PYTHONIOENCODING=utf-8 -set PYTHONUNBUFFERED=1 - -call .venv\Scripts\activate.bat -python web_gui.py - -pause diff --git a/Underlying_Operations.py b/Underlying_Operations.py index c310b18..0253200 100644 --- a/Underlying_Operations.py +++ b/Underlying_Operations.py @@ -1,6 +1,7 @@ import subprocess from datetime import datetime, timedelta import os +import warnings # PaddleOCR 3.x 会在初始化/导入时进行模型源连通性检查;在国内网络环境下容易卡住。 # 这里提前设置环境变量,避免启动耗时/卡死。 @@ -8,6 +9,11 @@ os.environ.setdefault("DISABLE_MODEL_SOURCE_CHECK", "True") # 额外抑制 paddle/oneDNN/glog 的冗余信息(INFO/WARNING) os.environ.setdefault("GLOG_minloglevel", "2") os.environ.setdefault("OMP_NUM_THREADS", "1") + +# 抑制 PyTorch DataLoader 的 pin_memory 警告(当没有 GPU 时,EasyOCR 会触发此警告) +warnings.filterwarnings("ignore", message=".*pin_memory.*", category=UserWarning) +warnings.filterwarnings("ignore", message=".*accelerator.*", category=UserWarning) + import time from PIL import Image, ImageFilter import numpy as np @@ -22,6 +28,9 @@ import base64 from typing import Tuple, Optional import time as time_module +# 外部完整版 fudai 逻辑所在的工作树路径,用于镜像 screenshot 给那边使用 +_EXTERNAL_AXF_SCREENSHOT = r"C:\Users\12742\.cursor\worktrees\douyin_guaji-main\axf\pic\screenshot.png" + def _safe_replace_file(tmp_file: str, out_file: str, max_retries: int = 5) -> bool: """安全地替换文件,处理Windows文件锁定问题。 @@ -140,37 +149,85 @@ def _safe_replace_file(tmp_file: str, out_file: str, max_retries: int = 5) -> bo return False + +def _mirror_screenshot_to_external(src_file: str) -> None: + """将当前项目下的 screenshot.png 同步一份到外部 axf 目录,便于完整版代码复用。 + + 若外部目录/路径不存在或复制失败,会静默忽略,不影响主流程。 + """ + try: + external_path = _EXTERNAL_AXF_SCREENSHOT + if not external_path: + return + external_dir = os.path.dirname(external_path) + if not external_dir: + return + os.makedirs(external_dir, exist_ok=True) + if not os.path.exists(src_file): + return + tmp = external_path + ".tmp" + import shutil + + shutil.copyfile(src_file, tmp) + _safe_replace_file(tmp, external_path) + except Exception: + # 任何错误都不应该影响截图主流程 + pass + class underlying_operations: """底层操作类""" def __init__(self): # 关闭文档方向/矫正等重型前处理:我们的截图是手机UI,不是扫描文档。 # 支持延迟初始化(测试流程/只做点击时不需要 OCR)。 self.ocr = None + self.ocr_type = None # 'easyocr' 或 'paddleocr' if not str(os.environ.get("SKIP_OCR_INIT", "")).strip(): - # 在导入和实例化 PaddleOCR 时重定向 stdout/stderr, - # 以抑制其在控制台打印的“Checking connectivity/create model”等信息。 + # 优先使用EasyOCR(更快),如果失败则回退到PaddleOCR + # 首先尝试EasyOCR try: devnull = open(os.devnull, "w") with contextlib.redirect_stdout(devnull), contextlib.redirect_stderr(devnull): - from paddleocr import PaddleOCR - self.ocr = PaddleOCR( - lang="ch", - ocr_version="PP-OCRv4", - use_doc_orientation_classify=False, - use_doc_unwarping=False, - use_textline_orientation=False, - ) + import easyocr + # 只加载中文和英文,加快初始化速度 + self.ocr = easyocr.Reader(['ch_sim', 'en'], gpu=False, verbose=False) + self.ocr_type = 'easyocr' + print("[OCR] 使用 EasyOCR(快速模式)") try: devnull.close() except Exception: pass - except Exception: - # 若静默初始化失败,保留 None 并允许后续按需初始化,避免阻塞启动。 + except Exception as e: + # EasyOCR初始化失败,回退到PaddleOCR try: devnull.close() except Exception: pass - self.ocr = None + try: + devnull = open(os.devnull, "w") + with contextlib.redirect_stdout(devnull), contextlib.redirect_stderr(devnull): + from paddleocr import PaddleOCR + self.ocr = PaddleOCR( + lang="ch", + ocr_version="PP-OCRv4", + use_doc_orientation_classify=False, + use_doc_unwarping=False, + use_textline_orientation=False, + ) + self.ocr_type = 'paddleocr' + print("[OCR] EasyOCR不可用,使用 PaddleOCR(备选方案)") + print(f"[OCR] 提示:安装EasyOCR可提升速度,运行: pip install easyocr") + try: + devnull.close() + except Exception: + pass + except Exception: + # 若静默初始化失败,保留 None 并允许后续按需初始化,避免阻塞启动。 + try: + devnull.close() + except Exception: + pass + self.ocr = None + self.ocr_type = None logging.disable(logging.DEBUG) logging.disable(logging.WARNING) @@ -193,27 +250,48 @@ class underlying_operations: def _ensure_ocr(self): if self.ocr is not None: return + # 优先尝试EasyOCR try: devnull = open(os.devnull, "w") with contextlib.redirect_stdout(devnull), contextlib.redirect_stderr(devnull): - from paddleocr import PaddleOCR - self.ocr = PaddleOCR( - lang="ch", - ocr_version="PP-OCRv4", - use_doc_orientation_classify=False, - use_doc_unwarping=False, - use_textline_orientation=False, - ) + import easyocr + self.ocr = easyocr.Reader(['ch_sim', 'en'], gpu=False, verbose=False) + self.ocr_type = 'easyocr' + print("[OCR] 延迟初始化:使用 EasyOCR(快速模式)") try: devnull.close() except Exception: pass except Exception: + # EasyOCR失败,回退到PaddleOCR try: devnull.close() except Exception: pass - self.ocr = None + try: + devnull = open(os.devnull, "w") + with contextlib.redirect_stdout(devnull), contextlib.redirect_stderr(devnull): + from paddleocr import PaddleOCR + self.ocr = PaddleOCR( + lang="ch", + ocr_version="PP-OCRv4", + use_doc_orientation_classify=False, + use_doc_unwarping=False, + use_textline_orientation=False, + ) + self.ocr_type = 'paddleocr' + print("[OCR] 延迟初始化:使用 PaddleOCR(备选方案)") + try: + devnull.close() + except Exception: + pass + except Exception: + try: + devnull.close() + except Exception: + pass + self.ocr = None + self.ocr_type = None def select_device(self): """选择需要连接的设备""" @@ -248,6 +326,41 @@ class underlying_operations: num = int(num) return dictdevice[num] + def _find_pic_path(self, picname: str, for_reading: bool = True) -> Optional[str]: + """查找图片路径,支持新旧位置(向后兼容) + + Args: + picname: 图片名称(不含扩展名),如 '直播广场', '福袋内容' + for_reading: True=读取(支持新旧位置),False=写入(使用新位置) + + Returns: + 图片的完整路径,如果找不到且for_reading=True则返回None + """ + base_dir = os.path.dirname(__file__) + pic_base = os.path.join(base_dir, 'pic') + + # 运行时必需文件始终在根目录(不需要移动) + runtime_files = {'screenshot', 'cut'} + if picname in runtime_files: + path = os.path.join(pic_base, f'{picname}.png') + return path if (os.path.exists(path) or not for_reading) else None + + # OCR图片文件:优先查找新位置(ocr/),然后查找旧位置(根目录) + if for_reading: + # 读取:先查新位置,再查旧位置(向后兼容) + new_path = os.path.join(pic_base, 'ocr', f'{picname}.png') + if os.path.exists(new_path): + return new_path + old_path = os.path.join(pic_base, f'{picname}.png') + if os.path.exists(old_path): + return old_path + return None + else: + # 写入:使用新位置,确保目录存在 + ocr_dir = os.path.join(pic_base, 'ocr') + os.makedirs(ocr_dir, exist_ok=True) + return os.path.join(ocr_dir, f'{picname}.png') + def get_screenshot(self, device_id, path='pic'): """截图3个adb命令需要2S左右的时间""" if path == 'pic': @@ -294,6 +407,7 @@ class underlying_operations: if _valid_png(tmp_file): # 使用安全的文件替换函数 if _safe_replace_file(tmp_file, out_file): + _mirror_screenshot_to_external(out_file) print(f"[{timetag}] [截图] ✓ 获取屏幕截图成功") return True else: @@ -337,6 +451,7 @@ class underlying_operations: if _valid_png(tmp_file): # 使用安全的文件替换函数 if _safe_replace_file(tmp_file, out_file): + _mirror_screenshot_to_external(out_file) print("{} 获取屏幕截图".format(timetag)) return True else: @@ -349,6 +464,7 @@ class underlying_operations: try: with open(tmp_file, 'rb') as src, open(out_file, 'wb') as dst: dst.write(src.read()) + _mirror_screenshot_to_external(out_file) print(f"[{timetag}] [截图] ✓ 获取屏幕截图成功(通过直接写入)") return True except (OSError, PermissionError) as e: @@ -365,6 +481,7 @@ class underlying_operations: pass # 尝试重命名临时文件为目标文件 os.rename(tmp_file, out_file) + _mirror_screenshot_to_external(out_file) print("{} 获取屏幕截图(通过重命名临时文件)".format(timetag)) return True except Exception: @@ -410,36 +527,7 @@ class underlying_operations: os.system("%s -s %s shell input keyevent 4" % (self._adb(), device_id)) print("点击返回键") - def get_battery_level(self, device_id): - """获取设备电量信息""" - battery_info = subprocess.Popen("%s -s %s shell dumpsys battery" % (self._adb(), device_id), shell=True, - stdout=subprocess.PIPE) - battery_info_string = battery_info.stdout.read() - battery_info_string = bytes.decode(battery_info_string) - location = re.search('level:', battery_info_string) - if not location: - print("[警告] 无法解析电量信息,返回默认值100") - return 100 - span = location.span() - start, end = span - start = end + 1 - # 防止越界 - max_end = min(len(battery_info_string), start + 10) - for i in range(max_end - start): - end = start + i - if end >= len(battery_info_string) or battery_info_string[end] == "\n": - break - if end <= start: - print("[警告] 无法解析电量信息,返回默认值100") - return 100 - battery_level_str = battery_info_string[start:end].strip() - try: - battery_level = int(battery_level_str) - print("设备当前电量为{}".format(battery_level)) - return battery_level - except ValueError: - print(f"[警告] 电量解析失败:'{battery_level_str}',返回默认值100") - return 100 + # 电量检测方法已删除 def get_device_resolution(self, device_id): """获取设备分辨率""" @@ -505,25 +593,139 @@ class underlying_operations: print("保存中奖截图失败") def cut_pic(self, left_up=(0, 63), right_down=(1080, 1620), target='', name=''): - '''裁剪图片,获取需要的区域小图片方便识别''' - if target == '' or target == False: - path = os.path.dirname(__file__) + '/pic' - pic1_path = path + '/screenshot.png' - pic = Image.open(pic1_path) - if name == '': - cut_pic_path = path + '/cut.png' - else: - cut_pic_path = path + '/' + name + '.png' - pic.crop((left_up[0], left_up[1], right_down[0], right_down[1])).save(cut_pic_path) - return True - path_target = os.path.dirname(__file__) + '/pic/' + target - pic1_path = path_target + '/screenshot.png' - pic = Image.open(pic1_path) - if name == '': - cut_pic_path = path_target + '/cut.png' - else: - cut_pic_path = path_target + '/' + name + '.png' - pic.crop((left_up[0], left_up[1], right_down[0], right_down[1])).save(cut_pic_path) + '''裁剪图片,获取需要的区域小图片方便识别 + + 添加了错误处理: + - 检查文件是否存在 + - 验证图片完整性 + - 重试机制(如果文件损坏) + - 异常处理避免程序崩溃 + ''' + max_retries = 3 + retry_delay = 0.1 + + for attempt in range(max_retries): + try: + if target == '' or target == False: + path = os.path.dirname(__file__) + '/pic' + pic1_path = path + '/screenshot.png' + + # 检查文件是否存在 + if not os.path.exists(pic1_path): + if attempt < max_retries - 1: + time_module.sleep(retry_delay * (attempt + 1)) + continue + raise FileNotFoundError(f"截图文件不存在: {pic1_path}") + + # 验证文件大小(至少应该有一些内容) + if os.path.getsize(pic1_path) < 100: + if attempt < max_retries - 1: + time_module.sleep(retry_delay * (attempt + 1)) + continue + raise ValueError(f"截图文件太小,可能损坏: {pic1_path}") + + # 尝试打开并验证图片 + try: + pic = Image.open(pic1_path) + # 验证图片完整性(通过访问尺寸属性) + _ = pic.size + # 确保图片已加载 + pic.load() + except (SyntaxError, IOError, OSError) as e: + # 图片损坏,重试或返回False + if attempt < max_retries - 1: + print(f"[警告] 图片文件可能损坏,重试中 ({attempt + 1}/{max_retries}): {e}") + time_module.sleep(retry_delay * (attempt + 1)) + continue + # 最后一次尝试失败,让外层异常处理 + raise + + if name == '': + cut_pic_path = path + '/cut.png' + else: + # 使用新的路径查找方法(写入到新位置ocr/) + cut_pic_path = self._find_pic_path(name, for_reading=False) + + # 验证裁剪坐标有效性 + width, height = pic.size + left, top = left_up + right, bottom = right_down + if left < 0 or top < 0 or right > width or bottom > height or left >= right or top >= bottom: + raise ValueError(f"裁剪坐标无效: left_up={left_up}, right_down={right_down}, image_size={pic.size}") + + pic.crop((left, top, right, bottom)).save(cut_pic_path) + return True + + else: + path_target = os.path.dirname(__file__) + '/pic/' + target + pic1_path = path_target + '/screenshot.png' + + # 检查文件是否存在 + if not os.path.exists(pic1_path): + if attempt < max_retries - 1: + time_module.sleep(retry_delay * (attempt + 1)) + continue + raise FileNotFoundError(f"截图文件不存在: {pic1_path}") + + # 验证文件大小 + if os.path.getsize(pic1_path) < 100: + if attempt < max_retries - 1: + time_module.sleep(retry_delay * (attempt + 1)) + continue + raise ValueError(f"截图文件太小,可能损坏: {pic1_path}") + + # 尝试打开并验证图片 + try: + pic = Image.open(pic1_path) + _ = pic.size + pic.load() + except (SyntaxError, IOError, OSError) as e: + # 图片损坏,重试或返回False + if attempt < max_retries - 1: + print(f"[警告] 图片文件可能损坏,重试中 ({attempt + 1}/{max_retries}): {e}") + time_module.sleep(retry_delay * (attempt + 1)) + continue + # 最后一次尝试失败,让外层异常处理 + raise + + if name == '': + cut_pic_path = path_target + '/cut.png' + else: + cut_pic_path = path_target + '/' + name + '.png' + + # 验证裁剪坐标有效性 + width, height = pic.size + left, top = left_up + right, bottom = right_down + if left < 0 or top < 0 or right > width or bottom > height or left >= right or top >= bottom: + error_msg = f"裁剪坐标无效: left_up={left_up}, right_down={right_down}, image_size={pic.size}" + if attempt == max_retries - 1: + print(f"[错误] {error_msg}") + return False + continue + + pic.crop((left, top, right, bottom)).save(cut_pic_path) + return True + + except (SyntaxError, IOError, OSError, FileNotFoundError, ValueError) as e: + # 最后一次尝试失败,打印错误信息 + if attempt == max_retries - 1: + error_msg = f"[错误] 裁剪图片失败 (尝试 {max_retries} 次): {e}" + print(error_msg) + print(f" 源文件: {pic1_path}") + print(f" 目标文件: {cut_pic_path if 'cut_pic_path' in locals() else 'N/A'}") + # 不抛出异常,返回 False 让调用者处理 + return False + # 继续重试 + continue + except Exception as e: + # 其他未知异常 + if attempt == max_retries - 1: + print(f"[错误] 裁剪图片时发生未知错误: {e}") + return False + continue + + return False def analyse_pic_word(self, picname='', change_color=0): """识别图像中的文字, change_color=1或2为不同的二值化模式,其他不做处理 @@ -536,11 +738,15 @@ class underlying_operations: if self.ocr is None: return '' - path = os.path.dirname(__file__) + '/pic' if picname == '': + # cut.png 始终在根目录 + path = os.path.dirname(__file__) + '/pic' pic_path = path + '/cut.png' else: - pic_path = path + '/' + picname + '.png' + # 使用新的路径查找方法(支持新旧位置) + pic_path = self._find_pic_path(picname, for_reading=True) + if not pic_path: + return '' # 检查文件是否存在 if not os.path.exists(pic_path): @@ -568,9 +774,10 @@ class underlying_operations: # 性能优化:先用原尺寸跑一次 OCR;只有识别为空时才放大重试。 w, h = img.size # 优化:对于很小的图片,直接放大,避免浪费一次OCR调用 - if max(w, h) < 100: + # 提高阈值:对于UI文字(如"直播广场"),即使是172x58这样稍大的尺寸也需要放大 + if max(w, h) < 200: try: - scale = max(2, 200 // max(w, h, 1)) # 至少放大到200像素 + scale = max(2, 300 // max(w, h, 1)) # 至少放大到300像素,提高小文字识别率 img = img.resize((w * scale, h * scale), Image.BICUBIC) w, h = img.size except Exception: @@ -584,17 +791,28 @@ class underlying_operations: img_sharpened = img.filter(ImageFilter.UnsharpMask(radius=1, percent=150, threshold=3)) # 再增强对比度(轻微增强,避免过度处理) enhancer = ImageEnhance.Contrast(img_sharpened) - img_enhanced = enhancer.enhance(1.15) # 增强15%对比度 + # 根据图片尺寸动态调整对比度:小图片需要更强的对比度 + contrast_factor = 1.25 if max(w, h) < 300 else 1.15 # 小图片增强25%对比度 + img_enhanced = enhancer.enhance(contrast_factor) img1 = img_enhanced except Exception: # 如果增强失败,回退到原来的锐化 img1 = img.filter(ImageFilter.SHARPEN) img_np = np.array(img1) - result = self.ocr.ocr(img_np) - if result == [None]: - return '' - text = self.extract_ocr_content(result) + + # 根据OCR类型调用不同的识别方法 + # 如果没有设置ocr_type,默认使用PaddleOCR格式(向后兼容) + if getattr(self, 'ocr_type', None) == 'easyocr': + # EasyOCR: readtext返回格式为 [(bbox, text, confidence), ...] + result = self.ocr.readtext(img_np) + text = self.extract_ocr_content(result) + else: + # PaddleOCR: ocr返回格式为 [[...]] 或 [...] + result = self.ocr.ocr(img_np) + if result == [None]: + return '' + text = self.extract_ocr_content(result) # 如果识别为空且图片较小,尝试放大重试(精度优化:使用更好的放大算法和增强处理) if (not text) and max(w, h) <= 1200: @@ -610,15 +828,25 @@ class underlying_operations: img2 = img2_enhanced except Exception: img2 = img2.filter(ImageFilter.SHARPEN) - result2 = self.ocr.ocr(np.array(img2)) - if result2 != [None]: - text = self.extract_ocr_content(result2) - result = result2 + + if getattr(self, 'ocr_type', None) == 'easyocr': + result2 = self.ocr.readtext(np.array(img2)) + text2 = self.extract_ocr_content(result2) + if text2: + text = text2 + result = result2 + else: + result2 = self.ocr.ocr(np.array(img2)) + if result2 != [None]: + text2 = self.extract_ocr_content(result2) + if text2: + text = text2 + result = result2 except Exception: pass # 对关键字段做轻量级调试输出:图片很清楚但识别为空时,通常是返回结构变化或未检出文本 - if picname in ("fudai_content", "fudai_countdown") and not text: + if picname in ("福袋内容", "福袋倒计时") and not text: try: if isinstance(result, list) and result and isinstance(result[0], dict): print(f"OCR调试({picname}): result[0] keys={list(result[0].keys())}") @@ -634,8 +862,13 @@ class underlying_operations: ocr_result = content def _extract_text_from_item(item): - # 兼容旧格式:[box, (text, score)] + # 兼容EasyOCR格式:[(bbox, text, confidence), ...] -> (bbox, text, confidence) if isinstance(item, (list, tuple)) and len(item) >= 2: + # EasyOCR格式:item = (bbox, text, confidence),text在索引1 + if isinstance(item[1], str): + return item[1] + + # 兼容旧格式:[box, (text, score)] second = item[1] if isinstance(second, (list, tuple)) and len(second) >= 1: if isinstance(second[0], str): @@ -685,9 +918,10 @@ class underlying_operations: def _extract_xy_from_item(item): """尽力从 OCR item 中提取用于排序的 (y, x)。无法提取则返回 None。""" try: - # 旧格式:item = [box, (text, score)],box 为 4 点坐标 if isinstance(item, (list, tuple)) and len(item) >= 1: box = item[0] + # EasyOCR格式:bbox = [[x1,y1], [x2,y2], [x3,y3], [x4,y4]] + # PaddleOCR格式:box 为 4 点坐标列表 if isinstance(box, (list, tuple)) and box: xs = [] ys = [] @@ -1371,4 +1605,3 @@ class underlying_operations: return False time.sleep(0.2) - diff --git a/assets/x.png b/assets/x.png new file mode 100644 index 0000000..a113031 Binary files /dev/null and b/assets/x.png differ diff --git a/assets/xin.png b/assets/xin.png new file mode 100644 index 0000000..886cb45 Binary files /dev/null and b/assets/xin.png differ diff --git a/config.json b/config.json index f8d1456..c7c67bf 100644 --- a/config.json +++ b/config.json @@ -1,155 +1,69 @@ { - "log_unified_enabled": true, - "log_unified_path": "logs/unified.log", - "webgui_log_capacity": 2000, - "contains_want": [], - "contains_not_want": [ - "袜子1" - ], - "min_prize_value_yuan": 199.7, + "needswitch": true, + "wait_minutes": 5, + "min_prize_value_yuan": 200.0, "min_participants": 0, "max_participants": 0, "skip_if_countdown_lt_seconds": 5, + "reset_after_swipes_enabled": true, + "reset_after_swipes": 30, "auto_join_fansclub": true, "fansclub_fail_action": "switch", "high_value_fudai_enabled": true, - "high_value_fudai_threshold_yuan": 500, - "high_value_fudai_join_ahead_seconds": 90, - "high_value_fudai_max_swipe_back": 0, - "high_value_fudai_max_reservations": 4, + "high_value_fudai_threshold_yuan": 500.0, + "high_value_fudai_join_ahead_seconds": 120, + "high_value_fudai_max_swipe_back": 35, + "high_value_fudai_max_reservations": 3, "high_value_fudai_after_action": "continue", - "fudai_abnormal_reopen_delay_seconds": 1.2, - "fudai_quiet_hours_enabled": true, - "fudai_quiet_start_hour": 2, - "fudai_quiet_end_hour": 7, - "no_fudai_watchdog_enabled": false, - "reset_after_swipes": 15, - "yanghao_enabled": false, + "high_value_room_revisit_enabled": false, + "high_value_room_revisit_only_current_run": false, + "reservation_back_verify_enabled": false, + "reservation_back_swipe_delay": 0.6, + "reservation_preempt_min_value": 0.0, + "fudai_find_max_attempts": 10, + "fudai_icon_retry_delay_seconds": 0.6, + "fudai_icon_max_wait_seconds": 5.0, "yanghao_recommend_duration_seconds": 216, "yanghao_recommend_interval_seconds": 600, - "yanghao_enable_actions": false, - "yanghao_like_prob": 0.0, - "yanghao_fav_prob": 0.0, - "yanghao_like_icon_x": 988, - "yanghao_like_icon_y": 1290, - "yanghao_fav_icon_x": 985, - "yanghao_fav_icon_y": 1637, + "yanghao_like_prob": 1.0, + "yanghao_fav_prob": 0.85, + "yanghao_comment_prob": 1.0, + "yanghao_icon_roi_size": 240, + "yanghao_icon_match_threshold": 0.72, + "yanghao_step_screenshot": false, "yanghao_like_roi_offset_x": 0, "yanghao_like_roi_offset_y": -50, "yanghao_fav_roi_offset_x": 40, "yanghao_fav_roi_offset_y": 0, - "yanghao_icon_roi_size": 240, - "yanghao_icon_match_threshold": 0.72, + "contains_want": [], + "contains_not_want": [ + "袜子" + ], + "fudai_quiet_hours_enabled": true, + "fudai_quiet_start_hour": 2, + "fudai_quiet_end_hour": 6, + "yanghao_enabled": false, + "yanghao_enable_actions": false, + "yanghao_like_icon_x": 0, + "yanghao_like_icon_y": -1, + "yanghao_fav_icon_x": -1, + "yanghao_fav_icon_y": 0, "yanghao_like_template_path": "assets/like.png", "yanghao_fav_template_path": "assets/fav.png", - "yanghao_step_screenshot": false, - "yanghao_comment_prob": 0.0, - "yanghao_comment_btn_x": 981, - "yanghao_comment_btn_y": 1399, - "yanghao_comment_input_x": 250, - "yanghao_comment_input_y": 2218, - "yanghao_comment_send_x": 906, - "yanghao_comment_send_y": 1298, - "yanghao_comment_close_x": 586, - "yanghao_comment_close_y": 385, - "yanghao_comment_texts": [ - "????????????", - "??????????????????????????????", - "?????????????????????????????????????????????", - "???????????????????????????????????????", - "???????????????????????????", - "??????????????????????????????????????????", - "???????????????????????????", - "?????????????????????", - "??????????????????", - "????????????????????????", - "????????????????????????", - "???????????????????????????", - "????????????????????????????????????", - "????????????????????????", - "????????????????????????", - "????????????????????????????????????", - "???????????????????????????", - "?????????????????????", - "????????????-1", - "????????????", - "??????????????????????????????????????????", - "?????????????????????????????????????????????", - "??????????????????????????????????????????????????????????????????????????????????????????", - "????????????????????????????????????", - "?????????????????????????????????????????????", - "?????????????????????????????????????????????????????????????????????", - "?????????????????????????????????????????????", - "??????????????????????????????????????????", - "????????????????????????????????????????????????", - "???????????????????????????????????????", - "????????????", - "?????????????????????????????????", - "????????????????????????", - "???????????????????????????????????????", - "??????????????????????????????????????????????????????????????????", - "??????????????????", - "???????????????????????????????????????", - "????????????", - "???????????????????????????", - "????????????????????????????????????????????????", - "???????????????????????????", - "?????????????????????????????????", - "??????????????????", - "????????????????????????", - "?????????????????????????????????????????????", - "????????????????????????????????????", - "????????????????????????", - "?????????", - "????????????", - "????????????", - "DJ???????????????????????????????????????????????????", - "???????????????????????????", - "?????????????????????????????????????????????", - "???????????????????????????????????????????????????????????????????????????", - "???????????????????????????", - "??????????????????????????????", - "???????????????????????????", - "???????????????????????????", - "?????????????????????????????????", - "???XX???????????????", - "???????????????????????????", - "??????????????????", - "??????????????????", - "???????????????????????????", - "???????????????????????????????????????", - "????????????????????????", - "??????????????????????????????", - "??????????????????", - "??????????????????????????????", - "?????????????????????????????????" - ], "yanghao_after_dwell_swipe_direction": "up", "yanghao_after_dwell_swipe_distance_px": 900, - "yanghao_like_keywords": [ - "???", - "??????", - "Like" - ], - "yanghao_fav_keywords": [ - "??????", - "????????????", - "????????????", - "Favorite" - ], - "yanghao_fallback_close_x": 1030, - "yanghao_fallback_close_y": 120, - "yanghao_fallback_live_x": 718, - "yanghao_fallback_live_y": 169, - "yanghao_fallback_enter_live_x": 119, - "yanghao_fallback_enter_live_y": 345, - "reset_after_swipes_enabled": true, - "high_value_room_revisit_enabled": false, - "high_value_room_revisit_only_current_run": false, - "reservation_back_verify_enabled": false, - "fudai_icon_max_wait_seconds": 10, - "fudai_icon_adaptive_enabled": false, - "fudai_find_max_attempts": 5, - "reservation_preempt_min_value": 0, - "reservation_back_swipe_delay": 0.6 + "yanghao_comment_btn_x": 0, + "yanghao_comment_btn_y": -1, + "yanghao_comment_input_x": 0, + "yanghao_comment_input_y": 0, + "yanghao_comment_send_x": 0, + "yanghao_comment_send_y": -1, + "yanghao_comment_close_x": 0, + "yanghao_comment_close_y": 0, + "yanghao_comment_texts": [], + "yanghao_like_keywords": [], + "yanghao_fav_keywords": [], + "stage_diag_max_time": 15.0, + "stage_diag_max_step_time": 4.0, + "live_room_match_threshold": 0.7 } diff --git a/douyin_detection.py b/douyin_detection.py new file mode 100644 index 0000000..b98f60b --- /dev/null +++ b/douyin_detection.py @@ -0,0 +1,500 @@ +from __future__ import annotations + +""" +Functional fudai detection (WebGUI version) +=========================================== + +This module reimplements the key detection helpers used in `douyin_fudai`: + +- check_detail_height(analyser) -> int +- check_have_fudai_with_ready_screenshot(analyser, screenshot_ready=False) -> bool +- check_in_fudai_detail(analyser) -> bool + +The logic is adapted from the original `axf/douyin_detection.py`, with extra +defensive checks to avoid crashes when certain analyser attributes are missing. +""" + +from typing import Any +import os +import time + +from PIL import Image + + +def _ensure_detection_cache(analyser: Any) -> None: + """Ensure analyser has a simple detection cache structure.""" + if not hasattr(analyser, "_detection_cache"): + analyser._detection_cache = {} + if not hasattr(analyser, "_detection_cache_ttl"): + analyser._detection_cache_ttl = 2.0 + + +def check_detail_height(analyser: Any) -> int: + """Detect how many tasks are required in the fudai detail popup. + + Returns: + 0 / 1 / 2 / 3 (number of tasks). + """ + path = os.path.join(os.path.dirname(__file__), "pic") + pic1_path = os.path.join(path, "screenshot.png") + pic = None + for attempt in range(3): + try: + pic = Image.open(pic1_path) + pic.load() # force load to catch truncated files early + break + except Exception: + if attempt < 2: + try: + analyser.operation.get_screenshot(analyser.device_id) + analyser.operation.delay(0.2) + except Exception: + pass + pic = None + if pic is None: + try: + analyser._log_kv("检测", "读取截图失败,默认不需要任务", level="WARN") + except Exception: + pass + return 0 + + pic_new = pic.convert("RGBA") + pix = pic_new.load() + width, height = pic_new.size + + # X of “参与” button + try: + rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080) + except Exception: + rx = 1080 + try: + ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400) + except Exception: + ry = 2400 + + x = 536 * rx // 1080 + if not (0 <= x < width): + return 0 + + # (base_y, y_pianyi_offset, task_count) + try: + y_pianyi_val = int(getattr(analyser, "y_pianyi", 0) or 0) + except Exception: + y_pianyi_val = 0 + + check_points = [ + (983, 0, 2), + (983, y_pianyi_val, 2), + (983, -y_pianyi_val, 2), + (883, 0, 3), + (883, y_pianyi_val, 3), + (883, -y_pianyi_val, 3), + (1058, 0, 1), + (1058, y_pianyi_val, 1), + (1058, -y_pianyi_val, 1), + ] + + def _check_pixel_color(y_coord: int) -> bool: + if not (0 <= y_coord < height): + return False + try: + p = pix[x, y_coord] + if not (isinstance(p, tuple) and len(p) >= 3): + return False + r, g, b = int(p[0]), int(p[1]), int(p[2]) + return 28 <= r <= 40 and 32 <= g <= 42 and 76 <= b <= 86 + except Exception: + return False + + try: + for base_y, dy, task_count in check_points: + y = base_y * ry // 2400 + dy + if _check_pixel_color(y): + try: + analyser._log_kv("检测", f"识别到福袋任务数量:{task_count}个", task_count=task_count) + except Exception: + pass + return task_count + except Exception: + pass + + # Optional robot-check path from original implementation + try: + if hasattr(analyser, "check_have_robot_analyse") and analyser.check_have_robot_analyse(): + analyser.deal_robot_analyse() + except Exception: + pass + try: + analyser._log_kv("检测", "识别福袋任务数量:0个(不需要任务)", level="INFO", task_count=0) + except Exception: + pass + return 0 + + +def check_have_fudai_with_ready_screenshot(analyser: Any, screenshot_ready: bool = False): + """Check whether the live-room screen currently has a fudai icon. + + 仅使用像素/颜色特征进行检测(无位置过滤、无 OCR): + - 先用 numpy/逐像素扫描找到疑似图标位置; + - 再通过颜色统计(粉紫/粉蓝 vs 橙色券)过滤误报。 + """ + func_start = time.time() + path = os.path.join(os.path.dirname(__file__), "pic") + pic1_path = os.path.join(path, "screenshot.png") + attempt_count = 0 # 仅用于日志记录,不影响循环控制 + + try: + retry_delay_s = float(getattr(analyser, "fudai_icon_retry_delay_seconds", 0.3) or 0.3) + except Exception: + retry_delay_s = 0.3 + try: + max_wait_s = float(getattr(analyser, "fudai_icon_max_wait_seconds", 2.5) or 2.5) + except Exception: + max_wait_s = 2.5 + if retry_delay_s < 0.15: + retry_delay_s = 0.15 + if max_wait_s < 0: + max_wait_s = 0.0 + + try: + analyser._log_kv("[找福袋图标] 开始", f"最大等待时间{max_wait_s}秒,复用截图={screenshot_ready}") + except Exception: + pass + + detected_any = False + + # 完全基于时间限制,不使用次数限制 + while (time.time() - func_start) < max_wait_s: + attempt_start = time.time() + attempt_count += 1 + # Reuse external screenshot only on first attempt if provided + if not (screenshot_ready and attempt_count == 1): + try: + analyser._shot_and_diagnose("找福袋图标", "判定是否存在福袋", analyser.device_id, diagnose=False) + except Exception: + pass + + try: + pic = Image.open(pic1_path) + pic.load() + except Exception: + try: + analyser.operation.get_screenshot(analyser.device_id) + except Exception: + pass + # 检查是否还有剩余时间 + elapsed = time.time() - func_start + if elapsed < max_wait_s: + # 计算剩余时间,但至少等待 retry_delay_s + remaining_time = max_wait_s - elapsed + sleep_time = min(retry_delay_s, remaining_time) + if sleep_time > 0: + try: + analyser.operation.delay(sleep_time) + except Exception: + time.sleep(sleep_time) + continue + + pic_new = pic.convert("RGBA") + detected = False + detected_x = None + + # Resolution ratios + try: + rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080) + except Exception: + rx = 1080 + try: + ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400) + except Exception: + ry = 2400 + try: + y_pianyi_val = int(getattr(analyser, "y_pianyi", 0) or 0) + except Exception: + y_pianyi_val = 0 + + # First try numpy-accelerated scan over a horizontal band + numpy_scan_start = time.time() + try: + import numpy as _np + + # 优惠券一般在左侧,这里将扫描区域整体右移: + # 原范围约为 x∈[41,410],现在改为 x∈[220,960](1080 基准), + # 既避开左侧券位,又覆盖更多右侧可能出现福袋的位置。 + # Y值检测范围扩大:从348到448并行检测(基于1080x2400分辨率) + x1 = max(0, 220 * rx // 1080) + x2 = min(pic_new.size[0], 960 * rx // 1080) + y_top_base = 348 * ry // 2400 + y_pianyi_val + y_bottom_base = 448 * ry // 2400 + y_pianyi_val + y_top = max(0, y_top_base) + y_bottom = min(pic_new.size[1], y_bottom_base) + + if x1 < x2 and y_top < y_bottom: + roi = pic_new.crop((x1, y_top, x2, y_bottom)).convert("RGB") + arr = _np.array(roi) + if arr.size > 0: + r = arr[:, :, 0] + g = arr[:, :, 1] + b = arr[:, :, 2] + mask_center = ( + (r >= 190) + & (r <= 206) + & (g >= 173) + & (g <= 196) + & (b >= 234) + & (b <= 250) + ) + cols = _np.sum(mask_center, axis=0) + valid_cols = cols >= 2 + if valid_cols.any(): + col_idx = int(_np.argmax(valid_cols)) + detected_x = int((x1 + col_idx) * 1080.0 / max(1, rx)) + detected = True + detected_any = True + try: + analyser.last_find_fudai_time = time.time() + except Exception: + pass + except Exception: + detected = False + numpy_scan_elapsed = time.time() - numpy_scan_start + if numpy_scan_elapsed > 0.01: + try: + elapsed_time = time.time() - func_start + analyser._log_step_time( + f"numpy像素扫描(已用时{elapsed_time:.2f}秒)", numpy_scan_start, {"结果": "命中" if detected else "未命中"} + ) + except Exception: + pass + + # Fallback: per-pixel scan(第一步:只做颜色/像素级粗检测) + if not detected: + pixel_scan_start = time.time() + try: + pix = pic_new.load() + pic_width, pic_height = pic_new.size + # 与 numpy 扫描保持一致:整体右移,并尽量覆盖右侧大部分区域 + # Y值检测范围扩大:从348到448并行检测(基于1080x2400分辨率) + scan_x_start = 220 * rx // 1080 + scan_x_end = min(960 * rx // 1080, pic_width) + scan_y_start_base = 348 * ry // 2400 + y_pianyi_val + scan_y_end_base = 448 * ry // 2400 + y_pianyi_val + scan_y_start = max(0, scan_y_start_base) + scan_y_end = min(pic_height, scan_y_end_base) + + # 并行检测348到448范围内的所有Y值 + for check_y in range(scan_y_start, scan_y_end): + if not (0 <= check_y < pic_height): + continue + for x_scaled in range(scan_x_start, scan_x_end): + try: + px = pix[x_scaled, check_y] + if ( + len(px) >= 3 + and 190 <= px[0] <= 206 + and 173 <= px[1] <= 196 + and 234 <= px[2] <= 250 + ): + detected_x = int(x_scaled * 1080.0 / max(1, rx)) + detected = True + detected_any = True + try: + analyser.last_find_fudai_time = time.time() + except Exception: + pass + break + except Exception: + continue + if detected: + break + except Exception: + pass + pixel_scan_elapsed = time.time() - pixel_scan_start + if pixel_scan_elapsed > 0.01: + try: + elapsed_time = time.time() - func_start + analyser._log_step_time( + f"逐像素扫描(已用时{elapsed_time:.2f}秒)", pixel_scan_start, {"结果": "命中" if detected else "未命中"} + ) + except Exception: + pass + + if detected and detected_x is not None: + # 颜色分布过滤:在候选区域统计“粉紫/粉蓝”(福袋) vs “橙色”(券) 像素数量 + try: + base_y = 403 * ry // 2400 + y_pianyi_val + cx1 = max(0, int((detected_x - 45) * rx / 1080)) + cx2 = min(pic_new.size[0], int((detected_x + 45) * rx / 1080)) + cy1 = max(0, base_y - 45) + cy2 = min(pic_new.size[1], base_y + 45) + fudai_like = 0 + coupon_like = 0 + if cx1 < cx2 and cy1 < cy2: + pix2 = pic_new.load() + step = max(1, (cx2 - cx1) // 24) # 下采样防止太慢 + for yy in range(cy1, cy2, step): + for xx in range(cx1, cx2, step): + try: + p = pix2[xx, yy] + except Exception: + continue + if not (isinstance(p, tuple) and len(p) >= 3): + continue + r, g, b = int(p[0]), int(p[1]), int(p[2]) + # 福袋:粉/紫/粉蓝:R 高、B 也高,G 中等 + if r >= 200 and b >= 210 and 80 <= g <= 230: + fudai_like += 1 + # 券:偏黄橙色:R 高、G 中等、B 明显偏低 + if r >= 200 and 120 <= g <= 230 and b <= 180: + coupon_like += 1 + # 如果“橙券像素”明显多于“粉袋像素”,判定为优惠券,丢弃 + if coupon_like > fudai_like * 1.2: + try: + analyser._log_kv( + "[找福袋图标] 颜色过滤未通过", + "区域颜色更接近优惠券,视为非福袋", + fudai_like=fudai_like, + coupon_like=coupon_like, + x=detected_x, + ) + except Exception: + pass + detected = False + detected_x = None + except Exception: + detected = False + detected_x = None + + if detected and detected_x is not None: + # store last X if analyser expects it(此时已通过颜色过滤) + try: + analyser._last_fudai_icon_x = detected_x + except Exception: + pass + break + + # 检查是否还有剩余时间 + elapsed = time.time() - func_start + if elapsed < max_wait_s: + # 计算剩余时间,但至少等待 retry_delay_s + remaining_time = max_wait_s - elapsed + sleep_time = min(retry_delay_s, remaining_time) + if sleep_time > 0: + try: + analyser.operation.delay(sleep_time) + except Exception: + time.sleep(sleep_time) + + try: + total_elapsed = time.time() - func_start + analyser._log_kv( + "[找福袋图标] 结束", + "检测完成", + detected=bool(detected_any and detected_x is not None), + elapsed_ms=int(total_elapsed * 1000), + ) + except Exception: + pass + + # 与原始 fudai.py 的 check_have_fudai 行为保持一致: + # 返回福袋图标的 x 坐标(1080 基准坐标),未找到返回 False。 + return int(detected_x) if detected_x is not None else False + + +def check_in_fudai_detail(analyser: Any) -> bool: + """Detect whether we are currently on the fudai detail page.""" + _ensure_detection_cache(analyser) + cache_key = "check_in_fudai_detail" + now = time.time() + cached = analyser._detection_cache.get(cache_key) + if cached: + cached_ts, cached_result = cached + ttl = float(getattr(analyser, "_detection_cache_ttl", 2.0) or 2.0) + if (now - cached_ts) < ttl: + return bool(cached_result) + + path = os.path.join(os.path.dirname(__file__), "pic") + pic1_path = os.path.join(path, "screenshot.png") + try: + try: + pic0 = Image.open(pic1_path) + pic0.load() + pic = pic0.convert("RGBA") + except Exception: + try: + analyser.operation.get_screenshot(analyser.device_id) + pic0 = Image.open(pic1_path) + pic0.load() + pic = pic0.convert("RGBA") + except Exception: + analyser._detection_cache[cache_key] = (now, False) + return False + + pix = pic.load() + width, height = pic.size + try: + rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080) + except Exception: + rx = 1080 + try: + ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400) + except Exception: + ry = 2400 + try: + y_pianyi_val = int(getattr(analyser, "y_pianyi", 0) or 0) + except Exception: + y_pianyi_val = 0 + + x = 536 * rx // 1080 + if not (0 <= x < width): + analyser._detection_cache[cache_key] = (now, False) + return False + + base_ys = (883, 983, 1058) + offsets = (0, y_pianyi_val, -y_pianyi_val) + + for base_y in base_ys: + y0 = base_y * ry // 2400 + for dy in offsets: + y = y0 + dy + if not (0 <= y < height): + continue + try: + p = pix[x, y] + if not (isinstance(p, tuple) and len(p) >= 3): + continue + r, g, b = int(p[0]), int(p[1]), int(p[2]) + if 30 <= r <= 38 and 34 <= g <= 40 and 78 <= b <= 84: + analyser._detection_cache[cache_key] = (now, True) + return True + except Exception: + continue + except Exception: + pass + + # OCR fallback (lighter version of original implementation) + try: + try: + min_interval = float(getattr(analyser, "detail_ocr_check_min_interval_seconds", 8.0) or 0.0) + except Exception: + min_interval = 8.0 + last = float(getattr(analyser, "_last_detail_ocr_check_ts", 0.0) or 0.0) + if min_interval > 0 and (now - last) < min_interval: + analyser._detection_cache[cache_key] = (now, False) + return False + analyser._last_detail_ocr_check_ts = now + + analyser.cut_pic(306, 2030, 780, 2110, "", "参与按钮") + t_btn = str(analyser.operation.analyse_pic_word("参与按钮", 0) or "") + keywords = ("参与", "评论", "还需看播", "无法参与", "时长不足", "粉丝团", "开始观看") + if not t_btn or not any(k in t_btn for k in keywords): + t_btn = str(analyser.operation.analyse_pic_word("参与按钮", 1) or "") + if any(k in t_btn for k in keywords): + analyser._detection_cache[cache_key] = (now, True) + return True + except Exception: + pass + + analyser._detection_cache[cache_key] = (now, False) + return False + diff --git a/douyin_flow_control.py b/douyin_flow_control.py new file mode 100644 index 0000000..6b8dc3a --- /dev/null +++ b/douyin_flow_control.py @@ -0,0 +1,199 @@ +from __future__ import annotations + +""" +Flow control main helpers (本地模块化实现,基础版) +================================================ + +当前只实现与你"基础抢福袋、不启用预约"相关的核心流程: +- handle_stage_after_diagnosis:记录阶段信息(暂不做复杂跳转) +- find_and_open_fudai_detail:通过像素检测福袋图标并点击打开详情 +- handle_no_fudai_situation:在没有福袋时做简单的等待/上滑切换 +- filter_fudai_detail:根据 config.json 对福袋进行基础筛选 +""" + +from typing import Any, List, Tuple +import time + +from douyin_detection import check_have_fudai_with_ready_screenshot +from douyin_fudai_core import should_skip_fudai_by_config + + +def handle_stage_after_diagnosis( + analyser: Any, + stage: str, + seen: str, + loop_count: int, +) -> bool: + """记录阶段诊断结果,当前不改变主流程走向。""" + try: + analyser._log_kv( + "流程", + "handle_stage_after_diagnosis", + stage=stage, + seen=seen, + loop_count=loop_count, + ) + except Exception: + pass + return False + + +def find_and_open_fudai_detail( + analyser: Any, + room_pos_ref: List[int], +) -> bool: + """在当前直播间查找福袋图标并尝试点击打开详情(基础版,不做预约)。""" + device_id = getattr(analyser, "device_id", "") + + # 1. 利用像素检测福袋图标的 X 坐标(1080 基准) + x = check_have_fudai_with_ready_screenshot(analyser, screenshot_ready=False) + if not x: + try: + analyser._log_kv("流程", "find_and_open_fudai_detail:未检测到福袋图标", x=int(x or 0)) + except Exception: + pass + return False + + # 点击坐标:用检测到的 X,加一个固定基准 Y(图标所在高度) + try: + rx = int(getattr(analyser, "resolution_ratio_x", 1080) or 1080) + ry = int(getattr(analyser, "resolution_ratio_y", 2400) or 2400) + except Exception: + rx, ry = 1080, 2400 + + base_y = 403 # 与检测时使用的同一水平线附近 + click_x = int(x * rx / 1080) + click_y = int(base_y * ry / 2400) + + try: + analyser._log_kv( + "流程", + "find_and_open_fudai_detail:检测到福袋图标并点击", + fudai_x=int(x), + click_x=click_x, + click_y=click_y, + ) + except Exception: + pass + + # 优先走底层 operation.click,失败再尝试 analyser.click + try: + analyser.operation.click(device_id, click_x, click_y) + analyser.operation.delay(1.0) + return True + except Exception: + try: + analyser.click(x, base_y) + return True + except Exception: + return False + + +def handle_no_fudai_situation( + analyser: Any, + x: int, + swipe_times: int, + wait_times_ref: List[int], + needswitch: bool, + reservation_focus_until_ts: float, + reservations: list, + room_pos: int, + post_switch_delay_s: float, + swipe_up_switch_callback, + swipe_down_back_callback, + sort_reservations_callback, + clear_reservations_callback, + write_state_callback, + back_to_list_callback, + into_list_callback, + reservation_focus_until_ts_ref: List[float], + reset_to_list_after_reservations_ref: List[bool], + swipe_times_ref: List[int], +) -> bool: + """当前直播间没有福袋时的基础处理:稍微等待,然后按需要上滑切换。""" + try: + analyser._log_kv( + "流程", + "handle_no_fudai_situation", + x=x, + swipe_times=swipe_times, + room_pos=room_pos, + reservations=len(reservations), + ) + except Exception: + pass + + # 简单策略:轻微等待 + 上滑切换 + try: + analyser.operation.delay(1.0) + except Exception: + time.sleep(1.0) + + if needswitch and swipe_up_switch_callback: + swipe_up_switch_callback() + try: + analyser.operation.delay(post_switch_delay_s or 1.2) + except Exception: + time.sleep(post_switch_delay_s or 1.2) + + return False + + +def filter_fudai_detail( + analyser: Any, + detail: Tuple, + x: int, + needswitch: bool, + post_switch_delay_s: float, + close_detail_callback, + swipe_up_switch_callback, + add_reservation_callback, +) -> bool: + """福袋详情过滤逻辑:根据 config.json 中的配置决定是否丢弃该福袋。 + + 返回: + True 表示"已丢弃/已处理",上层不再参与; + False 表示"不过滤",可继续参与抽奖。 + """ + skip, reason = should_skip_fudai_by_config(analyser, detail) + try: + content = str(detail[0] or "") if isinstance(detail, tuple) and len(detail) >= 1 else "" + analyser._log_kv( + "流程", + "filter_fudai_detail", + x=x, + needswitch=needswitch, + skip=int(bool(skip)), + reason=reason, + content_preview=content[:60] if content else "", + ) + except Exception: + pass + + if not skip: + # 返回 False 表示"不丢弃",保留该福袋 + return False + + # 需要丢弃:先关闭详情 + try: + close_detail_callback(analyser) + except Exception: + try: + analyser.operation.click_back(analyser.device_id) + except Exception: + pass + + # 如允许切换,则顺便切到下一个直播间 + if needswitch and swipe_up_switch_callback: + try: + swipe_up_switch_callback() + analyser.operation.delay(post_switch_delay_s or 1.2) + except Exception: + try: + time.sleep(post_switch_delay_s or 1.2) + except Exception: + pass + return True + + return False + diff --git a/douyin_fudai.py b/douyin_fudai.py index 47bde78..1665754 100644 --- a/douyin_fudai.py +++ b/douyin_fudai.py @@ -1,5937 +1,601 @@ -import os -import sys -import time -from PIL import Image -from datetime import datetime -from Underlying_Operations import underlying_operations -import json -import re -import shutil -import random -import hashlib -import difflib +from __future__ import annotations """ - V3.3.1 版本 - """ +本地完整版 douyin_fudai(模块化调度器) +====================================== +目标: +- 不再依赖外部 axf 目录; +- 保持 `from douyin_fudai import fudai_analyse` 导入方式不变; +- 将核心逻辑拆分到各子模块,仅在此做“组装 + 调度”。 +""" -def normalize_countdown_text(text: str) -> str: - if not text: - return '' - t = re.sub(r"\s+", "", str(text)) - t = t.replace(':', ':') - # 常见 OCR 混淆纠正(只做轻量替换,避免影响其它文字) - t = t.translate(str.maketrans({ - 'O': '0', 'o': '0', 'Q': '0', 'D': '0', - 'I': '1', 'l': '1', '|': '1', '!': '1', - 'S': '5', 's': '5', - 'B': '8', - 'G': '6', - 'Z': '2', - })) +from typing import Any, List, Tuple +import os +import time - # 中文:x分y秒 / y秒 - m = re.search(r"(\d{1,2})分(\d{1,2})秒", t) - if m: - mm = int(m.group(1)) - ss = int(m.group(2)) - if ss >= 60: - mm += ss // 60 - ss = ss % 60 - return f"{mm:02d}:{ss:02d}" - m = re.search(r"(\d{1,3})秒", t) - if m: - ss = int(m.group(1)) - mm = ss // 60 - ss = ss % 60 - return f"{mm:02d}:{ss:02d}" - # 标准样式:11:37后开奖 / 11:37后开奖 - m = re.search(r"(\d{1,2})[::](\d{2}).*后开奖", t) - if m: - mm = int(m.group(1)) - ss = int(m.group(2)) - # 若分秒识别反了(例如 53:08 实际应为 08:53),优先选择 <= 15 分钟的解释 - if (mm * 60 + ss) > 900 and (ss * 60 + mm) <= 900: - mm, ss = ss, mm - return f"{mm:02d}:{ss:02d}后开奖" - # 识别错序:54后开奖04 - m = re.search(r"(\d{1,2})后开奖(\d{2})", t) - if m: - mm = int(m.group(1)) - ss = int(m.group(2)) - if (mm * 60 + ss) > 900 and (ss * 60 + mm) <= 900: - mm, ss = ss, mm - return f"{mm:02d}:{ss:02d}后开奖" - # 纯数字 1137 / 5404 - digits = ''.join(ch for ch in t if ch.isdigit()) - if len(digits) == 4: - a = int(digits[:2]) - b = int(digits[2:]) +from Underlying_Operations import underlying_operations - # 生成两种解释:mm:ss 以及交换后的 mm:ss - mm1, ss1 = a, b - mm2, ss2 = b, a - - total1 = mm1 * 60 + ss1 - total2 = mm2 * 60 + ss2 - - # 默认相信“从左到右”的顺序:前两位=分,后两位=秒。 - # 只有在明显异常(>15分钟)或秒数不合法时才交换。 - if ss1 >= 60 and ss2 < 60: - mm, ss = mm2, ss2 - elif ss2 >= 60 and ss1 < 60: - mm, ss = mm1, ss1 - elif total1 > 900 and total2 <= 900: - mm, ss = mm2, ss2 - elif total2 > 900 and total1 <= 900: - mm, ss = mm1, ss1 - else: - mm, ss = mm1, ss1 - - return f"{mm:02d}:{ss:02d}" - # 3 位数字:934 => 09:34 - if len(digits) == 3: - mm = int(digits[0]) - ss = int(digits[1:]) - if ss >= 60: - # 尝试 15:09(OCR 丢 0) - mm2 = int(digits[:2]) - ss2 = int(digits[2]) - if ss2 < 60: - return f"{mm2:02d}:{ss2:02d}" - mm += ss // 60 - ss = ss % 60 - return f"{mm:02d}:{ss:02d}" - # 2 位数字:31 => 00:31(更符合临近开奖) - if len(digits) == 2: - return f"00:{int(digits):02d}" - return t - - -def extract_prize_value_yuan(text: str) -> float: - if not text: - return 0.0 - t = re.sub(r"\s+", "", str(text)) - # 先去掉倒计时类数字,避免把 00:31 解析成 31 元 - t = re.sub(r"\b\d{1,2}[::]\d{2}\b", "", t) - - # 优先匹配带币种符号/单位的金额:参考价值¥199 / ¥199.9 / ¥199 / 199元 - currency_matches = re.findall(r"[¥¥](\d+(?:\.\d+)?)", t) - yuan_matches = re.findall(r"(\d+(?:\.\d+)?)元", t) - tagged = currency_matches + yuan_matches - if tagged: - vals = [] - for n in tagged: - try: - vals.append(float(n)) - except ValueError: - pass - return max(vals) if vals else 0.0 - - # 去掉常见干扰:份数/参与人数 - t = re.sub(r"共\d+份", "", t) - t = re.sub(r"\d+人已参与", "", t) - - # 退化:抓小数 - decimals = re.findall(r"\d+\.\d+", t) - if decimals: - vals = [] - for n in decimals: - try: - vals.append(float(n)) - except ValueError: - pass - return max(vals) if vals else 0.0 - - # 再退化:抓整数 - ints = re.findall(r"\d+", t) - if ints: - vals = [] - for n in ints: - try: - v = int(n) - except ValueError: - continue - if 1 <= v <= 99999: - vals.append(float(v)) - return max(vals) if vals else 0.0 - - return 0.0 - -class Tee(object): - """重写print的函数""" - - def __init__(self, *files): - self.files = files - - def write(self, obj): - for f in self.files: - f.write(obj) - f.flush() - - def flush(self): - for f in self.files: - f.flush() +import douyin_stage +import douyin_detection +import douyin_fudai_detail +import douyin_fudai_core +import douyin_flow_control +import douyin_live_room +import douyin_lottery +import douyin_popups +import douyin_robot +import douyin_swipe_ops +import douyin_text_utils +import douyin_utils +import douyin_yanghao +import douyin_pixel class fudai_analyse: - """福袋抽奖相关操作类""" + """福袋抽奖相关操作类(本地模块化实现,保留原有属性与入口)。""" - def __init__(self): - self.device_id = 'XXXXXXXXX' - self.y_pianyi = 0 # 应用于不同型号手机,图标相对屏幕的高度位置有偏差 - self.resolution_ratio_x = 1080 - self.resolution_ratio_y = 2400 - # OCR结果缓存:避免短时间内重复识别相同区域 - self._ocr_cache: dict[str, tuple[float, str]] = {} # key: (picname, change_color), value: (timestamp, result) - self._ocr_cache_ttl: float = 2.0 # 缓存有效期(秒) - # 检测结果缓存 - self._detection_cache: dict[str, tuple[float, object]] = {} # key: method_name, value: (timestamp, result) - self._detection_cache_ttl: float = 1.0 # 检测缓存有效期(秒) - # 预约队列状态文件(用于 Web GUI 展示;子进程写入,Web GUI 进程读取) - self._reservations_state_path = os.path.join(os.path.dirname(__file__), "state", "reservations.json") - # 让终端输出更“整行、实时”(避免看起来空白/零散) - try: - sys.stdout.reconfigure(encoding='utf-8', line_buffering=True) - except Exception: - pass - try: - sys.stderr.reconfigure(encoding='utf-8', line_buffering=True) - except Exception: - pass - # 可通过环境变量关闭 Tee 重定向(例如 Web GUI 统一收集日志时) - if not str(os.environ.get("NO_TEE_STDOUT", "")).strip(): - # 统一日志文件(默认 logs/unified.log),便于长期追踪与 grep - base_dir = os.path.dirname(__file__) - cfg = {} - try: - cfg_path = os.path.join(base_dir, "config.json") - if os.path.exists(cfg_path): - with open(cfg_path, "r", encoding="utf-8") as f: - cfg = json.load(f) if f.readable() else {} - except Exception: - cfg = {} + def __init__(self) -> None: + # 设备与分辨率 + self.device_id: str = "XXXXXXXXX" + self.y_pianyi: int = 0 + self.resolution_ratio_x: int = 1080 + self.resolution_ratio_y: int = 2400 - enabled = True - try: - enabled = bool(cfg.get("log_unified_enabled", True)) - except Exception: - enabled = True - - if enabled: - rel = str(cfg.get("log_unified_path") or "logs/unified.log") - log_path = rel if os.path.isabs(rel) else os.path.join(base_dir, rel) - try: - os.makedirs(os.path.dirname(log_path), exist_ok=True) - except Exception: - pass - # 使用 utf-8-sig:文件首次创建时写入 BOM,避免 Windows PowerShell 误按 ANSI 读取导致中文乱码 - log_file = open(log_path, 'a', encoding='utf-8-sig', errors='ignore') - else: - # 兼容:若禁用统一日志,则按旧逻辑写一个时间戳文件 - timepic = datetime.now().strftime('%Y-%m-%d-%H-%M') - log_file = open(timepic + '.log', 'a', encoding='utf-8-sig', errors='ignore') - - sys.stdout = Tee(sys.stdout, log_file) - sys.stderr = Tee(sys.stderr, log_file) - - # 结构化日志:本次运行唯一 id + 递增序号(便于 Web GUI 里按 rid/seq 定位) - try: - self._run_id = datetime.now().strftime('%Y%m%d%H%M%S') - except Exception: - self._run_id = str(int(time.time())) - self._log_seq = 0 - self.last_find_fudai_time = 0.0 - self.last_refresh_zhibo_list_time = 0.0 - # 进入直播间计时:用于统计“进入直播间后找到福袋图标耗时” - self._enter_live_ts = 0.0 - self._enter_live_reason = "" - self._enter_live_fudai_logged = False - # 无福袋“看门狗”:超时后回到列表重进直播。用户要求先整体关闭,后续再调整。 - self.no_fudai_watchdog_enabled = False + # 运行配置(只保留与你当前需求直接相关的主流程字段,细节统一放在各子模块内部) self.operation = underlying_operations() self.config_path = "config.json" - self.contains_not_want = [] - self.contains_want = [] - self.min_prize_value_yuan = 0.0 # 小于该价值(元)则不参与,0 表示不启用 - self.min_participants = 0 # 参与人数小于该值则不参与,0 表示不启用 - self.max_participants = 0 # 参与人数大于该值则不参与,0 表示不启用 - self.skip_if_countdown_lt_seconds = 15 # 倒计时小于该秒数则不参与(仅 needswitch=True 时生效) - # 切换直播间计数:当上划切换达到阈值后,在当前直播间页面下滑回退到第一个直播间 - self.reset_after_swipes_enabled = False # 由 Web/CLI 显式开关 - self.reset_after_swipes = 10 # 达到阈值次数后回退,需启用开关后生效 + # 日志相关字段:沿用原 fudai1.py 的 _log_kv 实现 + from 原始代码.fudai1 import fudai_analyse as _Orig # type: ignore - # 高价值福袋:预约参与(避免在倒计时很长时一直卡在直播间等待) - self.high_value_fudai_enabled = False - self.high_value_fudai_threshold_yuan = 1000.0 - self.high_value_fudai_join_ahead_seconds = 120 # 开奖前 N 秒回到该直播间并参与 - self.high_value_fudai_max_swipe_back = 60 # 为防止回滑过远导致异常,限制最多回退次数 - self.high_value_fudai_max_reservations = 5 # 最多记录多少个高价值福袋预约 - # 完成某个预约福袋后动作:stay=停留当前直播间;continue=继续执行抢福袋 - self.high_value_fudai_after_action = "continue" - self.high_value_fudai_after_stay_seconds = 120 + # 直接复用原始实现中的 _log_kv,以保持统一格式 + self._run_id = getattr(_Orig(), "_run_id", str(int(time.time()))) + self._log_seq = 0 + self._log_kv = _Orig._log_kv.__get__(self, fudai_analyse) # type: ignore[attr-defined] - # 高价值直播间“回访”:曾经记录过高价值福袋的直播间,每隔一段时间回去看一眼是否出现新福袋。 - # 优先级:预约参与(最高) > 回访(中) > 普通找福袋(低) - self.high_value_room_revisit_enabled = True - self.high_value_room_revisit_interval_seconds = 300 # 默认 5 分钟 - self.high_value_room_revisit_watch_window_seconds = 900 # 默认仅在 15 分钟观察窗内回访 - self.high_value_room_revisit_skip_if_reservation_within_seconds = 120 # 若离预约参与窗口过近则跳过回访 - self.high_value_room_revisit_only_current_run = False # 若为 True,则仅回访本次运行记录的直播间 - # 预约回退校验开关:用于在运行时决定是否做回退后详细校验(可通过 Run 面板控制) - self.reservation_back_verify_enabled = True + # 进入直播间后诊断与阶段流转所需的一些状态 + self._last_diag_stage: str = "INIT" + self._last_diag_seen: str = "-" + self._last_diag_ts: float = 0.0 + + # 与配置相关的核心字段(只初始化最关键的几项,其余保持默认) + self.contains_not_want: list[str] = [] + self.contains_want: list[str] = [] + self.min_prize_value_yuan: float = 0.0 + self.min_participants: int = 0 + self.max_participants: int = 0 + self.skip_if_countdown_lt_seconds: int = 15 + self.no_fudai_watchdog_enabled: bool = False + # 福袋图标检测节流相关默认值 + # 实际识别到福袋一般需要 4–6 秒,这里取中间值 5 秒作为默认上限,具体值可在 GUI / config.json 中调整 + # 注意:已改为使用时间限制(fudai_icon_max_wait_seconds),不再使用尝试次数限制 + self.fudai_icon_retry_delay_seconds: float = 0.6 + self.fudai_icon_max_wait_seconds: float = 5.0 + # fudai_find_max_attempts 已废弃,保留仅为兼容性,实际不再使用 + self.fudai_find_max_attempts: int = 10 + self.screenshot_diagnose_min_interval_seconds: float = 8.0 - # 轮询策略:在预计开奖前多少秒开始积极轮询结果(默认 10 秒) - self.poll_before_open_seconds = 10 - # 预约抢占最小价值:低于该价值的预约不抢占当前任务(元,默认0表示任何预约可抢占) - self.reservation_preempt_min_value_yuan = 0.0 + # 直播间检测阈值(模板匹配阈值,0.0~1.0,默认0.8) + self.live_room_match_threshold: float = 0.8 - # 详情页识别兜底(参与按钮 OCR)节流 - self.detail_ocr_check_min_interval_seconds = 8.0 - - # 福袋详情识别异常(时间/价值)时:关闭重开后延迟再截图的秒数 - self.fudai_abnormal_reopen_delay_seconds = 1.2 - - # 定时禁抢:凌晨时段不抢福袋,仅持续养号 - self.fudai_quiet_hours_enabled = True - self.fudai_quiet_start_hour = 2 - self.fudai_quiet_end_hour = 7 - - # 运行中动态加载配置(网页端保存 config.json 后可生效) - self._last_config_reload_ts = 0.0 - - # 按需求:只保留“推荐页养号流程”(纯坐标点击),不再提供“推荐/直播/进入直播间”文本识别流程。 - # 养号总开关:关闭时不执行推荐页养号(只原地等待) - self.yanghao_enabled = True - # 推荐页养号:可配置的“时长/间隔(冷却)” - self.yanghao_recommend_duration_seconds = 60 - self.yanghao_recommend_interval_seconds = 0 # 0=不限制(每次触发都可执行) - self._yanghao_last_recommend_ts = 0.0 - - def _log_kv(self, *args, **fields): - """统一日志输出:保留 [tag] 前缀,同时提供中文 key=value 字段,方便 grep/debug。 - - 兼容性说明:有些地方可能通过 kwargs 传入名为 'tag' 或 'msg' 的键, - 为避免出现 "multiple values for argument 'tag'" 错误,这里优先使用位置参数, - 并在必要时从 fields 中移除重复键。 - """ - # 解析位置参数/关键字,位置参数优先 - tag = None - msg = None - if len(args) >= 1: - tag = args[0] - if len(args) >= 2: - msg = args[1] - # 若 kwargs 中包含 'tag'/'msg',且位置参数未提供,则取 kwargs 的值;若位置参数已提供,则删除以避免重复 - if 'tag' in fields: - if tag is None: - tag = fields.pop('tag') - else: - # 删除以避免后续处理将其误当作字段 - fields.pop('tag', None) - if 'msg' in fields: - if msg is None: - msg = fields.pop('msg') - else: - fields.pop('msg', None) - - try: - self._log_seq += 1 - except Exception: - self._log_seq = 1 - - key_map = { - # 通用 - "rid": "运行", - "seq": "序号", - "msg": "说明", - "biaoqian": "标签", - "bq": "标签", - "stage": "阶段", - "seen": "识别", - "next": "下一步", - "ok": "成功", - "text": "文本", - "action": "动作", - "result": "结果", - "mode": "模式", - "reason": "原因", - "wait_seconds": "等待秒", - "wait_s": "等待秒", - "remain_to_join_window_s": "距参与窗口秒", - "remain_wait_s": "剩余等待秒", - # 预约 - "value_yuan": "价值元", - "future": "开奖时间", - "pos_seen": "发现位置", - "qsize": "队列数量", - "max_try": "最大尝试次数", - "cap": "队列上限", - "dropped": "丢弃数量", - "dropped_value_yuan": "丢弃价值元", - "dropped_future": "丢弃开奖时间", - "back_times": "需回退次数", - "room_pos": "当前位置", - "target_future": "【目标】开奖时间", - "target_value_yuan": "【目标】价值元", - "target_content": "【目标】内容", - "queue_brief": "【队列】摘要", - "attempt": "尝试次数", - "room_title": "直播间名(清洗后)", - "room_title_raw": "直播间名原文", - "room_title_expected": "【预期】直播间名", - "room_title_current": "【当前】直播间名", - "room_title_ratio": "直播间名相似度", - "room_title_raw_expected": "【预期】直播间名原文", - "room_title_raw_current": "【当前】直播间名原文", - - # 预约回退校验:匹配调试字段(来自 _match_reservation debug_dict) - "expected_future": "【期望】开奖时间戳", - "actual_future": "【识别】开奖时间戳", - "future_diff_s": "开奖时间差秒", - "expected_value": "【期望】价值元", - "actual_value": "【识别】价值元", - "expected_content": "【期望】内容", - "actual_content": "【识别】内容", - # 新增字段映射 - "content": "内容", - "task_count": "任务数", - "countdown": "倒计时", - "min_participants": "最小参与人数", - "max_participants": "最大参与人数", - "min_value_yuan": "最小价值元", - "diag_text": "诊断文本", - "seconds": "耗时秒", - "enter_reason": "进入原因", - "fudai_x": "福袋X坐标", - "participants": "参与人数", - "copies": "份数", - "value_yuan": "价值元", - "keyword": "关键词", - "x": "X坐标", - "y": "Y坐标", - "clicks": "点击次数", - "abnormal": "异常", - "reasons": "原因", - } - - flat = [] - flat.append("{}={}".format(key_map.get("rid", "运行"), getattr(self, "_run_id", "-"))) - flat.append("{}={}".format(key_map.get("seq", "序号"), getattr(self, "_log_seq", 0))) - if msg: - m = str(msg).replace("\r", " ").replace("\n", " ").strip() - if len(m) > 240: - m = m[:240] + "..." - flat.append("{}={}".format(key_map.get("msg", "说明"), m)) - - for k, v in (fields or {}).items(): - if v is None: - continue - s = str(v) - if s == "": - continue - s = s.replace("\r", " ").replace("\n", " ").strip() - if len(s) > 240: - s = s[:240] + "..." - ck = key_map.get(str(k), None) - if not ck: - # 兜底:避免英文 key 出现在日志里 - ck = "字段_{}".format(str(k)) - flat.append("{}={}".format(ck, s)) - - # 获取时间戳(格式:HH:MM:SS) - try: - timestamp = datetime.now().strftime('%H:%M:%S') - except Exception: - timestamp = "" - - # 构建日志行:格式为 [时间] [标签] 消息 字段... - # 如果消息为空,则只显示字段 - log_parts = [] - if timestamp: - log_parts.append(f"[{timestamp}]") - log_parts.append(f"[{tag}]") - - if msg: - m = str(msg).replace("\r", " ").replace("\n", " ").strip() - if len(m) > 200: - m = m[:200] + "..." - log_parts.append(m) - - # 添加字段(使用中文key,格式化值) - for k, v in (fields or {}).items(): - if v is None: - continue - key_cn = key_map.get(str(k), None) - if not key_cn: - # 兜底:避免英文 key 出现在日志里 - key_cn = "字段_{}".format(str(k)) - - # 格式化值:数字保留适当精度,字符串截断 - if isinstance(v, float): - if abs(v) < 1: - v_str = f"{v:.3f}" - elif abs(v) < 100: - v_str = f"{v:.2f}" - else: - v_str = f"{int(v)}" - elif isinstance(v, (int, bool)): - v_str = str(v) - else: - s = str(v).replace("\r", " ").replace("\n", " ").strip() - if len(s) > 100: - s = s[:100] + "..." - v_str = s - - log_parts.append(f"{key_cn}={v_str}") - - # 构建完整日志行 - log_line = " ".join(log_parts) - - # 日志自动换行:每行最多130字符,超过则换行缩进继续输出 - if len(log_line) <= 130: - print(log_line) - else: - # 超长日志:首行显示时间+标签+消息,后续行显示字段 - parts = [] - # 首行:时间 + 标签 + 消息 - header_parts = [] - if timestamp: - header_parts.append(f"[{timestamp}]") - header_parts.append(f"[{tag}]") - if msg: - m = str(msg).replace("\r", " ").replace("\n", " ").strip() - if len(m) > 200: - m = m[:200] + "..." - header_parts.append(m) - parts.append(" ".join(header_parts)) - - # 字段分行显示 - indent = " " # 2个空格缩进 - current_line = indent - - for k, v in (fields or {}).items(): - if v is None: - continue - key_cn = key_map.get(str(k), None) - if not key_cn: - key_cn = "字段_{}".format(str(k)) - - # 格式化值 - if isinstance(v, float): - if abs(v) < 1: - v_str = f"{v:.3f}" - elif abs(v) < 100: - v_str = f"{v:.2f}" - else: - v_str = f"{int(v)}" - elif isinstance(v, (int, bool)): - v_str = str(v) - else: - s = str(v).replace("\r", " ").replace("\n", " ").strip() - if len(s) > 100: - s = s[:100] + "..." - v_str = s - - field_str = f"{key_cn}={v_str}" - - # 检查是否需要换行(考虑缩进) - if len(current_line) + len(field_str) + 1 > 130: - if current_line.strip(): - parts.append(current_line.strip()) - current_line = indent + field_str - else: - if current_line == indent: - current_line += field_str - else: - current_line += " " + field_str - - if current_line.strip() and current_line != indent: - parts.append(current_line.strip()) - - print("\n".join(parts)) - - # 纯坐标点击所需的内部默认坐标(1080x2400 基准,会自动按分辨率缩放) - self.yanghao_fallback_close_x = 1030 - self.yanghao_fallback_close_y = 120 - self.yanghao_fallback_live_x = 900 - self.yanghao_fallback_live_y = 2280 - self.yanghao_fallback_enter_live_x = 109 - self.yanghao_fallback_enter_live_y = 376 - # 关注标签坐标(用于从推荐页面点击顶部“关注”标签) - # 坐标以 1080x2400 分辨率为基准;你提供的矩形为: - # 左上角 (674, 153),右下角 (749, 185),中心点约为 (712, 169) - self.yanghao_follow_tab_x = 712 # 关注标签中心的 x 坐标(1080x2400 基准) - self.yanghao_follow_tab_y = 169 # 关注标签中心的 y 坐标(1080x2400 基准) - - # 新养号动作:停留期间可按概率点爱心/收藏,停留结束后自动滑动到下一个 - self.yanghao_enable_actions = True - self.yanghao_like_prob = 0.15 - self.yanghao_fav_prob = 0.05 - self.yanghao_after_dwell_swipe_direction = "up" # up=下一个内容, down=上一个内容 - self.yanghao_after_dwell_swipe_distance_px = 900 - self.yanghao_like_keywords = ["赞", "喜欢", "Like"] - self.yanghao_fav_keywords = ["收藏", "加入收藏", "取消收藏", "Favorite"] - - # 爱心/收藏图标检测(更适合图标,避免文案/层级变化影响) - # 坐标以 1080x2400 为基准,会按当前分辨率缩放。 - self.yanghao_like_icon_x = 0 - self.yanghao_like_icon_y = 0 - self.yanghao_fav_icon_x = 0 - self.yanghao_fav_icon_y = 0 - # 仅用于“截图检测ROI”的偏移(不影响点击坐标)。用于微调截图中心。 - self.yanghao_like_roi_offset_x = 0 - self.yanghao_like_roi_offset_y = 0 - self.yanghao_fav_roi_offset_x = 0 - self.yanghao_fav_roi_offset_y = 0 - self.yanghao_icon_roi_size = 180 # 截取检测区域边长(px) - self.yanghao_icon_match_threshold = 0.72 - self.yanghao_like_template_path = os.path.join(os.path.dirname(__file__), "assets", "like.png") - self.yanghao_fav_template_path = os.path.join(os.path.dirname(__file__), "assets", "fav.png") - # 桌面图标模板(用于检测是否回到桌面) - self.desktop_icon_template_path = os.path.join(os.path.dirname(__file__), "assets", "desktop.png") - self.desktop_icon_x = 153 - self.desktop_icon_y = 260 - self.desktop_icon_roi_size = 200 - self.desktop_icon_match_threshold = 0.6 - - # 养号逐步截图(调试用,开启后会比较慢/占空间) - self.yanghao_step_screenshot = False - - # “评论/发弹幕”动作:仅在同时检测到爱心+收藏时,按概率触发 - self.yanghao_comment_prob = 0.0 - self.yanghao_comment_btn_x = 981 - self.yanghao_comment_btn_y = 1399 - self.yanghao_comment_input_x = 250 - self.yanghao_comment_input_y = 2218 - self.yanghao_comment_send_x = 906 - self.yanghao_comment_send_y = 1298 - self.yanghao_comment_close_x = 586 - self.yanghao_comment_close_y = 385 - self.yanghao_comment_texts = [] - - self.auto_join_fansclub = False # 是否自动尝试加入粉丝团(可能触发付费/钻石消耗) - self.fansclub_fail_action = "stay" # 粉丝团门槛无法处理时:stay=停留当前直播间,switch=切换下一个 - self.last_attend_fail_reason = "" # 最近一次参与失败原因 - - # 福袋图标检测提速参数(默认更快;可在 config.json 覆盖) - self.fudai_icon_retry_delay_seconds = 0.6 - self.fudai_icon_max_wait_seconds = 4.0 - # 最多尝试寻找福袋图标次数(默认 5,可由 UI 修改) - self.fudai_find_max_attempts = 5 - # 截图阶段诊断(OCR)节流:避免高频截图时反复 OCR 拖慢 - self.screenshot_diagnose_min_interval_seconds = 8.0 - self._last_diag_ts = 0.0 - self._last_diag_stage = "-" - self._last_diag_seen = "-" - - # 福袋详情异常重试预算:避免 OCR 异常时单次卡太久 - self.fudai_detail_retry_budget_seconds = 10.0 + # 初次加载配置 self.load_config() - def load_config(self): - """从配置文件中加载数据""" - if os.path.exists(self.config_path): - with open(self.config_path, "r", encoding="utf-8") as file: - config = json.load(file) - self.contains_not_want = config.get("contains_not_want", []) - self.contains_want = config.get("contains_want", []) - try: - self.min_prize_value_yuan = float(config.get("min_prize_value_yuan", 0) or 0) - except (TypeError, ValueError): - self.min_prize_value_yuan = 0.0 - try: - self.min_participants = int(config.get("min_participants", 0) or 0) - except (TypeError, ValueError): - self.min_participants = 0 - try: - self.max_participants = int(config.get("max_participants", 0) or 0) - except (TypeError, ValueError): - self.max_participants = 0 - try: - self.skip_if_countdown_lt_seconds = int(config.get("skip_if_countdown_lt_seconds", 15) or 15) - except (TypeError, ValueError): - self.skip_if_countdown_lt_seconds = 15 + def load_config(self) -> None: + """从 config.json 加载与福袋筛选/节流相关的关键参数(精简版)。""" + import json + import os - # 无福袋看门狗(30分钟无福袋回列表重进):默认关闭 - try: - self.no_fudai_watchdog_enabled = bool(config.get("no_fudai_watchdog_enabled", False)) - except Exception: - self.no_fudai_watchdog_enabled = False - - # 福袋图标检测提速参数 - try: - self.fudai_icon_retry_delay_seconds = float(config.get("fudai_icon_retry_delay_seconds", self.fudai_icon_retry_delay_seconds) or self.fudai_icon_retry_delay_seconds) - except (TypeError, ValueError): - pass - if self.fudai_icon_retry_delay_seconds < 0.2: - self.fudai_icon_retry_delay_seconds = 0.2 - if self.fudai_icon_retry_delay_seconds > 5: - self.fudai_icon_retry_delay_seconds = 5.0 - try: - self.fudai_icon_max_wait_seconds = float(config.get("fudai_icon_max_wait_seconds", self.fudai_icon_max_wait_seconds) or self.fudai_icon_max_wait_seconds) - except (TypeError, ValueError): - pass - if self.fudai_icon_max_wait_seconds < 0: - self.fudai_icon_max_wait_seconds = 0.0 - if self.fudai_icon_max_wait_seconds > 30: - self.fudai_icon_max_wait_seconds = 30.0 - try: - self.fudai_find_max_attempts = int(config.get("fudai_find_max_attempts", self.fudai_find_max_attempts) or self.fudai_find_max_attempts) - except (TypeError, ValueError): - pass - if self.fudai_find_max_attempts < 1: - self.fudai_find_max_attempts = 1 - if self.fudai_find_max_attempts > 50: - self.fudai_find_max_attempts = 50 - - # 截图阶段诊断(OCR)节流 - try: - self.screenshot_diagnose_min_interval_seconds = float( - config.get("screenshot_diagnose_min_interval_seconds", self.screenshot_diagnose_min_interval_seconds) - or self.screenshot_diagnose_min_interval_seconds - ) - except (TypeError, ValueError): - pass - if self.screenshot_diagnose_min_interval_seconds < 0: - self.screenshot_diagnose_min_interval_seconds = 0.0 - if self.screenshot_diagnose_min_interval_seconds > 60: - self.screenshot_diagnose_min_interval_seconds = 60.0 - - try: - self.reset_after_swipes_enabled = bool(config.get("reset_after_swipes_enabled", False)) - except Exception: - self.reset_after_swipes_enabled = False - try: - raw_reset_swipes = config.get("reset_after_swipes", 10) - self.reset_after_swipes = int(10 if raw_reset_swipes is None else raw_reset_swipes) - except (TypeError, ValueError): - self.reset_after_swipes = 10 - # 兼容旧配置:若未声明开关但阈值大于0,则自动视为开启 - if not config.get("reset_after_swipes_enabled", None) and self.reset_after_swipes > 0: - self.reset_after_swipes_enabled = True - if self.reset_after_swipes < 1: - self.reset_after_swipes = 1 - - # 高价值福袋预约 - try: - self.high_value_fudai_enabled = bool(config.get("high_value_fudai_enabled", False)) - except Exception: - self.high_value_fudai_enabled = False - try: - self.high_value_fudai_threshold_yuan = float(config.get("high_value_fudai_threshold_yuan", 1000.0) or 1000.0) - except (TypeError, ValueError): - self.high_value_fudai_threshold_yuan = 1000.0 - try: - self.high_value_fudai_join_ahead_seconds = int(config.get("high_value_fudai_join_ahead_seconds", 120) or 120) - except (TypeError, ValueError): - self.high_value_fudai_join_ahead_seconds = 120 - try: - self.high_value_fudai_max_swipe_back = int(config.get("high_value_fudai_max_swipe_back", 60) or 60) - except (TypeError, ValueError): - self.high_value_fudai_max_swipe_back = 60 - - try: - self.high_value_fudai_max_reservations = int(config.get("high_value_fudai_max_reservations", 5) or 5) - except (TypeError, ValueError): - self.high_value_fudai_max_reservations = 5 - if self.high_value_fudai_max_reservations < 1: - self.high_value_fudai_max_reservations = 1 - if self.high_value_fudai_max_reservations > 50: - self.high_value_fudai_max_reservations = 50 - - try: - self.high_value_fudai_after_action = str(config.get("high_value_fudai_after_action", "continue") or "continue").strip().lower() - except Exception: - self.high_value_fudai_after_action = "continue" - if self.high_value_fudai_after_action not in ("stay", "continue"): - self.high_value_fudai_after_action = "continue" - try: - self.high_value_fudai_after_stay_seconds = int(config.get("high_value_fudai_after_stay_seconds", 120) or 120) - except (TypeError, ValueError): - self.high_value_fudai_after_stay_seconds = 120 - if self.high_value_fudai_after_stay_seconds < 0: - self.high_value_fudai_after_stay_seconds = 0 - if self.high_value_fudai_after_stay_seconds > 3600: - self.high_value_fudai_after_stay_seconds = 3600 - - # 高价值直播间回访 - try: - self.high_value_room_revisit_enabled = bool(config.get("high_value_room_revisit_enabled", self.high_value_room_revisit_enabled)) - except Exception: - pass - try: - self.reservation_back_verify_enabled = bool(config.get("reservation_back_verify_enabled", True)) - except Exception: - self.reservation_back_verify_enabled = True - try: - self.reservation_preempt_min_value_yuan = float(config.get("reservation_preempt_min_value_yuan", self.reservation_preempt_min_value_yuan) or self.reservation_preempt_min_value_yuan) - except (TypeError, ValueError): - pass - if self.reservation_preempt_min_value_yuan < 0: - self.reservation_preempt_min_value_yuan = 0.0 - try: - self.poll_before_open_seconds = int(config.get("poll_before_open_seconds", self.poll_before_open_seconds) or self.poll_before_open_seconds) - except (TypeError, ValueError): - pass - if self.poll_before_open_seconds < 0: - self.poll_before_open_seconds = 0 - try: - self.high_value_room_revisit_interval_seconds = float( - config.get("high_value_room_revisit_interval_seconds", self.high_value_room_revisit_interval_seconds) - or self.high_value_room_revisit_interval_seconds - ) - except (TypeError, ValueError): - pass - if self.high_value_room_revisit_interval_seconds < 60: - self.high_value_room_revisit_interval_seconds = 60.0 - if self.high_value_room_revisit_interval_seconds > 1800: - self.high_value_room_revisit_interval_seconds = 1800.0 - - try: - self.high_value_room_revisit_watch_window_seconds = float( - config.get("high_value_room_revisit_watch_window_seconds", self.high_value_room_revisit_watch_window_seconds) - or self.high_value_room_revisit_watch_window_seconds - ) - except (TypeError, ValueError): - pass - if self.high_value_room_revisit_watch_window_seconds < 60: - self.high_value_room_revisit_watch_window_seconds = 60.0 - if self.high_value_room_revisit_watch_window_seconds > 7200: - self.high_value_room_revisit_watch_window_seconds = 7200.0 - - try: - self.high_value_room_revisit_skip_if_reservation_within_seconds = int( - config.get( - "high_value_room_revisit_skip_if_reservation_within_seconds", - self.high_value_room_revisit_skip_if_reservation_within_seconds, - ) - or self.high_value_room_revisit_skip_if_reservation_within_seconds - ) - except (TypeError, ValueError): - pass - if self.high_value_room_revisit_skip_if_reservation_within_seconds < 0: - self.high_value_room_revisit_skip_if_reservation_within_seconds = 0 - if self.high_value_room_revisit_skip_if_reservation_within_seconds > 1800: - self.high_value_room_revisit_skip_if_reservation_within_seconds = 1800 - - # 详情页 OCR 兜底节流 - try: - self.detail_ocr_check_min_interval_seconds = float( - config.get("detail_ocr_check_min_interval_seconds", self.detail_ocr_check_min_interval_seconds) - or self.detail_ocr_check_min_interval_seconds - ) - except (TypeError, ValueError): - pass - if self.detail_ocr_check_min_interval_seconds < 0: - self.detail_ocr_check_min_interval_seconds = 0.0 - if self.detail_ocr_check_min_interval_seconds > 60: - self.detail_ocr_check_min_interval_seconds = 60.0 - - # 福袋详情异常(时间/价值)重开延迟 - try: - self.fudai_abnormal_reopen_delay_seconds = float( - config.get("fudai_abnormal_reopen_delay_seconds", 1.2) or 1.2 - ) - except (TypeError, ValueError): - self.fudai_abnormal_reopen_delay_seconds = 1.2 - if self.fudai_abnormal_reopen_delay_seconds < 0: - self.fudai_abnormal_reopen_delay_seconds = 0.0 - if self.fudai_abnormal_reopen_delay_seconds > 10: - self.fudai_abnormal_reopen_delay_seconds = 10.0 - - # 福袋详情异常重试预算 - try: - self.fudai_detail_retry_budget_seconds = float( - config.get("fudai_detail_retry_budget_seconds", self.fudai_detail_retry_budget_seconds) - or self.fudai_detail_retry_budget_seconds - ) - except (TypeError, ValueError): - pass - if self.fudai_detail_retry_budget_seconds < 0: - self.fudai_detail_retry_budget_seconds = 0.0 - if self.fudai_detail_retry_budget_seconds > 60: - self.fudai_detail_retry_budget_seconds = 60.0 - - # 定时禁抢(默认 2:00-7:00) - try: - self.fudai_quiet_hours_enabled = bool(config.get("fudai_quiet_hours_enabled", True)) - except Exception: - self.fudai_quiet_hours_enabled = True - try: - self.fudai_quiet_start_hour = int(config.get("fudai_quiet_start_hour", 2) or 2) - except (TypeError, ValueError): - self.fudai_quiet_start_hour = 2 - try: - self.fudai_quiet_end_hour = int(config.get("fudai_quiet_end_hour", 7) or 7) - except (TypeError, ValueError): - self.fudai_quiet_end_hour = 7 - - # 只保留推荐页养号:忽略旧字段与流程开关 - try: - self.yanghao_enabled = bool(config.get("yanghao_enabled", True)) - except Exception: - self.yanghao_enabled = True - try: - self.yanghao_recommend_duration_seconds = int(config.get("yanghao_recommend_duration_seconds", 60) or 60) - except (TypeError, ValueError): - self.yanghao_recommend_duration_seconds = 60 - try: - self.yanghao_recommend_interval_seconds = int(config.get("yanghao_recommend_interval_seconds", 0) or 0) - except (TypeError, ValueError): - self.yanghao_recommend_interval_seconds = 0 - # 注意:不再从 config 读取“推荐/直播/进入直播间文本”与“兜底坐标”;统一使用代码内默认坐标。 - - self.yanghao_enable_actions = bool(config.get("yanghao_enable_actions", True)) - try: - self.yanghao_like_prob = float(config.get("yanghao_like_prob", 0.15) or 0.15) - except (TypeError, ValueError): - self.yanghao_like_prob = 0.15 - try: - self.yanghao_fav_prob = float(config.get("yanghao_fav_prob", 0.05) or 0.05) - except (TypeError, ValueError): - self.yanghao_fav_prob = 0.05 - self.yanghao_after_dwell_swipe_direction = str( - config.get("yanghao_after_dwell_swipe_direction", "up") or "up" - ).strip().lower() - try: - self.yanghao_after_dwell_swipe_distance_px = int( - config.get("yanghao_after_dwell_swipe_distance_px", 900) or 900 - ) - except (TypeError, ValueError): - self.yanghao_after_dwell_swipe_distance_px = 900 - - lk = config.get("yanghao_like_keywords", ["赞", "喜欢", "Like"]) or ["赞", "喜欢", "Like"] - fk = config.get("yanghao_fav_keywords", ["收藏", "加入收藏", "取消收藏", "Favorite"]) or ["收藏", "加入收藏", "取消收藏", "Favorite"] - if isinstance(lk, list): - self.yanghao_like_keywords = [str(x) for x in lk if str(x).strip()] - if isinstance(fk, list): - self.yanghao_fav_keywords = [str(x) for x in fk if str(x).strip()] - - # 图标检测配置(可选) - try: - self.yanghao_like_icon_x = int(config.get("yanghao_like_icon_x", 0) or 0) - except (TypeError, ValueError): - self.yanghao_like_icon_x = 0 - try: - self.yanghao_like_icon_y = int(config.get("yanghao_like_icon_y", 0) or 0) - except (TypeError, ValueError): - self.yanghao_like_icon_y = 0 - try: - self.yanghao_fav_icon_x = int(config.get("yanghao_fav_icon_x", 0) or 0) - except (TypeError, ValueError): - self.yanghao_fav_icon_x = 0 - try: - self.yanghao_fav_icon_y = int(config.get("yanghao_fav_icon_y", 0) or 0) - except (TypeError, ValueError): - self.yanghao_fav_icon_y = 0 - - # ROI 偏移(可选) - for k, attr in ( - ("yanghao_like_roi_offset_x", "yanghao_like_roi_offset_x"), - ("yanghao_like_roi_offset_y", "yanghao_like_roi_offset_y"), - ("yanghao_fav_roi_offset_x", "yanghao_fav_roi_offset_x"), - ("yanghao_fav_roi_offset_y", "yanghao_fav_roi_offset_y"), - ): - try: - setattr(self, attr, int(config.get(k, getattr(self, attr)) or getattr(self, attr))) - except (TypeError, ValueError): - pass - try: - self.yanghao_icon_roi_size = int(config.get("yanghao_icon_roi_size", 180) or 180) - except (TypeError, ValueError): - self.yanghao_icon_roi_size = 180 - try: - self.yanghao_icon_match_threshold = float(config.get("yanghao_icon_match_threshold", 0.72) or 0.72) - except (TypeError, ValueError): - self.yanghao_icon_match_threshold = 0.72 - tp_like = str(config.get("yanghao_like_template_path", self.yanghao_like_template_path) or self.yanghao_like_template_path) - tp_fav = str(config.get("yanghao_fav_template_path", self.yanghao_fav_template_path) or self.yanghao_fav_template_path) - base_dir = os.path.dirname(__file__) - if tp_like and (not os.path.isabs(tp_like)): - tp_like = os.path.normpath(os.path.join(base_dir, tp_like)) - if tp_fav and (not os.path.isabs(tp_fav)): - tp_fav = os.path.normpath(os.path.join(base_dir, tp_fav)) - self.yanghao_like_template_path = tp_like - self.yanghao_fav_template_path = tp_fav - - # 逐步截图开关(可选) - try: - self.yanghao_step_screenshot = bool(config.get("yanghao_step_screenshot", False)) - except Exception: - self.yanghao_step_screenshot = False - - # 评论动作配置 - try: - self.yanghao_comment_prob = float(config.get("yanghao_comment_prob", 0.0) or 0.0) - except (TypeError, ValueError): - self.yanghao_comment_prob = 0.0 - for k, attr in ( - ("yanghao_comment_btn_x", "yanghao_comment_btn_x"), - ("yanghao_comment_btn_y", "yanghao_comment_btn_y"), - ("yanghao_comment_input_x", "yanghao_comment_input_x"), - ("yanghao_comment_input_y", "yanghao_comment_input_y"), - ("yanghao_comment_send_x", "yanghao_comment_send_x"), - ("yanghao_comment_send_y", "yanghao_comment_send_y"), - ("yanghao_comment_close_x", "yanghao_comment_close_x"), - ("yanghao_comment_close_y", "yanghao_comment_close_y"), - ): - try: - setattr(self, attr, int(config.get(k, getattr(self, attr)) or getattr(self, attr))) - except (TypeError, ValueError): - pass - - ct = config.get("yanghao_comment_texts", []) or [] - if isinstance(ct, list): - self.yanghao_comment_texts = [str(x).strip() for x in ct if str(x).strip()] - self.auto_join_fansclub = bool(config.get("auto_join_fansclub", False)) - self.fansclub_fail_action = str(config.get("fansclub_fail_action", "stay") or "stay").lower() - - def _maybe_reload_config(self, min_interval_seconds: float = 2.0) -> None: - """运行中定期从 config.json 重新加载配置,便于网页端随时修改。""" + path = getattr(self, "config_path", "config.json") try: - now = time.time() - if (now - float(self._last_config_reload_ts or 0.0)) < float(min_interval_seconds or 0.0): + if not os.path.exists(path): return - self._last_config_reload_ts = now - self.load_config() + with open(path, "r", encoding="utf-8") as f: + config = json.load(f) + except Exception: + return + + try: + self.contains_not_want = list(config.get("contains_not_want", []) or []) + except Exception: + self.contains_not_want = [] + try: + self.contains_want = list(config.get("contains_want", []) or []) + except Exception: + self.contains_want = [] + + def _float(name: str, default: float) -> float: + try: + return float(config.get(name, default) or default) + except Exception: + return default + + def _int(name: str, default: int) -> int: + try: + return int(config.get(name, default) or default) + except Exception: + return default + + self.min_prize_value_yuan = _float("min_prize_value_yuan", self.min_prize_value_yuan) + self.min_participants = _int("min_participants", self.min_participants) + self.max_participants = _int("max_participants", self.max_participants) + self.skip_if_countdown_lt_seconds = _int("skip_if_countdown_lt_seconds", self.skip_if_countdown_lt_seconds) + + try: + self.no_fudai_watchdog_enabled = bool(config.get("no_fudai_watchdog_enabled", self.no_fudai_watchdog_enabled)) except Exception: pass - def _mark_enter_live(self, reason: str = "") -> None: - """标记一次“已进入直播间”,用于统计后续找到福袋图标的耗时。""" - try: - self._enter_live_ts = float(time.time()) - except Exception: - self._enter_live_ts = 0.0 - try: - self._enter_live_reason = str(reason or "") - except Exception: - self._enter_live_reason = "" - self._enter_live_fudai_logged = False + self.fudai_icon_retry_delay_seconds = _float( + "fudai_icon_retry_delay_seconds", + self.fudai_icon_retry_delay_seconds, + ) + self.fudai_icon_max_wait_seconds = _float( + "fudai_icon_max_wait_seconds", + self.fudai_icon_max_wait_seconds, + ) + self.fudai_find_max_attempts = _int( + "fudai_find_max_attempts", + self.fudai_find_max_attempts, + ) + self.screenshot_diagnose_min_interval_seconds = _float( + "screenshot_diagnose_min_interval_seconds", + self.screenshot_diagnose_min_interval_seconds, + ) + self.live_room_match_threshold = _float( + "live_room_match_threshold", + self.live_room_match_threshold, + ) + # 确保阈值在合理范围内 + if self.live_room_match_threshold < 0.0: + self.live_room_match_threshold = 0.0 + if self.live_room_match_threshold > 1.0: + self.live_room_match_threshold = 1.0 - def _in_quiet_hours(self, hour: int) -> bool: - """判断当前小时是否处于禁抢时段(支持跨天区间)。""" + # ========== 兼容旧入口:主循环 ========== + def fudai_choujiang(self, device_id: str = "", y_pianyi: int = 0, needswitch: bool = False, wait_minutes: int = 15) -> None: + """兼容原 fudai1.fudai_choujiang 的主入口(当前实现为精简版:仅基础抢福袋)。""" + self.device_id = device_id or self.device_id + self.y_pianyi = int(y_pianyi or 0) try: - h = int(hour) + rx, ry = self.operation.get_device_resolution(self.device_id) + self.resolution_ratio_x, self.resolution_ratio_y = int(rx or 1080), int(ry or 2400) except Exception: - return False + self.resolution_ratio_x, self.resolution_ratio_y = 1080, 2400 + + self._log_kv( + "启动", + "fudai_choujiang 开始执行(基础版,仅抢当前直播间福袋,不含预约/高价值房间)", + 分辨率=f"{self.resolution_ratio_x}x{self.resolution_ratio_y}", + needswitch=int(bool(needswitch)), + wait_minutes=int(wait_minutes), + ) + + # 基础循环:在限定时间内反复执行单轮逻辑 + end_ts = time.time() + max(1, int(wait_minutes)) * 60 + while time.time() < end_ts: + self.run_once_basic() + # 为避免过于频繁截图,增加少量间隔 + try: + self.operation.delay(1.0) + except Exception: + time.sleep(1.0) + + # ========== 阶段诊断 ========== + def _diagnose_stage_from_current_screen(self) -> Tuple[str, str]: + """封装到子模块的阶段诊断入口。""" + return douyin_stage.diagnose_stage_from_current_screen(self) + + # ========== 截图 / 裁剪 / 图标检测(供阶段诊断等调用) ========== + def cut_pic( + self, + x_top: int = 1, + y_top: int = 1, + x_bottom: int = 2, + y_bottom: int = 2, + target: str = "", + cut_pic_name: str = "", + y_pianyi: int = 0, + ) -> None: + """裁剪图片:保持与原 fudai1.cut_pic 相同的坐标语义(1080x2400 基准)。""" try: - start = int(self.fudai_quiet_start_hour) - end = int(self.fudai_quiet_end_hour) - except Exception: - start, end = 2, 7 - # 归一化 - start = start % 24 - end = end % 24 - if start == end: - return False - if start < end: - return start <= h < end - # 跨天:例如 22-7 - return (h >= start) or (h < end) - - def _save_step_screenshot(self, label: str) -> str | None: - """保存当前屏幕截图为独立文件,便于你逐步核对是否点对了位置。""" - try: - base_dir = os.path.join(os.path.dirname(__file__), "pic") - os.makedirs(base_dir, exist_ok=True) - - ok = self._shot_and_diagnose("养号截图", "保存逐步截图({})".format(label), self.device_id) - if not ok: - return None - src = os.path.join(base_dir, "screenshot.png") - if not os.path.exists(src): - return None - - safe = re.sub(r"[^0-9A-Za-z\u4e00-\u9fa5_-]+", "_", str(label or "step")) - label_dir = os.path.join(base_dir, safe) - os.makedirs(label_dir, exist_ok=True) - # 同时保存一份带时间戳的历史截图 + 覆盖 latest.png - ts = datetime.now().strftime("%Y%m%d_%H%M%S_%f") - dst_hist = os.path.join(label_dir, f"{ts}.png") - dst_latest = os.path.join(label_dir, "latest.png") - shutil.copyfile(src, dst_hist) - shutil.copyfile(src, dst_latest) - print(f"[养号] 截图已保存:{dst_hist} (latest已更新)") - return dst_hist + x1 = x_top * self.resolution_ratio_x // 1080 + y1 = y_top * self.resolution_ratio_y // 2400 + int(y_pianyi or 0) + x2 = x_bottom * self.resolution_ratio_x // 1080 + y2 = y_bottom * self.resolution_ratio_y // 2400 + int(y_pianyi or 0) + self.operation.cut_pic((x1, y1), (x2, y2), target, cut_pic_name) except Exception as e: - print(f"[养号] 截图保存失败:{e}") - return None + try: + self._log_kv( + "截图", + "cut_pic 失败", + error=str(e), + x_top=x_top, + y_top=y_top, + x_bottom=x_bottom, + y_bottom=y_bottom, + y_pianyi=y_pianyi, + ) + except Exception: + pass - def _scale_from_base(self, x: int, y: int, base_w: int = 1080, base_h: int = 2400) -> tuple[int, int]: + def _read_pixel_stage_state(self) -> dict: + """读取像素阶段状态(用于阶段诊断)。""" + import os + pic_path = os.path.join(os.path.dirname(__file__), "pic", "screenshot.png") + return douyin_pixel.read_pixel_stage_state_from_screenshot(pic_path) + + def _check_in_live_room_by_icon(self) -> Tuple[bool, float]: + """通过右上角关闭/心形图标进行直播间图形识别(轻量模板匹配版)。 + + 返回: + (detected, score) 其中 score 为匹配得分(0.0~1.0,来自 TM_CCOEFF_NORMED)。 + """ + # 为了兼容没有 cv2/numpy 的环境,这里做降级处理 try: - sx = int(int(x) * int(self.resolution_ratio_x) / int(base_w)) - sy = int(int(y) * int(self.resolution_ratio_y) / int(base_h)) - except Exception: - sx, sy = int(x), int(y) - return sx, sy - - def _capture_roi_screenshot(self, label: str, center_x: int, center_y: int, size_px: int) -> str | None: - """截屏并裁剪指定坐标附近 ROI,保存到 pic/