commit 2253a2d7740d610bcf4b090c5a7e8a71c901e566
Author: admin <1051592396@qq.com>
Date: Fri Sep 11 11:19:56 2026 +0800
初始化多平台机器人部署项目 - Telegram/Discord/QQ资源搜索机器人
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..d8ddf89
--- /dev/null
+++ b/README.md
@@ -0,0 +1,125 @@
+# 多平台机器人统一部署指南
+
+## 📁 目录结构
+```
+bots-deploy/
+├── telegram/ # Telegram机器人 (tg-search-bot)
+├── discord/ # Discord机器人
+├── qq/ # QQ机器人 (真寻bot)
+└── README.md # 本文件
+```
+
+## 🚀 部署顺序(推荐)
+
+### 1️⃣ Telegram机器人(最简单,10分钟)
+**项目**:tg-search-bot
+**功能**:AI搜索+磁力链接+PikPak自动保存
+
+#### 部署步骤:
+1. 复制 `F:\开源项目\tg-search-bot` 到服务器 `C:\bots\tg-search-bot`
+2. 创建配置目录:`C:\Users\Administrator\.tg_search_bot\`
+3. 创建配置文件 `config.yaml`:
+```yaml
+tg_chat_id: 你的Telegram用户ID
+tg_bot_token: 你的Bot Token
+use_proxy: 0
+enable_nsfw: 0
+```
+4. 安装依赖:`pip install -r requirements.txt`
+5. 启动:`python bot.py`
+
+#### 获取Bot Token:
+- 找 @BotFather → /newbot → 按提示创建
+- 获取用户ID:找 @userinfobot → 发送任意消息
+
+---
+
+### 2️⃣ Discord机器人(15分钟)
+**项目**:自建基础版(已开发完成)
+**功能**:全局资源搜索+群管理+统计
+
+#### 部署步骤:
+1. 复制 `F:\开源项目\multi-platform-bot\discord-bot` 到服务器 `C:\bots\discord-bot`
+2. 复制 `.env.example` 为 `.env`,填入 `DISCORD_TOKEN`
+3. 安装依赖:`pip install -r requirements.txt`
+4. 启动:`python bot.py` 或双击 `start.bat`
+
+#### 获取Discord Bot Token:
+1. 访问 https://discord.com/developers/applications
+2. 创建新应用 → Bot → Add Bot
+3. 复制 Token
+4. **必须开启** Message Content Intent
+5. OAuth2 → URL Generator → 勾选 bot + applications.commands
+6. 权限:Send Messages、Read Message History、Add Reactions
+7. 打开生成的链接邀请机器人到服务器
+
+---
+
+### 3️⃣ QQ机器人(最复杂,30分钟)
+**项目**:真寻bot (zhenxun_bot)
+**功能**:bt磁力搜索+群管理+娱乐功能,最全面
+
+#### 部署步骤:
+1. 下载真寻bot整合包:https://zhenxun-org.github.io/zhenxun_bot/beginner/
+2. 下载 go-cqhttp 或 NapCatQQ
+3. 配置QQ小号登录
+4. 配置真寻bot连接
+5. 启动
+
+#### 注意事项:
+- ⚠️ 建议用小号,有封号风险
+- ⚠️ 需要保持QQ客户端登录状态
+- bt磁力搜索功能默认开启,私聊使用
+
+---
+
+## 📊 三个机器人对比
+
+| 功能 | Telegram | Discord | QQ |
+|------|----------|---------|-----|
+| 资源搜索 | ✅ AI智能搜索 | ✅ 关键词搜索 | ✅ bt磁力搜索 |
+| 磁力链接 | ✅ | ✅ | ✅ |
+| 自动保存网盘 | ✅ PikPak | ❌ | ❌ |
+| 群管理 | ✅ | ✅ | ✅ |
+| 部署难度 | ⭐ 简单 | ⭐⭐ 中等 | ⭐⭐⭐ 复杂 |
+| 封号风险 | 低 | 低 | ⚠️ 中 |
+| 用户量 | 海外为主 | 海外为主 | 国内最大 |
+
+---
+
+## 🔧 统一管理脚本
+
+### 启动所有机器人(start_all.bat)
+```batch
+@echo off
+echo 启动所有机器人...
+start "Telegram Bot" cmd /k "cd C:\bots\tg-search-bot && python bot.py"
+start "Discord Bot" cmd /k "cd C:\bots\discord-bot && python bot.py"
+echo 所有机器人已启动!
+pause
+```
+
+### 查看机器人状态
+- Telegram:查看日志文件 `~/.tg_search_bot/log.txt`
+- Discord:查看控制台输出
+- QQ:查看真寻bot控制台
+
+---
+
+## ⚠️ 注意事项
+
+1. **首尔服务器是Windows系统**,所有机器人用Python直接运行,不用Docker
+2. **端口冲突**:确保各机器人使用不同端口(如果有Web界面)
+3. **开机自启**:把启动脚本放到 `shell:startup` 目录
+4. **日志管理**:定期清理日志文件,避免占满磁盘
+5. **Token安全**:不要把Token提交到Git,用.env或config.yaml本地配置
+
+---
+
+## 📝 下一步
+
+1. ✅ Telegram机器人:配置Token后即可启动
+2. ⏳ Discord机器人:配置Token后即可启动
+3. ⏳ QQ机器人:需要下载整合包和配置QQ小号
+
+需要我帮你配置哪个机器人的Token?或者先把文件上传到首尔服务器?
diff --git a/deploy_server.bat b/deploy_server.bat
new file mode 100644
index 0000000..7792a55
--- /dev/null
+++ b/deploy_server.bat
@@ -0,0 +1,73 @@
+@echo off
+chcp 65001 >nul
+echo ========================================
+echo 首尔服务器 - 多平台机器人一键部署
+echo ========================================
+echo.
+
+set DEPLOY_DIR=C:\bots
+
+echo [1/5] 创建部署目录...
+if not exist "%DEPLOY_DIR%" mkdir "%DEPLOY_DIR%"
+if not exist "%DEPLOY_DIR%\telegram" mkdir "%DEPLOY_DIR%\telegram"
+if not exist "%DEPLOY_DIR%\discord" mkdir "%DEPLOY_DIR%\discord"
+echo ✅ 目录创建完成
+
+echo.
+echo [2/5] 检查Python环境...
+python --version
+if errorlevel 1 (
+ echo ❌ 未找到Python,请先安装Python 3.9+
+ pause
+ exit /b 1
+)
+echo ✅ Python环境正常
+
+echo.
+echo [3/5] 安装Telegram机器人依赖...
+cd /d "%DEPLOY_DIR%\telegram\tg-search-bot"
+pip install -r requirements.txt
+if errorlevel 1 (
+ echo ⚠️ Telegram依赖安装失败,请手动检查
+) else (
+ echo ✅ Telegram依赖安装完成
+)
+
+echo.
+echo [4/5] 安装Discord机器人依赖...
+cd /d "%DEPLOY_DIR%\discord\discord-bot"
+pip install -r requirements.txt
+if errorlevel 1 (
+ echo ⚠️ Discord依赖安装失败,请手动检查
+) else (
+ echo ✅ Discord依赖安装完成
+)
+
+echo.
+echo [5/5] 创建配置目录...
+set CONFIG_DIR=%USERPROFILE%\.tg_search_bot
+if not exist "%CONFIG_DIR%" mkdir "%CONFIG_DIR%"
+echo ✅ 配置目录创建完成
+
+echo.
+echo ========================================
+echo 部署完成!
+echo ========================================
+echo.
+echo 下一步:
+echo 1. 配置 Telegram Bot:
+echo 编辑 %CONFIG_DIR%\config.yaml
+echo 填入 tg_chat_id 和 tg_bot_token
+echo.
+echo 2. 配置 Discord Bot:
+echo 编辑 %DEPLOY_DIR%\discord\discord-bot\.env
+echo 填入 DISCORD_TOKEN
+echo.
+echo 3. 启动机器人:
+echo 双击 %DEPLOY_DIR%\start_all.bat
+echo.
+echo 获取Token:
+echo - Telegram: 找 @BotFather 创建
+echo - Discord: https://discord.com/developers/applications
+echo.
+pause
diff --git a/discord/.env.example b/discord/.env.example
new file mode 100644
index 0000000..b2f087d
--- /dev/null
+++ b/discord/.env.example
@@ -0,0 +1,18 @@
+# Discord 机器人配置文件
+# 复制为 .env 并填入实际值
+
+# Discord Bot Token(必填)
+# 获取地址:https://discord.com/developers/applications
+DISCORD_TOKEN=your_discord_bot_token_here
+
+# 命令前缀(可选,默认 !)
+COMMAND_PREFIX=!
+
+# 管理员用户ID(可选,多个用逗号分隔)
+ADMIN_IDS=
+
+# 数据库路径(可选,默认 discord_resources.db)
+DATABASE_PATH=discord_resources.db
+
+# 日志级别(可选,默认 INFO)
+LOG_LEVEL=INFO
diff --git a/discord/discord-bot/.env.example b/discord/discord-bot/.env.example
new file mode 100644
index 0000000..9882390
--- /dev/null
+++ b/discord/discord-bot/.env.example
@@ -0,0 +1,5 @@
+# Discord机器人配置
+DISCORD_TOKEN=your_discord_bot_token_here
+
+# 资源数据库路径(默认使用Telegram采集的数据库)
+# RESOURCE_DB_PATH=F:\开源项目\telegram-resource-collector\web_collected.db
diff --git a/discord/discord-bot/bot.py b/discord/discord-bot/bot.py
new file mode 100644
index 0000000..2e4e665
--- /dev/null
+++ b/discord/discord-bot/bot.py
@@ -0,0 +1,436 @@
+"""
+Discord资源搜索机器人 - 独立数据库版
+功能:全局资源搜索、群管理、资源统计、独立数据库
+"""
+import os
+import sys
+import sqlite3
+import discord
+from discord.ext import commands
+from dotenv import load_dotenv
+
+# 加载配置
+load_dotenv()
+DISCORD_TOKEN = os.getenv("DISCORD_TOKEN", "")
+
+# 独立数据库路径(Discord机器人自己的数据库)
+BOT_DIR = os.path.dirname(os.path.abspath(__file__))
+DB_PATH = os.path.join(BOT_DIR, "discord_resources.db")
+
+# 每页显示数量
+PAGE_SIZE = 8
+
+
+# ========== 数据库初始化 ==========
+def init_db():
+ """初始化独立数据库"""
+ conn = sqlite3.connect(DB_PATH)
+ c = conn.cursor()
+
+ # 资源表
+ c.execute("""
+ CREATE TABLE IF NOT EXISTS resources (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ title TEXT NOT NULL,
+ tg_link TEXT DEFAULT '',
+ source TEXT DEFAULT '',
+ keyword TEXT DEFAULT '',
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
+ )
+ """)
+
+ # 搜索记录表
+ c.execute("""
+ CREATE TABLE IF NOT EXISTS search_log (
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
+ user_id INTEGER,
+ keyword TEXT,
+ result_count INTEGER,
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
+ )
+ """)
+
+ # 群配置表
+ c.execute("""
+ CREATE TABLE IF NOT EXISTS group_config (
+ guild_id INTEGER PRIMARY KEY,
+ guild_name TEXT,
+ welcome_enabled INTEGER DEFAULT 1,
+ search_enabled INTEGER DEFAULT 1,
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
+ )
+ """)
+
+ conn.commit()
+ conn.close()
+ print(f"✅ 数据库初始化: {DB_PATH}")
+
+
+# ========== 资源搜索功能 ==========
+def search_resources(keyword, limit=PAGE_SIZE, offset=0):
+ """从独立数据库搜索资源"""
+ if not os.path.exists(DB_PATH):
+ init_db()
+
+ conn = sqlite3.connect(DB_PATH)
+ conn.row_factory = sqlite3.Row
+ c = conn.cursor()
+
+ query = """
+ SELECT id, title, tg_link, source, keyword, created_at
+ FROM resources
+ WHERE title LIKE ? OR keyword LIKE ? OR source LIKE ?
+ ORDER BY (tg_link != '') DESC, created_at DESC
+ LIMIT ? OFFSET ?
+ """
+ like_keyword = f"%{keyword}%"
+ c.execute(query, (like_keyword, like_keyword, like_keyword, limit, offset))
+ results = [dict(row) for row in c.fetchall()]
+
+ c.execute("""
+ SELECT COUNT(*) FROM resources
+ WHERE title LIKE ? OR keyword LIKE ? OR source LIKE ?
+ """, (like_keyword, like_keyword, like_keyword))
+ total = c.fetchone()[0]
+
+ conn.close()
+ return results, total
+
+
+def add_resource(title, tg_link="", source="", keyword=""):
+ """添加资源到数据库"""
+ conn = sqlite3.connect(DB_PATH)
+ c = conn.cursor()
+ c.execute("""
+ INSERT OR IGNORE INTO resources (title, tg_link, source, keyword)
+ VALUES (?, ?, ?, ?)
+ """, (title, tg_link, source, keyword))
+ conn.commit()
+ conn.close()
+
+
+def get_stats():
+ """获取数据库统计"""
+ if not os.path.exists(DB_PATH):
+ init_db()
+
+ conn = sqlite3.connect(DB_PATH)
+ c = conn.cursor()
+
+ c.execute("SELECT COUNT(*) FROM resources")
+ total = c.fetchone()[0]
+
+ c.execute("SELECT COUNT(*) FROM resources WHERE tg_link != ''")
+ with_link = c.fetchone()[0]
+
+ c.execute("SELECT COUNT(*) FROM search_log")
+ search_count = c.fetchone()[0]
+
+ conn.close()
+ return {"total": total, "with_link": with_link, "search_count": search_count}
+
+
+def log_search(user_id, keyword, result_count):
+ """记录搜索日志"""
+ conn = sqlite3.connect(DB_PATH)
+ c = conn.cursor()
+ c.execute("""
+ INSERT INTO search_log (user_id, keyword, result_count)
+ VALUES (?, ?, ?)
+ """, (user_id, keyword, result_count))
+ conn.commit()
+ conn.close()
+
+
+# ========== 格式化输出 ==========
+def format_results(results, keyword, total, page=0):
+ """格式化搜索结果"""
+ lines = []
+ lines.append(f"🔍 搜索「{keyword}」共找到 {total} 条结果")
+ lines.append(f"📄 第 {page+1} 页 / 共 {(total + PAGE_SIZE - 1) // PAGE_SIZE} 页")
+ lines.append("")
+
+ for i, res in enumerate(results, 1):
+ idx = page * PAGE_SIZE + i
+ title = res.get("title", "")[:80]
+ tg_link = res.get("tg_link", "")
+ source = res.get("source", "")
+
+ link_icon = "📎" if tg_link else "🔍"
+ lines.append(f"{idx}. {link_icon} {title}")
+
+ if tg_link:
+ lines.append(f" 🔗 {tg_link}")
+
+ if source:
+ lines.append(f" 📡 来源: {source}")
+
+ lines.append("")
+
+ if total == 0:
+ lines = [f"❌ 未找到与「{keyword}」相关的资源", "", "💡 试试其他关键词"]
+
+ return "\n".join(lines)
+
+
+# ========== Discord机器人配置 ==========
+intents = discord.Intents.default()
+intents.message_content = True
+intents.members = True
+
+bot = commands.Bot(command_prefix='!', intents=intents, help_command=None)
+
+
+# ========== 事件处理 ==========
+@bot.event
+async def on_ready():
+ """机器人启动完成"""
+ init_db()
+ print(f'✅ Discord机器人已登录: {bot.user}')
+ print(f'📊 已连接 {len(bot.guilds)} 个服务器')
+ print(f'💾 数据库: {DB_PATH}')
+ await bot.change_presence(activity=discord.Game(name="资源搜索 | 发关键词自动搜索"))
+
+
+@bot.event
+async def on_guild_join(guild):
+ """加入新服务器"""
+ conn = sqlite3.connect(DB_PATH)
+ c = conn.cursor()
+ c.execute("""
+ INSERT OR IGNORE INTO group_config (guild_id, guild_name)
+ VALUES (?, ?)
+ """, (guild.id, guild.name))
+ conn.commit()
+ conn.close()
+ print(f"➕ 加入新服务器: {guild.name} ({guild.id})")
+
+
+@bot.event
+async def on_member_join(member):
+ """新成员加入欢迎"""
+ # 检查是否启用欢迎
+ conn = sqlite3.connect(DB_PATH)
+ c = conn.cursor()
+ c.execute("SELECT welcome_enabled FROM group_config WHERE guild_id = ?", (member.guild.id,))
+ result = c.fetchone()
+ conn.close()
+
+ if result and result[0] == 0:
+ return
+
+ # 查找欢迎频道
+ welcome_channel = None
+ for channel in member.guild.text_channels:
+ if 'welcome' in channel.name.lower() or '欢迎' in channel.name or 'general' in channel.name.lower():
+ welcome_channel = channel
+ break
+
+ if not welcome_channel and member.guild.text_channels:
+ welcome_channel = member.guild.text_channels[0]
+
+ if welcome_channel:
+ welcome_msg = f"""
+👋 欢迎 **{member.mention}** 加入 **{member.guild.name}**!
+
+📋 本机器人功能:
+• 直接发送关键词即可搜索资源
+• `!search 关键词` - 搜索资源
+• `!stats` - 查看资源库统计
+• `!help` - 查看帮助
+
+💡 试试发送:电影、音乐、软件、游戏
+"""
+ await welcome_channel.send(welcome_msg)
+
+
+# ========== 命令处理 ==========
+@bot.command(name='help')
+async def cmd_help(ctx):
+ """帮助命令"""
+ help_text = """
+📋 **Discord资源搜索机器人帮助**
+
+**🔍 资源搜索:**
+• 直接发送关键词 - 自动搜索资源库
+• `!search 关键词` - 搜索资源
+• `!stats` - 查看资源库统计
+
+**⚙️ 群管理:**
+• `!ping` - 测试机器人状态
+• `!serverinfo` - 查看服务器信息
+• `!welcome on/off` - 开启/关闭欢迎消息
+
+**💡 使用示例:**
+• 发送 `电影` - 搜索电影相关资源
+• 发送 `无损音乐` - 搜索无损音乐
+• 发送 `Adobe` - 搜索Adobe软件
+
+**📊 数据说明:**
+本机器人使用独立数据库,资源持续更新中...
+"""
+ await ctx.send(help_text)
+
+
+@bot.command(name='search')
+async def cmd_search(ctx, *, keyword: str = None):
+ """搜索资源"""
+ if not keyword:
+ await ctx.send("❌ 请输入搜索关键词\n示例:`!search 电影`")
+ return
+
+ await do_search(ctx, keyword)
+
+
+@bot.command(name='stats')
+async def cmd_stats(ctx):
+ """查看资源库统计"""
+ stats = get_stats()
+
+ total = stats['total']
+ with_link = stats['with_link']
+ search_count = stats['search_count']
+ link_percent = (with_link / total * 100) if total > 0 else 0
+
+ stats_text = f"""
+📊 **资源库统计**
+
+• 📦 总资源数:**{total}** 条
+• 🔗 带跳转链接:**{with_link}** 条
+• 📈 链接占比:**{link_percent:.1f}%**
+• 🔍 总搜索次数:**{search_count}** 次
+
+💡 发送关键词即可搜索资源
+"""
+ await ctx.send(stats_text)
+
+
+@bot.command(name='ping')
+async def cmd_ping(ctx):
+ """测试机器人状态"""
+ latency = bot.latency * 1000
+ await ctx.send(f"🏓 Pong! 延迟: {latency:.0f}ms")
+
+
+@bot.command(name='serverinfo')
+async def cmd_serverinfo(ctx):
+ """查看服务器信息"""
+ guild = ctx.guild
+ info = f"""
+🏰 **服务器信息**
+
+• 📛 名称:{guild.name}
+• 👥 成员数:{guild.member_count}
+• 📅 创建时间:{guild.created_at.strftime('%Y-%m-%d')}
+• 💬 频道数:{len(guild.text_channels)}
+• 🔊 语音频道数:{len(guild.voice_channels)}
+"""
+ await ctx.send(info)
+
+
+@bot.command(name='welcome')
+async def cmd_welcome(ctx, action: str = None):
+ """开启/关闭欢迎消息"""
+ if not action or action.lower() not in ['on', 'off']:
+ await ctx.send("❌ 用法:`!welcome on` 或 `!welcome off`")
+ return
+
+ enabled = 1 if action.lower() == 'on' else 0
+ conn = sqlite3.connect(DB_PATH)
+ c = conn.cursor()
+ c.execute("""
+ INSERT OR REPLACE INTO group_config (guild_id, guild_name, welcome_enabled)
+ VALUES (?, ?, ?)
+ """, (ctx.guild.id, ctx.guild.name, enabled))
+ conn.commit()
+ conn.close()
+
+ status = "✅ 已开启" if enabled else "❌ 已关闭"
+ await ctx.send(f"{status} 欢迎消息")
+
+
+# ========== 核心搜索功能 ==========
+async def do_search(ctx, keyword, page=0):
+ """执行搜索并发送结果"""
+ # 显示"正在搜索"
+ search_msg = await ctx.send(f"🔍 正在搜索「{keyword}」...")
+
+ try:
+ # 搜索资源
+ results, total = search_resources(keyword, limit=PAGE_SIZE, offset=page * PAGE_SIZE)
+
+ # 记录搜索日志
+ log_search(ctx.author.id, keyword, total)
+
+ # 格式化结果
+ reply = format_results(results, keyword, total, page=page)
+
+ # 编辑消息
+ await search_msg.edit(content=reply)
+
+ # 分页反应
+ if total > PAGE_SIZE:
+ await search_msg.add_reaction("⬅️")
+ await search_msg.add_reaction("➡️")
+
+ except Exception as e:
+ await search_msg.edit(content=f"❌ 搜索失败:{str(e)}")
+
+
+# ========== 全局消息监听 ==========
+@bot.event
+async def on_message(message):
+ """处理所有消息 - 全局资源搜索"""
+ # 忽略机器人自己的消息
+ if message.author == bot.user:
+ return
+
+ # 处理命令
+ await bot.process_commands(message)
+
+ # 如果是命令,不触发全局搜索
+ if message.content.startswith('!'):
+ return
+
+ # 忽略太短的消息
+ if len(message.content.strip()) < 2:
+ return
+
+ # 忽略包含URL的消息
+ if 'http://' in message.content or 'https://' in message.content:
+ return
+
+ # 只在服务器频道触发全局搜索
+ if message.guild is None:
+ return
+
+ # 检查是否启用搜索
+ conn = sqlite3.connect(DB_PATH)
+ c = conn.cursor()
+ c.execute("SELECT search_enabled FROM group_config WHERE guild_id = ?", (message.guild.id,))
+ result = c.fetchone()
+ conn.close()
+
+ if result and result[0] == 0:
+ return
+
+ # 全局资源搜索
+ keyword = message.content.strip()
+ await do_search(message.channel, keyword)
+
+
+# ========== 主函数 ==========
+def main():
+ """主函数"""
+ if not DISCORD_TOKEN:
+ print("❌ 错误:未配置DISCORD_TOKEN")
+ print("请在.env文件中设置DISCORD_TOKEN")
+ print("获取地址:https://discord.com/developers/applications")
+ return
+
+ print("🚀 正在启动Discord机器人...")
+ bot.run(DISCORD_TOKEN)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/discord/discord-bot/discord_resources.db b/discord/discord-bot/discord_resources.db
new file mode 100644
index 0000000..2b4d848
Binary files /dev/null and b/discord/discord-bot/discord_resources.db differ
diff --git a/discord/discord-bot/requirements.txt b/discord/discord-bot/requirements.txt
new file mode 100644
index 0000000..70ad9a2
--- /dev/null
+++ b/discord/discord-bot/requirements.txt
@@ -0,0 +1,2 @@
+discord.py>=2.3.0
+python-dotenv>=1.0.0
diff --git a/discord/discord-bot/start.bat b/discord/discord-bot/start.bat
new file mode 100644
index 0000000..76812c5
--- /dev/null
+++ b/discord/discord-bot/start.bat
@@ -0,0 +1,46 @@
+@echo off
+chcp 65001 >nul
+echo ========================================
+echo Discord资源搜索机器人 - 启动脚本
+echo ========================================
+echo.
+
+cd /d "%~dp0"
+
+echo [1/3] 检查Python环境...
+python --version
+if errorlevel 1 (
+ echo ❌ 未找到Python,请先安装Python 3.8+
+ pause
+ exit /b 1
+)
+
+echo.
+echo [2/3] 检查依赖...
+pip show discord.py >nul 2>&1
+if errorlevel 1 (
+ echo 正在安装依赖...
+ pip install -r requirements.txt
+) else (
+ echo ✅ 依赖已安装
+)
+
+echo.
+echo [3/3] 检查配置...
+if not exist .env (
+ echo ❌ 未找到.env配置文件
+ echo 请复制 .env.example 为 .env 并填入DISCORD_TOKEN
+ pause
+ exit /b 1
+)
+echo ✅ 配置文件存在
+
+echo.
+echo ========================================
+echo 正在启动Discord机器人...
+echo ========================================
+echo.
+
+python bot.py
+
+pause
diff --git a/start_all.bat b/start_all.bat
new file mode 100644
index 0000000..df4f80c
--- /dev/null
+++ b/start_all.bat
@@ -0,0 +1,24 @@
+@echo off
+chcp 65001 >nul
+echo ========================================
+echo 多平台机器人统一启动脚本
+echo ========================================
+echo.
+
+echo [1/3] 启动 Telegram 机器人...
+start "Telegram Bot" cmd /k "cd /d C:\bots\telegram\tg-search-bot && python bot.py"
+timeout /t 3 /nobreak >nul
+
+echo [2/3] 启动 Discord 机器人...
+start "Discord Bot" cmd /k "cd /d C:\bots\discord\discord-bot && python bot.py"
+timeout /t 3 /nobreak >nul
+
+echo [3/3] QQ 机器人请手动启动(如需)
+echo.
+
+echo ========================================
+echo 所有机器人已启动!
+echo 查看各窗口确认运行状态
+echo ========================================
+echo.
+pause
diff --git a/telegram/config.yaml.example b/telegram/config.yaml.example
new file mode 100644
index 0000000..f15b3d7
--- /dev/null
+++ b/telegram/config.yaml.example
@@ -0,0 +1,26 @@
+# tg-search-bot 配置文件
+# 复制到 C:\Users\Administrator\.tg_search_bot\config.yaml
+
+# 必填,你的 Telegram 用户ID(找 @userinfobot 获取)
+tg_chat_id: 123456789
+
+# 必填,你的 Telegram Bot Token(找 @BotFather 创建)
+tg_bot_token: 123456789:ABCdefGHIjklMNOpqrsTUVwxyz
+
+# 必填,是否启用全局代理,1 是 / 0 否
+use_proxy: 0
+
+# 可选,代理地址(use_proxy 为 1 时必填),如 http://127.0.0.1:7890
+proxy_addr:
+
+# 必填,是否开启 NSFW 内容,1 是 / 0 否
+enable_nsfw: 0
+
+# 可选,Pikpak 账号(用于自动保存磁力到网盘)
+pikpak_username:
+pikpak_password:
+
+# 可选,AI 自然语言搜索(任意 OpenAI 兼容接口)
+ai_base_url:
+ai_api_key:
+ai_model:
diff --git a/telegram/tg-search-bot/.gitignore b/telegram/tg-search-bot/.gitignore
new file mode 100644
index 0000000..83b8f44
--- /dev/null
+++ b/telegram/tg-search-bot/.gitignore
@@ -0,0 +1,6 @@
+__pycache__
+.vscode
+.DS_Store
+.idea
+.venv
+*.sqlite
\ No newline at end of file
diff --git a/telegram/tg-search-bot/LICENSE b/telegram/tg-search-bot/LICENSE
new file mode 100644
index 0000000..f288702
--- /dev/null
+++ b/telegram/tg-search-bot/LICENSE
@@ -0,0 +1,674 @@
+ GNU GENERAL PUBLIC LICENSE
+ Version 3, 29 June 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc.
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU General Public License is a free, copyleft license for
+software and other kinds of works.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+the GNU General Public License is intended to guarantee your freedom to
+share and change all versions of a program--to make sure it remains free
+software for all its users. We, the Free Software Foundation, use the
+GNU General Public License for most of our software; it applies also to
+any other work released this way by its authors. You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+them if you wish), that you receive source code or can get it if you
+want it, that you can change the software or use pieces of it in new
+free programs, and that you know you can do these things.
+
+ To protect your rights, we need to prevent others from denying you
+these rights or asking you to surrender the rights. Therefore, you have
+certain responsibilities if you distribute copies of the software, or if
+you modify it: responsibilities to respect the freedom of others.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must pass on to the recipients the same
+freedoms that you received. You must make sure that they, too, receive
+or can get the source code. And you must show them these terms so they
+know their rights.
+
+ Developers that use the GNU GPL protect your rights with two steps:
+(1) assert copyright on the software, and (2) offer you this License
+giving you legal permission to copy, distribute and/or modify it.
+
+ For the developers' and authors' protection, the GPL clearly explains
+that there is no warranty for this free software. For both users' and
+authors' sake, the GPL requires that modified versions be marked as
+changed, so that their problems will not be attributed erroneously to
+authors of previous versions.
+
+ Some devices are designed to deny users access to install or run
+modified versions of the software inside them, although the manufacturer
+can do so. This is fundamentally incompatible with the aim of
+protecting users' freedom to change the software. The systematic
+pattern of such abuse occurs in the area of products for individuals to
+use, which is precisely where it is most unacceptable. Therefore, we
+have designed this version of the GPL to prohibit the practice for those
+products. If such problems arise substantially in other domains, we
+stand ready to extend this provision to those domains in future versions
+of the GPL, as needed to protect the freedom of users.
+
+ Finally, every program is threatened constantly by software patents.
+States should not allow patents to restrict development and use of
+software on general-purpose computers, but in those that do, we wish to
+avoid the special danger that patents applied to a free program could
+make it effectively proprietary. To prevent this, the GPL assures that
+patents cannot be used to render the program non-free.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ TERMS AND CONDITIONS
+
+ 0. Definitions.
+
+ "This License" refers to version 3 of the GNU General Public License.
+
+ "Copyright" also means copyright-like laws that apply to other kinds of
+works, such as semiconductor masks.
+
+ "The Program" refers to any copyrightable work licensed under this
+License. Each licensee is addressed as "you". "Licensees" and
+"recipients" may be individuals or organizations.
+
+ To "modify" a work means to copy from or adapt all or part of the work
+in a fashion requiring copyright permission, other than the making of an
+exact copy. The resulting work is called a "modified version" of the
+earlier work or a work "based on" the earlier work.
+
+ A "covered work" means either the unmodified Program or a work based
+on the Program.
+
+ To "propagate" a work means to do anything with it that, without
+permission, would make you directly or secondarily liable for
+infringement under applicable copyright law, except executing it on a
+computer or modifying a private copy. Propagation includes copying,
+distribution (with or without modification), making available to the
+public, and in some countries other activities as well.
+
+ To "convey" a work means any kind of propagation that enables other
+parties to make or receive copies. Mere interaction with a user through
+a computer network, with no transfer of a copy, is not conveying.
+
+ An interactive user interface displays "Appropriate Legal Notices"
+to the extent that it includes a convenient and prominently visible
+feature that (1) displays an appropriate copyright notice, and (2)
+tells the user that there is no warranty for the work (except to the
+extent that warranties are provided), that licensees may convey the
+work under this License, and how to view a copy of this License. If
+the interface presents a list of user commands or options, such as a
+menu, a prominent item in the list meets this criterion.
+
+ 1. Source Code.
+
+ The "source code" for a work means the preferred form of the work
+for making modifications to it. "Object code" means any non-source
+form of a work.
+
+ A "Standard Interface" means an interface that either is an official
+standard defined by a recognized standards body, or, in the case of
+interfaces specified for a particular programming language, one that
+is widely used among developers working in that language.
+
+ The "System Libraries" of an executable work include anything, other
+than the work as a whole, that (a) is included in the normal form of
+packaging a Major Component, but which is not part of that Major
+Component, and (b) serves only to enable use of the work with that
+Major Component, or to implement a Standard Interface for which an
+implementation is available to the public in source code form. A
+"Major Component", in this context, means a major essential component
+(kernel, window system, and so on) of the specific operating system
+(if any) on which the executable work runs, or a compiler used to
+produce the work, or an object code interpreter used to run it.
+
+ The "Corresponding Source" for a work in object code form means all
+the source code needed to generate, install, and (for an executable
+work) run the object code and to modify the work, including scripts to
+control those activities. However, it does not include the work's
+System Libraries, or general-purpose tools or generally available free
+programs which are used unmodified in performing those activities but
+which are not part of the work. For example, Corresponding Source
+includes interface definition files associated with source files for
+the work, and the source code for shared libraries and dynamically
+linked subprograms that the work is specifically designed to require,
+such as by intimate data communication or control flow between those
+subprograms and other parts of the work.
+
+ The Corresponding Source need not include anything that users
+can regenerate automatically from other parts of the Corresponding
+Source.
+
+ The Corresponding Source for a work in source code form is that
+same work.
+
+ 2. Basic Permissions.
+
+ All rights granted under this License are granted for the term of
+copyright on the Program, and are irrevocable provided the stated
+conditions are met. This License explicitly affirms your unlimited
+permission to run the unmodified Program. The output from running a
+covered work is covered by this License only if the output, given its
+content, constitutes a covered work. This License acknowledges your
+rights of fair use or other equivalent, as provided by copyright law.
+
+ You may make, run and propagate covered works that you do not
+convey, without conditions so long as your license otherwise remains
+in force. You may convey covered works to others for the sole purpose
+of having them make modifications exclusively for you, or provide you
+with facilities for running those works, provided that you comply with
+the terms of this License in conveying all material for which you do
+not control copyright. Those thus making or running the covered works
+for you must do so exclusively on your behalf, under your direction
+and control, on terms that prohibit them from making any copies of
+your copyrighted material outside their relationship with you.
+
+ Conveying under any other circumstances is permitted solely under
+the conditions stated below. Sublicensing is not allowed; section 10
+makes it unnecessary.
+
+ 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
+
+ No covered work shall be deemed part of an effective technological
+measure under any applicable law fulfilling obligations under article
+11 of the WIPO copyright treaty adopted on 20 December 1996, or
+similar laws prohibiting or restricting circumvention of such
+measures.
+
+ When you convey a covered work, you waive any legal power to forbid
+circumvention of technological measures to the extent such circumvention
+is effected by exercising rights under this License with respect to
+the covered work, and you disclaim any intention to limit operation or
+modification of the work as a means of enforcing, against the work's
+users, your or third parties' legal rights to forbid circumvention of
+technological measures.
+
+ 4. Conveying Verbatim Copies.
+
+ You may convey verbatim copies of the Program's source code as you
+receive it, in any medium, provided that you conspicuously and
+appropriately publish on each copy an appropriate copyright notice;
+keep intact all notices stating that this License and any
+non-permissive terms added in accord with section 7 apply to the code;
+keep intact all notices of the absence of any warranty; and give all
+recipients a copy of this License along with the Program.
+
+ You may charge any price or no price for each copy that you convey,
+and you may offer support or warranty protection for a fee.
+
+ 5. Conveying Modified Source Versions.
+
+ You may convey a work based on the Program, or the modifications to
+produce it from the Program, in the form of source code under the
+terms of section 4, provided that you also meet all of these conditions:
+
+ a) The work must carry prominent notices stating that you modified
+ it, and giving a relevant date.
+
+ b) The work must carry prominent notices stating that it is
+ released under this License and any conditions added under section
+ 7. This requirement modifies the requirement in section 4 to
+ "keep intact all notices".
+
+ c) You must license the entire work, as a whole, under this
+ License to anyone who comes into possession of a copy. This
+ License will therefore apply, along with any applicable section 7
+ additional terms, to the whole of the work, and all its parts,
+ regardless of how they are packaged. This License gives no
+ permission to license the work in any other way, but it does not
+ invalidate such permission if you have separately received it.
+
+ d) If the work has interactive user interfaces, each must display
+ Appropriate Legal Notices; however, if the Program has interactive
+ interfaces that do not display Appropriate Legal Notices, your
+ work need not make them do so.
+
+ A compilation of a covered work with other separate and independent
+works, which are not by their nature extensions of the covered work,
+and which are not combined with it such as to form a larger program,
+in or on a volume of a storage or distribution medium, is called an
+"aggregate" if the compilation and its resulting copyright are not
+used to limit the access or legal rights of the compilation's users
+beyond what the individual works permit. Inclusion of a covered work
+in an aggregate does not cause this License to apply to the other
+parts of the aggregate.
+
+ 6. Conveying Non-Source Forms.
+
+ You may convey a covered work in object code form under the terms
+of sections 4 and 5, provided that you also convey the
+machine-readable Corresponding Source under the terms of this License,
+in one of these ways:
+
+ a) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by the
+ Corresponding Source fixed on a durable physical medium
+ customarily used for software interchange.
+
+ b) Convey the object code in, or embodied in, a physical product
+ (including a physical distribution medium), accompanied by a
+ written offer, valid for at least three years and valid for as
+ long as you offer spare parts or customer support for that product
+ model, to give anyone who possesses the object code either (1) a
+ copy of the Corresponding Source for all the software in the
+ product that is covered by this License, on a durable physical
+ medium customarily used for software interchange, for a price no
+ more than your reasonable cost of physically performing this
+ conveying of source, or (2) access to copy the
+ Corresponding Source from a network server at no charge.
+
+ c) Convey individual copies of the object code with a copy of the
+ written offer to provide the Corresponding Source. This
+ alternative is allowed only occasionally and noncommercially, and
+ only if you received the object code with such an offer, in accord
+ with subsection 6b.
+
+ d) Convey the object code by offering access from a designated
+ place (gratis or for a charge), and offer equivalent access to the
+ Corresponding Source in the same way through the same place at no
+ further charge. You need not require recipients to copy the
+ Corresponding Source along with the object code. If the place to
+ copy the object code is a network server, the Corresponding Source
+ may be on a different server (operated by you or a third party)
+ that supports equivalent copying facilities, provided you maintain
+ clear directions next to the object code saying where to find the
+ Corresponding Source. Regardless of what server hosts the
+ Corresponding Source, you remain obligated to ensure that it is
+ available for as long as needed to satisfy these requirements.
+
+ e) Convey the object code using peer-to-peer transmission, provided
+ you inform other peers where the object code and Corresponding
+ Source of the work are being offered to the general public at no
+ charge under subsection 6d.
+
+ A separable portion of the object code, whose source code is excluded
+from the Corresponding Source as a System Library, need not be
+included in conveying the object code work.
+
+ A "User Product" is either (1) a "consumer product", which means any
+tangible personal property which is normally used for personal, family,
+or household purposes, or (2) anything designed or sold for incorporation
+into a dwelling. In determining whether a product is a consumer product,
+doubtful cases shall be resolved in favor of coverage. For a particular
+product received by a particular user, "normally used" refers to a
+typical or common use of that class of product, regardless of the status
+of the particular user or of the way in which the particular user
+actually uses, or expects or is expected to use, the product. A product
+is a consumer product regardless of whether the product has substantial
+commercial, industrial or non-consumer uses, unless such uses represent
+the only significant mode of use of the product.
+
+ "Installation Information" for a User Product means any methods,
+procedures, authorization keys, or other information required to install
+and execute modified versions of a covered work in that User Product from
+a modified version of its Corresponding Source. The information must
+suffice to ensure that the continued functioning of the modified object
+code is in no case prevented or interfered with solely because
+modification has been made.
+
+ If you convey an object code work under this section in, or with, or
+specifically for use in, a User Product, and the conveying occurs as
+part of a transaction in which the right of possession and use of the
+User Product is transferred to the recipient in perpetuity or for a
+fixed term (regardless of how the transaction is characterized), the
+Corresponding Source conveyed under this section must be accompanied
+by the Installation Information. But this requirement does not apply
+if neither you nor any third party retains the ability to install
+modified object code on the User Product (for example, the work has
+been installed in ROM).
+
+ The requirement to provide Installation Information does not include a
+requirement to continue to provide support service, warranty, or updates
+for a work that has been modified or installed by the recipient, or for
+the User Product in which it has been modified or installed. Access to a
+network may be denied when the modification itself materially and
+adversely affects the operation of the network or violates the rules and
+protocols for communication across the network.
+
+ Corresponding Source conveyed, and Installation Information provided,
+in accord with this section must be in a format that is publicly
+documented (and with an implementation available to the public in
+source code form), and must require no special password or key for
+unpacking, reading or copying.
+
+ 7. Additional Terms.
+
+ "Additional permissions" are terms that supplement the terms of this
+License by making exceptions from one or more of its conditions.
+Additional permissions that are applicable to the entire Program shall
+be treated as though they were included in this License, to the extent
+that they are valid under applicable law. If additional permissions
+apply only to part of the Program, that part may be used separately
+under those permissions, but the entire Program remains governed by
+this License without regard to the additional permissions.
+
+ When you convey a copy of a covered work, you may at your option
+remove any additional permissions from that copy, or from any part of
+it. (Additional permissions may be written to require their own
+removal in certain cases when you modify the work.) You may place
+additional permissions on material, added by you to a covered work,
+for which you have or can give appropriate copyright permission.
+
+ Notwithstanding any other provision of this License, for material you
+add to a covered work, you may (if authorized by the copyright holders of
+that material) supplement the terms of this License with terms:
+
+ a) Disclaiming warranty or limiting liability differently from the
+ terms of sections 15 and 16 of this License; or
+
+ b) Requiring preservation of specified reasonable legal notices or
+ author attributions in that material or in the Appropriate Legal
+ Notices displayed by works containing it; or
+
+ c) Prohibiting misrepresentation of the origin of that material, or
+ requiring that modified versions of such material be marked in
+ reasonable ways as different from the original version; or
+
+ d) Limiting the use for publicity purposes of names of licensors or
+ authors of the material; or
+
+ e) Declining to grant rights under trademark law for use of some
+ trade names, trademarks, or service marks; or
+
+ f) Requiring indemnification of licensors and authors of that
+ material by anyone who conveys the material (or modified versions of
+ it) with contractual assumptions of liability to the recipient, for
+ any liability that these contractual assumptions directly impose on
+ those licensors and authors.
+
+ All other non-permissive additional terms are considered "further
+restrictions" within the meaning of section 10. If the Program as you
+received it, or any part of it, contains a notice stating that it is
+governed by this License along with a term that is a further
+restriction, you may remove that term. If a license document contains
+a further restriction but permits relicensing or conveying under this
+License, you may add to a covered work material governed by the terms
+of that license document, provided that the further restriction does
+not survive such relicensing or conveying.
+
+ If you add terms to a covered work in accord with this section, you
+must place, in the relevant source files, a statement of the
+additional terms that apply to those files, or a notice indicating
+where to find the applicable terms.
+
+ Additional terms, permissive or non-permissive, may be stated in the
+form of a separately written license, or stated as exceptions;
+the above requirements apply either way.
+
+ 8. Termination.
+
+ You may not propagate or modify a covered work except as expressly
+provided under this License. Any attempt otherwise to propagate or
+modify it is void, and will automatically terminate your rights under
+this License (including any patent licenses granted under the third
+paragraph of section 11).
+
+ However, if you cease all violation of this License, then your
+license from a particular copyright holder is reinstated (a)
+provisionally, unless and until the copyright holder explicitly and
+finally terminates your license, and (b) permanently, if the copyright
+holder fails to notify you of the violation by some reasonable means
+prior to 60 days after the cessation.
+
+ Moreover, your license from a particular copyright holder is
+reinstated permanently if the copyright holder notifies you of the
+violation by some reasonable means, this is the first time you have
+received notice of violation of this License (for any work) from that
+copyright holder, and you cure the violation prior to 30 days after
+your receipt of the notice.
+
+ Termination of your rights under this section does not terminate the
+licenses of parties who have received copies or rights from you under
+this License. If your rights have been terminated and not permanently
+reinstated, you do not qualify to receive new licenses for the same
+material under section 10.
+
+ 9. Acceptance Not Required for Having Copies.
+
+ You are not required to accept this License in order to receive or
+run a copy of the Program. Ancillary propagation of a covered work
+occurring solely as a consequence of using peer-to-peer transmission
+to receive a copy likewise does not require acceptance. However,
+nothing other than this License grants you permission to propagate or
+modify any covered work. These actions infringe copyright if you do
+not accept this License. Therefore, by modifying or propagating a
+covered work, you indicate your acceptance of this License to do so.
+
+ 10. Automatic Licensing of Downstream Recipients.
+
+ Each time you convey a covered work, the recipient automatically
+receives a license from the original licensors, to run, modify and
+propagate that work, subject to this License. You are not responsible
+for enforcing compliance by third parties with this License.
+
+ An "entity transaction" is a transaction transferring control of an
+organization, or substantially all assets of one, or subdividing an
+organization, or merging organizations. If propagation of a covered
+work results from an entity transaction, each party to that
+transaction who receives a copy of the work also receives whatever
+licenses to the work the party's predecessor in interest had or could
+give under the previous paragraph, plus a right to possession of the
+Corresponding Source of the work from the predecessor in interest, if
+the predecessor has it or can get it with reasonable efforts.
+
+ You may not impose any further restrictions on the exercise of the
+rights granted or affirmed under this License. For example, you may
+not impose a license fee, royalty, or other charge for exercise of
+rights granted under this License, and you may not initiate litigation
+(including a cross-claim or counterclaim in a lawsuit) alleging that
+any patent claim is infringed by making, using, selling, offering for
+sale, or importing the Program or any portion of it.
+
+ 11. Patents.
+
+ A "contributor" is a copyright holder who authorizes use under this
+License of the Program or a work on which the Program is based. The
+work thus licensed is called the contributor's "contributor version".
+
+ A contributor's "essential patent claims" are all patent claims
+owned or controlled by the contributor, whether already acquired or
+hereafter acquired, that would be infringed by some manner, permitted
+by this License, of making, using, or selling its contributor version,
+but do not include claims that would be infringed only as a
+consequence of further modification of the contributor version. For
+purposes of this definition, "control" includes the right to grant
+patent sublicenses in a manner consistent with the requirements of
+this License.
+
+ Each contributor grants you a non-exclusive, worldwide, royalty-free
+patent license under the contributor's essential patent claims, to
+make, use, sell, offer for sale, import and otherwise run, modify and
+propagate the contents of its contributor version.
+
+ In the following three paragraphs, a "patent license" is any express
+agreement or commitment, however denominated, not to enforce a patent
+(such as an express permission to practice a patent or covenant not to
+sue for patent infringement). To "grant" such a patent license to a
+party means to make such an agreement or commitment not to enforce a
+patent against the party.
+
+ If you convey a covered work, knowingly relying on a patent license,
+and the Corresponding Source of the work is not available for anyone
+to copy, free of charge and under the terms of this License, through a
+publicly available network server or other readily accessible means,
+then you must either (1) cause the Corresponding Source to be so
+available, or (2) arrange to deprive yourself of the benefit of the
+patent license for this particular work, or (3) arrange, in a manner
+consistent with the requirements of this License, to extend the patent
+license to downstream recipients. "Knowingly relying" means you have
+actual knowledge that, but for the patent license, your conveying the
+covered work in a country, or your recipient's use of the covered work
+in a country, would infringe one or more identifiable patents in that
+country that you have reason to believe are valid.
+
+ If, pursuant to or in connection with a single transaction or
+arrangement, you convey, or propagate by procuring conveyance of, a
+covered work, and grant a patent license to some of the parties
+receiving the covered work authorizing them to use, propagate, modify
+or convey a specific copy of the covered work, then the patent license
+you grant is automatically extended to all recipients of the covered
+work and works based on it.
+
+ A patent license is "discriminatory" if it does not include within
+the scope of its coverage, prohibits the exercise of, or is
+conditioned on the non-exercise of one or more of the rights that are
+specifically granted under this License. You may not convey a covered
+work if you are a party to an arrangement with a third party that is
+in the business of distributing software, under which you make payment
+to the third party based on the extent of your activity of conveying
+the work, and under which the third party grants, to any of the
+parties who would receive the covered work from you, a discriminatory
+patent license (a) in connection with copies of the covered work
+conveyed by you (or copies made from those copies), or (b) primarily
+for and in connection with specific products or compilations that
+contain the covered work, unless you entered into that arrangement,
+or that patent license was granted, prior to 28 March 2007.
+
+ Nothing in this License shall be construed as excluding or limiting
+any implied license or other defenses to infringement that may
+otherwise be available to you under applicable patent law.
+
+ 12. No Surrender of Others' Freedom.
+
+ If conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot convey a
+covered work so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you may
+not convey it at all. For example, if you agree to terms that obligate you
+to collect a royalty for further conveying from those to whom you convey
+the Program, the only way you could satisfy both those terms and this
+License would be to refrain entirely from conveying the Program.
+
+ 13. Use with the GNU Affero General Public License.
+
+ Notwithstanding any other provision of this License, you have
+permission to link or combine any covered work with a work licensed
+under version 3 of the GNU Affero General Public License into a single
+combined work, and to convey the resulting work. The terms of this
+License will continue to apply to the part which is the covered work,
+but the special requirements of the GNU Affero General Public License,
+section 13, concerning interaction through a network will apply to the
+combination as such.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+ Each version is given a distinguishing version number. If the
+Program specifies that a certain numbered version of the GNU General
+Public License "or any later version" applies to it, you have the
+option of following the terms and conditions either of that numbered
+version or of any later version published by the Free Software
+Foundation. If the Program does not specify a version number of the
+GNU General Public License, you may choose any version ever published
+by the Free Software Foundation.
+
+ If the Program specifies that a proxy can decide which future
+versions of the GNU General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+
+ Copyright (C)
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU General Public License as published by
+ the Free Software Foundation, either version 3 of the License, or
+ (at your option) any later version.
+
+ This program is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU General Public License for more details.
+
+ You should have received a copy of the GNU General Public License
+ along with this program. If not, see .
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If the program does terminal interaction, make it output a short
+notice like this when it starts in an interactive mode:
+
+ Copyright (C)
+ This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
+ This is free software, and you are welcome to redistribute it
+ under certain conditions; type `show c' for details.
+
+The hypothetical commands `show w' and `show c' should show the appropriate
+parts of the General Public License. Of course, your program's commands
+might be different; for a GUI interface, you would use an "about box".
+
+ You should also get your employer (if you work as a programmer) or school,
+if any, to sign a "copyright disclaimer" for the program, if necessary.
+For more information on this, and how to apply and follow the GNU GPL, see
+.
+
+ The GNU General Public License does not permit incorporating your program
+into proprietary programs. If your program is a subroutine library, you
+may consider it more useful to permit linking proprietary applications with
+the library. If this is what you want to do, use the GNU Lesser General
+Public License instead of this License. But first, please read
+.
diff --git a/telegram/tg-search-bot/README.md b/telegram/tg-search-bot/README.md
new file mode 100644
index 0000000..644955d
--- /dev/null
+++ b/telegram/tg-search-bot/README.md
@@ -0,0 +1,142 @@
+# tg-search-bot
+
+[English](README.md)|[中文](README.zh.md)
+
+A Python 3 Telegram bot for searching video magnet links. It supports collection and export of records, automatic saving to cloud storage, configurable NSFW filtering, proxy support, and AI-powered natural-language understanding for automatic intent, target, and source detection from user input.
+
+- Data sources: TorrentKitty (Chinese) + apibay (English) + video index APIs (Jvav)
+- Cloud storage: PikPak official OpenAPI
+- AI: any OpenAI-compatible API for intent recognition and automatic routing
+
+## Features
+
+- Search by title, keyword, number, plot, performer name, or genre
+- Return cover art, rating, release date, tags, cast, and magnet links with optional HD / subtitle filtering
+- Fetch preview videos, full videos, and screenshots
+- Store and export records in `record.json`
+- Random high-quality and latest picks
+- Save the best magnet link to PikPak with direct offline download support
+- AI natural-language search that understands intent and selects the best source automatically
+- BT torrent search using multiple sources with paginated results
+- Multi-turn follow-up: `next batch`, `next page`, `previous page`, `save item N`
+- Configurable NSFW filter and proxy support
+
+## Core flow
+
+1. The user sends a resource request such as a movie title, TV show, number, plot summary, performer, or genre.
+2. The AI interprets the request and returns `intent`, `target`, `source`, and `explain`.
+3. The bot replies with `🔍 Searching: {target}`.
+4. The AI chooses the best crawler or API for the request.
+5. The bot replies with `⏳ Searching ...`.
+6. The crawler/API returns magnet links or alternative BT results if no magnet is found.
+7. The bot replies with `📄 Search results`.
+8. The best magnet is saved to the configured PikPak account.
+9. The bot replies with `✅ Saved successfully`.
+
+> If no AI API is configured, the bot falls back to the original number detection and BT keyword search flow.
+
+```mermaid
+flowchart TD
+ A["1. User input
title / plot / number / genre / performer"] --> B["2. AI understands intent
intent · target · source · explain"]
+ B --> C["3. Reply 🔍 Searching: target"]
+ C --> D["4. Select the best crawler / API"]
+ D --> D1{intent}
+ D1 -->|number| E["Search by number
index sites"]
+ D1 -->|performer| F["Performer search"]
+ D1 -->|title / genre / plot| G["Keyword / BT search"]
+ E --> H["5. Reply ⏳ Searching ..."]
+ F --> H
+ G --> H
+ H --> I["6. Return magnet links
or BT alternatives"]
+ I --> J["7. Reply 📄 Search results"]
+ J --> K["8. Save best magnet to PikPak"]
+ K --> L["9. Reply ✅ Saved successfully"]
+```
+
+## Project structure
+
+```
+bot.py Main program: config, logging, message handlers, AI flow
+ai.py AI intent client using OpenAI-compatible /chat/completions
+pikpak.py PikPak official OpenAPI client for login, token refresh, and offline download
+database.py Data layer: BotFileDb (JSON records) + BotCacheDb (SQLite cache)
+requirements.txt Dependencies
+docker-compose.yml One-click deployment
+```
+
+Runtime data is stored under `~/.tg_search_bot/`: `config.yaml`, `record.json`, `cache.db`, `pikpak_token.json`, and `log.txt`.
+
+## Usage
+
+### 1. Configure
+
+Edit `~/.tg_search_bot/config.yaml`:
+
+```yaml
+# Required: Telegram chat ID
+tg_chat_id:
+# Required: Telegram bot token
+tg_bot_token:
+# Required: use global proxy, 1 = yes, 0 = no
+use_proxy:
+# Optional: proxy address, required when use_proxy is 1
+proxy_addr:
+# Required: enable NSFW content, 1 = yes, 0 = no
+enable_nsfw: 0
+# Optional: PikPak account for auto-saving magnets
+pikpak_username:
+pikpak_password:
+# Optional: AI natural-language search via any OpenAI-compatible API
+ai_base_url:
+ai_api_key:
+ai_model:
+```
+
+### 2. Run
+
+```sh
+# Option 1: Docker deployment
+docker-compose up -d
+
+# Option 2: run directly (Python 3.9+)
+pip install -r requirements.txt
+python3 bot.py
+```
+
+### 3. Commands
+
+| Command | Description |
+| --- | --- |
+| `/help` | Show help |
+| `/stars` | View collected performers |
+| `/ids` | View collected numbers |
+| `/record` | Export the records file |
+
+Simply send a movie title, keyword, number, plot summary, performer name, or genre. The AI will understand and search automatically.
+
+### 4. Multi-turn follow-up
+
+BT search results are paginated in groups of 5. You can continue with:
+
+- `next batch` / `next page` / `more` — show the next page
+- `previous page` — show the previous page
+- `save item N` or `save N` — save the N-th magnet to PikPak
+
+## Development
+
+Python 3.9+ is recommended, preferably with a virtual environment:
+
+```sh
+git clone https://github.com/akynazh/tg-search-bot.git
+cd tg-search-bot
+python3 -m venv .venv
+source ./.venv/bin/activate
+pip3 install -r requirements.txt
+```
+
+## Thanks
+
+
+
+
+Thanks to JetBrains for supporting this project.
diff --git a/telegram/tg-search-bot/README.zh.md b/telegram/tg-search-bot/README.zh.md
new file mode 100644
index 0000000..5ecf640
--- /dev/null
+++ b/telegram/tg-search-bot/README.zh.md
@@ -0,0 +1,143 @@
+# tg-search-bot
+
+[English](README.md)|[中文](README.zh.md)
+
+一个基于 Python3 的 Telegram 资源搜索机器人:搜索各类视频磁力链接,支持收藏、导出记录、自动保存到网盘,可配置 NSFW 开关与代理上网;同时集成 AI 自然语言理解能力,可直接根据用户自然语言意图自动识别搜索目标、类型与数据源。
+
+- 数据来源:TorrentKitty(中文)+ apibay(英文)+ 影视磁力索引 API(Jvav)
+- 网盘:Pikpak 官方 OpenAPI
+- AI:任意 OpenAI 兼容接口,支持意图识别与自动搜索
+
+## 功能
+
+- 按编号 / 演职人员 / 关键词搜索影片,返回封面、评分、日期、标签、演职人员及磁力链接(支持 HD / 字幕等过滤)
+- 获取预览视频、完整视频与影片截图
+- 收藏与导出记录(`record.json`)
+- 排行榜、随机高分 / 最新影片
+- 自动把最优磁力链接保存到 Pikpak(登录 token 直传离线任务)
+- AI 自然语言理解搜索:识别编号 / 演职人员 / 片名 / 剧情 / 类型并自动选择数据源
+- BT 种子搜索(中文 / 英文双引擎),结果分页
+- 多轮追问:`换一批` / `下一页` / `上一页` / `保存第N个`
+- 可配置 NSFW 开关与代理上网
+
+## 核心流程(AI 自然语言搜索)
+
+搜索流程:
+
+1. 用户输入想要的资源 / 资源相关信息(电影、电视剧名称、影片编号、剧情 / 对话、演职人员、影片类型)
+2. AI 根据输入理解用户目标(根据剧情推测片名、根据类型推荐等),输出 `intent / target / source / explain`
+3. 机器人回复:`🔍 搜索:{目标}`
+4. AI 选择最合适的爬虫 / API 进行搜索(编号 → 编号索引站,演职人员 → 演职人员搜索,其余 → 关键词或 BT)
+5. 机器人回复:`⏳ 搜索中 ...`
+6. 爬虫 / API 搜索得到磁力链接(没有磁力时返回 BT 种子等其他格式内容)
+7. 机器人回复:`📄 搜索结果`
+8. 程序将最优磁力链接保存到已配置的网盘(PikPak)
+9. 机器人回复:`✅ 保存结果:已提交离线任务到 PikPak`
+
+> 未配置 AI 接口时自动回退到原来的编号识别 + BT 关键词搜索逻辑。
+
+```mermaid
+flowchart TD
+ A["① 用户输入
电影 / 电视剧 / 编号 / 剧情 / 演职人员 / 类型"] --> B["② AI 理解意图
intent · target · source · explain"]
+ B --> C["③ 回复 🔍 搜索:目标"]
+ C --> D["④ 选择最合适的爬虫 / API"]
+ D --> D1{意图 intent}
+ D1 -->|编号| E["按编号搜索
编号索引站"]
+ D1 -->|演职人员| F["演职人员搜索"]
+ D1 -->|关键词 / 类型 / 剧情| G["关键词 → BT 种子"]
+ E --> H["⑤ 回复 ⏳ 搜索中"]
+ F --> H
+ G --> H
+ H --> I["⑥ 搜索得到磁力链接
(无磁力则返回 BT 等其他格式)"]
+ I --> J["⑦ 回复 📄 搜索结果"]
+ J --> K["⑧ 保存最优磁力链接到 PikPak"]
+ K --> L["⑨ 回复 ✅ 保存结果"]
+```
+
+## 目录结构
+
+```
+bot.py 主程序:配置、日志、消息 / 回调处理、AI 搜索流程
+ai.py AI 意图理解客户端(OpenAI 兼容 /chat/completions)
+pikpak.py Pikpak 官方 OpenAPI 客户端(登录 / 刷新 token、离线下载)
+database.py 数据层:BotFileDb(JSON 收藏)+ BotCacheDb(SQLite 缓存)
+requirements.txt 依赖
+docker-compose.yml 一键部署
+```
+
+配置与数据文件存放于 `~/.tg_search_bot/`:`config.yaml`(主配置)、`record.json`(收藏)、`cache.db`(缓存)、`pikpak_token.json`(Pikpak 登录态)、`log.txt`(日志)。
+
+## 使用
+
+### 1. 配置
+
+编辑 `~/.tg_search_bot/config.yaml`:
+
+```yaml
+# 必填,你的 Telegram chat id
+tg_chat_id:
+# 必填,你的 Telegram bot token
+tg_bot_token:
+# 必填,是否启用全局代理,1 是 / 0 否
+use_proxy:
+# 可选,代理地址(use_proxy 为 1 时必填),如 http://127.0.0.1:7890
+proxy_addr:
+# 必填,是否开启 NSFW 内容,1 是 / 0 否
+enable_nsfw: 0
+# 可选,Pikpak 账号(用于自动保存磁力到网盘,官方 API)
+pikpak_username:
+pikpak_password:
+# 可选,AI 自然语言搜索(任意 OpenAI 兼容接口)
+ai_base_url:
+ai_api_key:
+ai_model:
+```
+
+### 2. 运行
+
+```sh
+# 方式一:Docker 一键部署
+docker-compose up -d
+
+# 方式二:直接运行(Python >= 3.9)
+pip install -r requirements.txt
+python3 bot.py
+```
+
+### 3. 命令
+
+| 命令 | 说明 |
+| --- | --- |
+| `/help` | 查看帮助 |
+| `/stars` | 查看已收藏演职人员 |
+| `/ids` | 查看已收藏编号 |
+| `/record` | 导出收藏记录文件 |
+
+直接发送电影名 / 关键词 / 编号 / 剧情 / 演员名 / 类型即可,AI 会自动识别并搜索。
+
+### 4. 多轮追问
+
+BT 搜索结果每页 5 条,可继续回复:
+
+- `换一批` / `下一页` / `还有吗` — 下一页
+- `上一页` — 上一页
+- `保存第N个`(或 `save N`)— 把第 N 条磁力保存到 Pikpak
+
+## 开发
+
+推荐使用 Python 3.9,并建议使用虚拟环境:
+
+```sh
+git clone https://github.com/akynazh/tg-search-bot.git
+cd tg-search-bot
+python3 -m venv .venv
+source ./.venv/bin/activate
+pip3 install -r requirements.txt
+```
+
+## 致谢
+
+
+
+
+感谢 JetBrains 对这个项目的支持!
diff --git a/telegram/tg-search-bot/ai.py b/telegram/tg-search-bot/ai.py
new file mode 100644
index 0000000..e4aec46
--- /dev/null
+++ b/telegram/tg-search-bot/ai.py
@@ -0,0 +1,135 @@
+# -*- coding: UTF-8 -*-
+"""AI 意图理解客户端。
+
+对接任意 OpenAI 兼容接口(可自定义 base_url),将用户的自然语言输入解析为
+结构化的搜索意图,供机器人选择合适的爬虫 / API 进行资源搜索。
+"""
+
+import json
+import logging
+import re
+
+import requests
+
+LOG = logging.getLogger(__name__)
+
+SYSTEM_PROMPT = """你是一个 Telegram 资源搜索机器人的「意图理解」模块。用户会用自然语言描述想要的资源,可能包括:
+- AV 番号(如 ABP-123、FC2-PPV-12345)
+- 演员名字
+- 电影 / 电视剧名称
+- 一段剧情、台词或影片描述
+- 电影类型 / 题材(如「悬疑电影」「科幻片」)
+
+请解析用户输入,并只输出一个 JSON 对象(不要输出任何其他文字),字段如下:
+{
+ "intent": "av_id | actor | genre | keyword | plot | general",
+ "target": "解析后的搜索目标(番号 / 演员名 / 关键词 / 推测出的片名)",
+ "source": "javdb | javbus | sukebei | dmm | apibay | auto",
+ "explain": "用一句话说明你理解到的搜索目标"
+}
+
+规则:
+- intent=av_id:输入是明确的番号;target 保持番号原样(英文字母大写、连字符保留)
+- intent=actor:仅当输入是明确的日本 AV 演员 / 演员名(例如「波多野结衣」「桥本有菜」「三上悠亜」);target 必须是最可能的正式演员名,不要直接原样照抄用户输入;如果用户把演员名打错、同音字、错别字、简写、日文假名近似、中文音译偏差,优先纠正成真正的日本 AV 演员名;如果用户说的是普通成人明星、非 AV 演员、或无法确定是日本 AV 演员,则不要使用 actor,改用 keyword / general
+- intent=genre:输入是电影类型 / 题材;target 为该类型关键词(如「悬疑」)
+- intent=plot:输入是剧情 / 台词 / 描述;target 为推测出的最可能片名(不确定也给一个最接近的)
+- intent=keyword:输入是电影 / 电视剧名称或其他明确关键词;target 为精简后的关键词
+- intent=general:无法明确分类时使用;target 为原始输入的精简版
+- source 表示最合适的数据源:AV 相关用 javdb/javbus/sukebei/dmm,电影 / 电视剧 / 通用关键词用 apibay,拿不准用 auto
+- target 尽量精简,去掉语气词和多余描述
+- 特别注意:演员搜索是“纠错 + 归一化”任务,不要因为用户拼错字或音近字就保留错误名字;例如“波多野结衣”可能写成“波多野结衣”“娑多野结衣”,应修正到正确正式名;“三上悠亚”可能写成“三上悠亜/三上悠亚”都应统一成正式名
+"""
+
+
+class AiClient:
+ def __init__(
+ self,
+ base_url: str = "",
+ api_key: str = "",
+ model: str = "gpt-4o-mini",
+ proxy: str = "",
+ timeout: int = 60,
+ ):
+ self.base_url = (base_url or "").rstrip("/")
+ self.api_key = api_key or ""
+ self.model = model or "gpt-4o-mini"
+ self.proxy = proxy or ""
+ self.proxies = {"http": self.proxy, "https": self.proxy} if self.proxy else None
+ self.timeout = timeout
+
+ @property
+ def enabled(self):
+ return bool(self.base_url and self.api_key)
+
+ def chat(self, messages, temperature=0.2, max_tokens=800):
+ if not self.enabled:
+ return None
+ url = f"{self.base_url}/chat/completions"
+ headers = {
+ "Authorization": f"Bearer {self.api_key}",
+ "Content-Type": "application/json",
+ }
+ payload = {
+ "model": self.model,
+ "messages": messages,
+ "temperature": temperature,
+ "max_tokens": max_tokens,
+ }
+ try:
+ resp = requests.post(
+ url,
+ headers=headers,
+ json=payload,
+ proxies=self.proxies,
+ timeout=self.timeout,
+ )
+ except Exception as e:
+ LOG.error(f"AI request failed: {e}")
+ return None
+ if resp.status_code != 200:
+ LOG.error(
+ f"AI request failed with status {resp.status_code}: {resp.text[:300]}"
+ )
+ return None
+ try:
+ data = resp.json()
+ return data["choices"][0]["message"]["content"]
+ except Exception as e:
+ LOG.error(f"AI response parse failed: {e}")
+ return None
+
+ def understand(self, text: str):
+ """将自然语言输入解析为搜索意图 dict,失败返回 None。"""
+ if not self.enabled:
+ return None
+ messages = [
+ {"role": "system", "content": SYSTEM_PROMPT},
+ {"role": "user", "content": text},
+ ]
+ content = self.chat(messages)
+ if not content:
+ return None
+ LOG.info(f"AI 原始返回: {content}")
+ intent = self._parse_json(content)
+ LOG.info(f"AI 解析意图: {intent}")
+ return intent
+
+ @staticmethod
+ def _parse_json(content: str):
+ content = (content or "").strip()
+ content = re.sub(r"^```(?:json)?\s*", "", content)
+ content = re.sub(r"\s*```$", "", content)
+ try:
+ return json.loads(content)
+ except Exception:
+ pass
+ start = content.find("{")
+ end = content.rfind("}")
+ if start == -1 or end == -1 or end <= start:
+ LOG.error(f"AI returned non-JSON content: {content[:300]}")
+ return None
+ try:
+ return json.loads(content[start : end + 1])
+ except Exception as e:
+ LOG.error(f"AI JSON parse failed: {e}, content: {content[:300]}")
+ return None
diff --git a/telegram/tg-search-bot/bot.py b/telegram/tg-search-bot/bot.py
new file mode 100644
index 0000000..3684659
--- /dev/null
+++ b/telegram/tg-search-bot/bot.py
@@ -0,0 +1,1466 @@
+import concurrent.futures
+import math
+import os
+import re
+import string
+import random
+import jvav as jv
+import yaml
+import threading
+import langdetect
+import html
+import telebot
+from telebot import apihelper, types
+from telebot.types import InlineKeyboardButton, InlineKeyboardMarkup, InputMediaPhoto
+from database import BotFileDb, BotCacheDb
+from ai import AiClient
+from pikpak import PikPakClient
+from requests import get
+from requests.compat import quote
+from bs4 import BeautifulSoup
+import logging
+from logging.handlers import RotatingFileHandler
+
+
+class Logger:
+
+ def __init__(self, path_log_file: str, log_level=logging.INFO):
+ self.logger = logging.getLogger()
+ formatter = logging.Formatter("[%(asctime)s] %(levelname)s: %(message)s")
+ stream_handler = logging.StreamHandler()
+ stream_handler.setFormatter(formatter)
+ r_file_handler = RotatingFileHandler(
+ path_log_file, maxBytes=1024 * 1024 * 16, backupCount=1
+ )
+ r_file_handler.setFormatter(formatter)
+ self.logger.addHandler(r_file_handler)
+ self.logger.addHandler(stream_handler)
+ self.logger.setLevel(log_level)
+
+
+class BotConfig:
+ def __init__(self, path_config_file: str):
+ with open(path_config_file, "r", encoding="utf8") as f:
+ config = yaml.safe_load(f)
+ self.tg_chat_id = str(config["tg_chat_id"]) if config["tg_chat_id"] else ""
+ self.tg_bot_token = (
+ str(config["tg_bot_token"]) if config["tg_bot_token"] else ""
+ )
+ self.enable_nsfw = str(config["enable_nsfw"]) if config["enable_nsfw"] else "0"
+ self.use_proxy = str(config["use_proxy"]) if config["use_proxy"] else "0"
+ self.proxy_addr = str(config["proxy_addr"]) if config["proxy_addr"] else ""
+ self.pikpak_username = (
+ str(config["pikpak_username"]) if config.get("pikpak_username") else ""
+ )
+ self.pikpak_password = (
+ str(config["pikpak_password"]) if config.get("pikpak_password") else ""
+ )
+ self.ai_base_url = (
+ str(config["ai_base_url"]) if config.get("ai_base_url") else ""
+ )
+ self.ai_api_key = str(config["ai_api_key"]) if config.get("ai_api_key") else ""
+ self.ai_model = (
+ str(config["ai_model"]) if config.get("ai_model") else "gpt-4o-mini"
+ )
+ # set
+ self.proxy_json = {"http": "", "https": ""}
+ if self.use_proxy == "1":
+ self.proxy_json = {"http": self.proxy_addr, "https": self.proxy_addr}
+ LOG.info(f'Set proxy: "{self.proxy_addr}"')
+ else:
+ self.proxy_addr = ""
+ LOG.info("Successfully read and loaded the configuration file.")
+
+
+# URL
+BASE_URL_TG = "https://t.me"
+PIKPAK_BOT_NAME = "PikPak6_Bot"
+URL_PROJECT_ADDRESS = "https://github.com/akynazh/tg-search-bot"
+URL_PIKPAK_BOT = f"{BASE_URL_TG}/{PIKPAK_BOT_NAME}"
+# PATH
+PATH_ROOT = f'{os.path.expanduser("~")}/.tg_search_bot'
+PATH_LOG_FILE = f"{PATH_ROOT}/log.txt"
+PATH_RECORD_FILE = f"{PATH_ROOT}/record.json"
+PATH_PIKPAK_TOKEN_FILE = f"{PATH_ROOT}/pikpak_token.json"
+PATH_CACHE_FILE = f"{PATH_ROOT}/cache.db"
+PATH_CONFIG_FILE = f"{PATH_ROOT}/config.yaml"
+# BASE
+LOG = Logger(path_log_file=PATH_LOG_FILE).logger
+BOT_CFG = BotConfig(PATH_CONFIG_FILE)
+apihelper.proxy = BOT_CFG.proxy_json
+BOT = telebot.TeleBot(BOT_CFG.tg_bot_token)
+BOT_DB = BotFileDb(PATH_RECORD_FILE)
+BOT_CACHE_DB = BotCacheDb(
+ path_cache_file=PATH_CACHE_FILE,
+ use_cache="1",
+)
+BASE_UTIL = jv.BaseUtil(BOT_CFG.proxy_addr)
+DMM_UTIL = jv.DmmUtil(BOT_CFG.proxy_addr)
+JBUS_UTIL = jv.JavBusUtil(BOT_CFG.proxy_addr)
+JDB_UTIL = jv.JavDbUtil(BOT_CFG.proxy_addr)
+JLIB_UTIL = jv.JavLibUtil(BOT_CFG.proxy_addr)
+SUKEBEI_UTIL = jv.SukebeiUtil(BOT_CFG.proxy_addr)
+TRANS_UTIL = jv.TransUtil(BOT_CFG.proxy_addr)
+WIKI_UTIL = jv.WikiUtil(BOT_CFG.proxy_addr)
+VGLE_UTIL = jv.AvgleUtil(BOT_CFG.proxy_addr)
+EXECUTOR = concurrent.futures.ThreadPoolExecutor()
+PIKPAK = PikPakClient(
+ username=BOT_CFG.pikpak_username,
+ password=BOT_CFG.pikpak_password,
+ proxy=BOT_CFG.proxy_addr,
+ token_path=PATH_PIKPAK_TOKEN_FILE,
+)
+AI = AiClient(
+ base_url=BOT_CFG.ai_base_url,
+ api_key=BOT_CFG.ai_api_key,
+ model=BOT_CFG.ai_model,
+ proxy=BOT_CFG.proxy_addr,
+)
+# BT 搜索结果分页会话:token -> {"q": ..., "bts": [...], "page": n}
+BT_SESSIONS = {}
+CHAT_BT_SESSION = {}
+ID_PAT = re.compile(r"[a-z0-9]+[-_](?:ppv-)?[a-z0-9]+")
+BOT_CMDS = {
+ "help": "查看帮助",
+ "stars": "查看已收藏的演职人员",
+ "ids": "查看已收藏的编号",
+ "record": "导出收藏记录文件",
+}
+MSG_HELP = f"""直接发送片名、关键词或编号,剩下的交给我!
+
+"""
+for cmd, content in BOT_CMDS.items():
+ MSG_HELP += f"""/{cmd} {content}
+"""
+MSG_HELP += f"""
+[NSFW: {"已开启" if BOT_CFG.enable_nsfw == "1" else "已关闭"}]"""
+
+
+class BotKey:
+ KEY_GET_SAMPLE_BY_ID = "k0_0"
+ KEY_GET_MORE_MAGNETS_BY_ID = "k0_1"
+ KEY_SEARCH_STAR_BY_NAME = "k0_2"
+ KEY_WATCH_PV_BY_ID = "k1_0"
+ KEY_WATCH_FV_BY_ID = "k1_1"
+ KEY_GET_V_BY_ID = "k2_0"
+ KEY_RANDOM_GET_V_BY_STAR_ID = "k2_1"
+ KEY_RANDOM_GET_V_NICE = "k2_2"
+ KEY_RANDOM_GET_V_NEW = "k2_3"
+ KEY_GET_NEW_VS_BY_STAR_NAME_ID = "k2_4"
+ KEY_GET_NICE_VS_BY_STAR_NAME = "k2_5"
+ KEY_RECORD_STAR_BY_STAR_NAME_ID = "k3_0"
+ KEY_RECORD_V_BY_ID_STAR_IDS = "k3_1"
+ KEY_GET_STARS_RECORD = "k3_2"
+ KEY_GET_VS_RECORD = "k3_3"
+ KEY_GET_STAR_DETAIL_RECORD_BY_STAR_NAME_ID = "k3_4"
+ KEY_GET_V_DETAIL_RECORD_BY_ID = "k3_5"
+ KEY_UNDO_RECORD_STAR_BY_STAR_NAME_ID = "k3_6"
+ KEY_UNDO_RECORD_V_BY_ID = "k3_7"
+ KEY_DEL_V_CACHE = "k4_1"
+ KEY_BT_PAGE = "k5_0"
+
+
+class BotUtils:
+ v_utils = [JDB_UTIL, JBUS_UTIL, SUKEBEI_UTIL]
+
+ def send_action_typing(self):
+ BOT.send_chat_action(chat_id=BOT_CFG.tg_chat_id, action="typing")
+
+ def send_msg(self, msg: str, pv=False, markup=None):
+ BOT.send_message(
+ chat_id=BOT_CFG.tg_chat_id,
+ text=msg,
+ disable_web_page_preview=not pv,
+ parse_mode="HTML",
+ reply_markup=markup,
+ )
+
+ def send_msg_code_op(self, code: int, op: str):
+ if code == 200:
+ self.send_msg(f"✅ 操作成功:{op}")
+ elif code == 404:
+ self.send_msg(f"没有找到相关结果,{op} 未完成 Q_Q")
+ elif code == 500:
+ self.send_msg(f"服务器出错,{op} 未完成,请稍后重试或查看日志 Q_Q")
+ elif code == 502:
+ self.send_msg(f"网络请求失败,{op} 未完成,请检查网络后重试 Q_Q")
+
+ def send_msg_success_op(self, op: str):
+ self.send_msg(f"✅ 操作成功:{op}")
+
+ def send_msg_fail_reason_op(self, reason: str, op: str):
+ self.send_msg(f"{op} 失败:{reason} Q_Q")
+
+ def send_msg_v_not_found(self, v_id: str):
+ self.send_msg(
+ f"没有找到 {html.escape(v_id)} 的相关结果,请稍后重试或检查编号是否正确。"
+ )
+
+ def check_success(self, code: int, op: str):
+ if code == 200:
+ return True
+ if code == 404:
+ self.send_msg_fail_reason_op(reason="未找到相关结果", op=op)
+ elif code == 500:
+ self.send_msg_fail_reason_op(reason="服务器错误", op=op)
+ elif code == 502:
+ self.send_msg_fail_reason_op(reason="网络请求失败", op=op)
+ return False
+
+ def create_btn_by_key(self, key_type: str, obj):
+ if key_type == BotKey.KEY_GET_STAR_DETAIL_RECORD_BY_STAR_NAME_ID:
+ return InlineKeyboardButton(
+ text=obj["name"], callback_data=f'{obj["name"]}|{obj["id"]}:{key_type}'
+ )
+ elif key_type == BotKey.KEY_GET_V_DETAIL_RECORD_BY_ID:
+ return InlineKeyboardButton(text=obj, callback_data=f"{obj}:{key_type}")
+ elif key_type == BotKey.KEY_SEARCH_STAR_BY_NAME:
+ return InlineKeyboardButton(text=obj, callback_data=f"{obj}:{key_type}")
+ elif key_type == BotKey.KEY_GET_V_BY_ID:
+ return InlineKeyboardButton(
+ text=f'{obj["id"]} | {obj["rate"]}',
+ callback_data=f'{obj["id"]}:{key_type}',
+ )
+
+ def send_msg_btns(
+ self,
+ max_btn_per_row: int,
+ max_row_per_msg: int,
+ key_type: str,
+ title: str,
+ objs: list,
+ extra_btns=[],
+ page_btns=[],
+ ):
+ markup = InlineKeyboardMarkup()
+ row_count = 0
+ btns = []
+ for obj in objs:
+ btns.append(self.create_btn_by_key(key_type, obj))
+ if len(btns) == max_btn_per_row:
+ markup.row(*btns)
+ row_count += 1
+ btns = []
+ if row_count == max_row_per_msg:
+ for extra_btn in extra_btns:
+ markup.row(*extra_btn)
+ if page_btns != []:
+ markup.row(*page_btns)
+ self.send_msg(msg=title, markup=markup)
+ row_count = 0
+ markup = InlineKeyboardMarkup()
+ if btns != []:
+ markup.row(*btns)
+ row_count += 1
+ if row_count != 0:
+ for extra_btn in extra_btns:
+ markup.row(*extra_btn)
+ if page_btns != []:
+ markup.row(*page_btns)
+ self.send_msg(msg=title, markup=markup)
+
+ def get_page_elements(
+ self, objs: list, page: int, col: int, row: int, key_type: str
+ ):
+ """
+ Get the list of objects on the current page, list of pagination buttons, and the title of quantity.
+
+ :param list objs: All objects
+ :param int page: Current page
+ :param int col: Number of columns on the current page
+ :param int row: Number of rows on the current page
+ :param str key_type: Key type
+ :return tuple[list, list, str]: List of objects on the current page, list of pagination buttons, title of quantity
+ """
+ record_count_total = len(objs)
+ record_count_per_page = col * row
+ if record_count_per_page > record_count_total:
+ page_count = 1
+ else:
+ page_count = math.ceil(record_count_total / record_count_per_page)
+ if page > page_count:
+ page = page_count
+ start_idx = (page - 1) * record_count_per_page
+ objs = objs[start_idx : start_idx + record_count_per_page]
+ if page == 1:
+ to_previous = 1
+ else:
+ to_previous = page - 1
+ if page == page_count:
+ to_next = page_count
+ else:
+ to_next = page + 1
+ btn_to_first = InlineKeyboardButton(text="<<", callback_data=f"1:{key_type}")
+ btn_to_previous = InlineKeyboardButton(
+ text="<", callback_data=f"{to_previous}:{key_type}"
+ )
+ btn_to_current = InlineKeyboardButton(
+ text=f"-{page}-", callback_data=f"{page}:{key_type}"
+ )
+ btn_to_next = InlineKeyboardButton(
+ text=">", callback_data=f"{to_next}:{key_type}"
+ )
+ btn_to_last = InlineKeyboardButton(
+ text=">>", callback_data=f"{page_count}:{key_type}"
+ )
+ # Get the title of quantity
+ title = f"共 {record_count_total} 条,共 {page_count} 页"
+ return (
+ objs,
+ [btn_to_first, btn_to_previous, btn_to_current, btn_to_next, btn_to_last],
+ title,
+ )
+
+ def check_if_enable_nsfw(self):
+ if BOT_CFG.enable_nsfw == "0":
+ self.send_msg("[NSFW] 已关闭,无法访问该内容。")
+ return False
+ return True
+
+ def get_stars_record(self, page=1):
+ record, is_star_exists, _ = BOT_DB.check_has_record()
+ if not record or not is_star_exists:
+ self.send_msg_fail_reason_op(
+ reason="还没有收藏任何演职人员", op="查看收藏的演职人员"
+ )
+ return
+ stars = record["stars"]
+ stars.reverse()
+ col, row = 4, 5
+ objs, page_btns, title = self.get_page_elements(
+ objs=stars,
+ page=page,
+ col=col,
+ row=row,
+ key_type=BotKey.KEY_GET_STARS_RECORD,
+ )
+ self.send_msg_btns(
+ max_btn_per_row=col,
+ max_row_per_msg=row,
+ key_type=BotKey.KEY_GET_STAR_DETAIL_RECORD_BY_STAR_NAME_ID,
+ title="已收藏的演职人员:" + title,
+ objs=objs,
+ page_btns=page_btns,
+ )
+
+ def get_star_detail_record_by_name_id(self, star_name: str, star_id: str):
+ record, is_stars_exists, is_vs_exists = BOT_DB.check_has_record()
+ if not record:
+ self.send_msg_fail_reason_op(
+ reason="还没有收藏该演职人员",
+ op=f"查看演职人员 {star_name} 的详情",
+ )
+ return
+ star_vs = []
+ cur_star_exists = False
+ if is_vs_exists:
+ vs = record["vs"]
+ vs.reverse()
+ for v in vs:
+ if star_id in v["stars"]:
+ star_vs.append(v["id"])
+ if is_stars_exists:
+ stars = record["stars"]
+ for star in stars:
+ if star["id"].lower() == star_id.lower():
+ cur_star_exists = True
+ extra_btn1 = InlineKeyboardButton(
+ text="随机一部",
+ callback_data=f"{star_name}|{star_id}:{BotKey.KEY_RANDOM_GET_V_BY_STAR_ID}",
+ )
+ extra_btn2 = InlineKeyboardButton(
+ text="最新作品",
+ callback_data=f"{star_name}|{star_id}:{BotKey.KEY_GET_NEW_VS_BY_STAR_NAME_ID}",
+ )
+ extra_btn3 = InlineKeyboardButton(
+ text="高分作品",
+ callback_data=f"{star_name}:{BotKey.KEY_GET_NICE_VS_BY_STAR_NAME}",
+ )
+ if cur_star_exists:
+ extra_btn4 = InlineKeyboardButton(
+ text="取消收藏",
+ callback_data=f"{star_name}|{star_id}:{BotKey.KEY_UNDO_RECORD_STAR_BY_STAR_NAME_ID}",
+ )
+ else:
+ extra_btn4 = InlineKeyboardButton(
+ text="收藏",
+ callback_data=f"{star_name}|{star_id}:{BotKey.KEY_RECORD_STAR_BY_STAR_NAME_ID}",
+ )
+ title = f'{star_name} | Wiki | Javbus'
+ if len(star_vs) == 0:
+ markup = InlineKeyboardMarkup()
+ markup.row(extra_btn1, extra_btn2, extra_btn3, extra_btn4)
+ self.send_msg(msg=title, markup=markup)
+ return
+ self.send_msg_btns(
+ max_btn_per_row=4,
+ max_row_per_msg=10,
+ key_type=BotKey.KEY_GET_V_DETAIL_RECORD_BY_ID,
+ title=title,
+ objs=star_vs,
+ extra_btns=[[extra_btn1, extra_btn2, extra_btn3, extra_btn4]],
+ )
+
+ def get_vs_record(self, page=1):
+ record, _, is_vs_exists = BOT_DB.check_has_record()
+ if not record or not is_vs_exists:
+ self.send_msg_fail_reason_op(
+ reason="还没有收藏任何编号",
+ op="查看收藏的编号",
+ )
+ return
+ vs = [v["id"] for v in record["vs"]]
+ vs.reverse()
+ extra_btn1 = InlineKeyboardButton(
+ text="随机高分",
+ callback_data=f"0:{BotKey.KEY_RANDOM_GET_V_NICE}",
+ )
+ extra_btn2 = InlineKeyboardButton(
+ text="随机最新", callback_data=f"0:{BotKey.KEY_RANDOM_GET_V_NEW}"
+ )
+ col, row = 4, 10
+ objs, page_btns, title = self.get_page_elements(
+ objs=vs, page=page, col=col, row=row, key_type=BotKey.KEY_GET_VS_RECORD
+ )
+ self.send_msg_btns(
+ max_btn_per_row=col,
+ max_row_per_msg=row,
+ key_type=BotKey.KEY_GET_V_DETAIL_RECORD_BY_ID,
+ title="已收藏的编号:" + title,
+ objs=objs,
+ extra_btns=[[extra_btn1, extra_btn2]],
+ page_btns=page_btns,
+ )
+
+ def get_v_detail_record_by_id(self, id: str):
+ record, _, is_vs_exists = BOT_DB.check_has_record()
+ vs = record["vs"]
+ cur_v_exists = False
+ for v in vs:
+ if id.lower() == v["id"].lower():
+ cur_v_exists = True
+ markup = InlineKeyboardMarkup()
+ btn = InlineKeyboardButton(
+ text=f"查看",
+ callback_data=f"{id}:{BotKey.KEY_GET_V_BY_ID}",
+ )
+ if cur_v_exists:
+ markup.row(
+ btn,
+ InlineKeyboardButton(
+ text=f"取消收藏",
+ callback_data=f"{id}:{BotKey.KEY_UNDO_RECORD_V_BY_ID}",
+ ),
+ )
+ else:
+ markup.row(btn)
+ self.send_msg(msg=f"{id}", markup=markup)
+
+ def search_bts(self, q):
+ def append_trackers():
+ """Returns the base tracker list"""
+ trackers = [
+ "udp://tracker.coppersurfer.tk:6969/announce",
+ "udp://tracker.openbittorrent.com:6969/announce",
+ "udp://9.rarbg.to:2710/announce",
+ "udp://9.rarbg.me:2780/announce",
+ "udp://9.rarbg.to:2730/announce",
+ "udp://tracker.opentrackr.org:1337",
+ "http://p4p.arenabg.com:1337/announce",
+ "udp://tracker.torrent.eu.org:451/announce",
+ "udp://tracker.tiny-vps.com:6969/announce",
+ "udp://open.stealth.si:80/announce",
+ ]
+ trackers = [quote(tr) for tr in trackers]
+ return "&tr=".join(trackers)
+
+ def category_name(category):
+ """Translates the category code to a name"""
+ names = ["", "audio", "video", "apps", "games", "nsfw", "other"]
+ category = int(category[0])
+ category = category if category < len(names) - 1 else -1
+ return names[category]
+
+ def size_as_str(size):
+ """Formats the file size in bytes to kb, mb or gb accordingly"""
+ size = int(size)
+ size_str = f"{size} b"
+ if size >= 1024:
+ size_str = f"{(size / 1024):.2f} kb"
+ if size >= 1024**2:
+ size_str = f"{(size / 1024 ** 2):.2f} mb"
+ if size >= 1024**3:
+ size_str = f"{(size / 1024 ** 3):.2f} gb"
+ return size_str
+
+ def magnet_link(ih, name):
+ """Creates the magnet URI"""
+ return f"magnet:?xt=urn:btih:{ih}&dn={quote(name)}&tr={append_trackers()}"
+
+ agent = BASE_UTIL.ua()
+ url = f"https://apibay.org/q.php?q={quote(q)}"
+ try:
+ results = get(url, headers={"agent": agent}, timeout=10)
+ except Exception as e:
+ LOG.error(f"apibay search request failed: {e}")
+ return None
+ if not results.status_code == 200:
+ return None
+ matches = []
+ data = results.json()
+ if data and "no results" in data[0]["name"].lower():
+ return matches
+ for d in data:
+ matches.append(
+ {
+ "seeders": d["seeders"],
+ "leechers": d["leechers"],
+ "name": d["name"],
+ "category": category_name(d["category"]),
+ "size": size_as_str(d["size"]),
+ "magnet": magnet_link(d["info_hash"], d["name"]),
+ }
+ )
+ return matches
+
+ def search_bts_torrentkitty(self, q):
+ """通过 TorrentKitty 搜索中文 BT 资源,返回与 search_bts 相同格式的列表或 None。
+
+ TorrentKitty 聚合国内多家 BT 站,中文关键词命中率远高于 apibay。
+ """
+ url = f"https://www.torrentkitty.tv/search/{quote(q)}"
+ try:
+ resp = get(
+ url,
+ headers={"user-agent": BASE_UTIL.ua()},
+ timeout=10,
+ )
+ except Exception as e:
+ LOG.error(f"TorrentKitty search request failed: {e}")
+ return None
+ if resp.status_code != 200:
+ return None
+ try:
+ soup = BeautifulSoup(resp.text, "html.parser")
+ matches = []
+ for tr in soup.find_all("tr"):
+ name_td = tr.find("td", class_="name")
+ size_td = tr.find("td", class_="size")
+ magnet_a = tr.find("a", rel="magnet")
+ if not name_td or not magnet_a:
+ continue
+ matches.append(
+ {
+ "seeders": 0,
+ "leechers": 0,
+ "name": name_td.get_text(strip=True),
+ "category": "general",
+ "size": size_td.get_text(strip=True) if size_td else "",
+ "magnet": magnet_a.get("href"),
+ }
+ )
+ return matches if matches else None
+ except Exception as e:
+ LOG.error(f"TorrentKitty search parse failed: {e}")
+ return None
+
+ def get_v_by_id(
+ self,
+ id: str,
+ send_to_pikpak=True,
+ is_nice=True,
+ is_uncensored=True,
+ magnet_max_count=3,
+ not_send=False,
+ ):
+ """
+ Get based on id
+
+ :param str id: Number
+ :param bool send_to_pikpak: Whether to send to pikpak, default is yes
+ :param bool is_nice: Whether to filter out HD, subtitled magnet links, default is yes
+ :param bool is_uncensored: Whether to filter out uncensored magnet links, default is yes
+ :param int magnet_max_count: Maximum id of magnet links after filtering, default is 3
+ :param not_send: Whether not to send results, default is to send
+ :return dict: When not sending results, return the obtained results (if any)
+ """
+ if not self.check_if_enable_nsfw():
+ return {}
+ op_get_v_by_id = f"搜索编号 {id}"
+ v = BOT_CACHE_DB.get_cache(key=id, type=BotCacheDb.TYPE_V)
+ v_score = None
+ is_cache = False
+ if not v or not_send:
+ v_util = None
+ for util in self.v_utils:
+ code, v = util.get_av_by_id(
+ id=id,
+ is_nice=is_nice,
+ is_uncensored=is_uncensored,
+ magnet_max_count=magnet_max_count,
+ )
+ if code == 200:
+ v_util = util
+ break
+ if not v_util:
+ if not not_send:
+ self.send_msg_v_not_found(v_id=id)
+ return
+ if "score" not in v.keys():
+ _, v["score"] = DMM_UTIL.get_score_by_id(id)
+ if not not_send:
+ if len(v["magnets"]) == 0:
+ BOT_CACHE_DB.set_cache(
+ key=id, value=v, type=BotCacheDb.TYPE_V, expire=3600 * 24 * 1
+ )
+ else:
+ BOT_CACHE_DB.set_cache(key=id, value=v, type=BotCacheDb.TYPE_V)
+ else:
+ v_score = v["score"]
+ is_cache = True
+ if not_send:
+ return v
+ v_id = id
+ v_title = v["title"]
+ v_img = v["img"]
+ v_date = v["date"]
+ v_tags = v["tags"]
+ v_stars = v["stars"]
+ v_magnets = v["magnets"]
+ v_url = v["url"]
+ LOG.info(f"AV 搜索结果: {v_id} | {v_title}")
+ for _m in v_magnets:
+ LOG.info(f" 磁力: {_m['link']}")
+ msg = ""
+ if v_title != "":
+ v_title = v_title.replace("<", "").replace(">", "")
+ msg += f"""【标题】{v_title}
+"""
+ msg += f"""【编号】{v_id}
+"""
+ if v_date != "":
+ msg += f"""【日期】{v_date}
+"""
+ if v_score:
+ msg += f"""【评分】{v_score}
+"""
+ if v_stars != []:
+ show_star_name = v_stars[0]["name"]
+ show_star_id = v_stars[0]["id"]
+ stars_msg = ""
+ for star in v_stars:
+ stars_msg += f"""【演职人员】{star["name"]}
+"""
+ msg += stars_msg
+ if v_tags:
+ v_tags = " ".join(v_tags).replace("<", "").replace(">", "")
+ msg += f"""【标签】{v_tags}
+"""
+ msg += f"""【其他】Pikpak | 项目主页
+"""
+ magnet_send_to_pikpak = ""
+ for i, magnet in enumerate(v_magnets):
+ if i == 0:
+ magnet_send_to_pikpak = magnet["link"]
+ magnet_tags = ""
+ if magnet["uc"] == "1":
+ magnet_tags += "无码 "
+ if magnet["hd"] == "1":
+ magnet_tags += "HD "
+ if magnet["zm"] == "1":
+ magnet_tags += "中字 "
+ msg_tmp = f"""【{magnet_tags}磁力-{string.ascii_letters[i].upper()} {magnet["size"]}】{magnet["link"]}
+"""
+ if len(msg + msg_tmp) >= 2000:
+ break
+ msg += msg_tmp
+ pv_btn = InlineKeyboardButton(
+ text="预览", callback_data=f"{v_id}:{BotKey.KEY_WATCH_PV_BY_ID}"
+ )
+ fv_btn = InlineKeyboardButton(
+ text="在线观看", callback_data=f"{v_id}:{BotKey.KEY_WATCH_FV_BY_ID}"
+ )
+ sample_btn = InlineKeyboardButton(
+ text="截图", callback_data=f"{v_id}:{BotKey.KEY_GET_SAMPLE_BY_ID}"
+ )
+ more_btn = InlineKeyboardButton(
+ text="更多磁力",
+ callback_data=f"{v_id}:{BotKey.KEY_GET_MORE_MAGNETS_BY_ID}",
+ )
+ if len(v_magnets) != 0:
+ markup = InlineKeyboardMarkup().row(sample_btn, pv_btn, fv_btn, more_btn)
+ else:
+ markup = InlineKeyboardMarkup().row(sample_btn, pv_btn, fv_btn)
+ star_record_btn = None
+ if len(v_stars) == 1:
+ if BOT_DB.check_star_exists_by_id(star_id=show_star_id):
+ star_record_btn = InlineKeyboardButton(
+ text="详情",
+ callback_data=f"{show_star_name}|{show_star_id}:{BotKey.KEY_GET_STAR_DETAIL_RECORD_BY_STAR_NAME_ID}",
+ )
+ else:
+ star_record_btn = InlineKeyboardButton(
+ text="收藏演职人员",
+ callback_data=f"{show_star_name}|{show_star_id}:{BotKey.KEY_RECORD_STAR_BY_STAR_NAME_ID}",
+ )
+ star_ids = ""
+ for i, star in enumerate(v_stars):
+ star_ids += star["id"] + "|"
+ if i >= 5:
+ star_ids += "...|"
+ break
+ if star_ids != "":
+ star_ids = star_ids[: len(star_ids) - 1]
+ v_record_btn = None
+ if BOT_DB.check_id_exists(id=v_id):
+ v_record_btn = InlineKeyboardButton(
+ text="详情",
+ callback_data=f"{v_id}:{BotKey.KEY_GET_V_DETAIL_RECORD_BY_ID}",
+ )
+ else:
+ v_record_btn = InlineKeyboardButton(
+ text="收藏",
+ callback_data=f"{v_id}|{star_ids}:{BotKey.KEY_RECORD_V_BY_ID_STAR_IDS}",
+ )
+ renew_btn = None
+ if is_cache:
+ renew_btn = InlineKeyboardButton(
+ text="刷新", callback_data=f"{v_id}:{BotKey.KEY_DEL_V_CACHE}"
+ )
+ if star_record_btn and renew_btn:
+ markup.row(v_record_btn, star_record_btn, renew_btn)
+ elif star_record_btn:
+ markup.row(v_record_btn, star_record_btn)
+ elif renew_btn:
+ markup.row(v_record_btn, renew_btn)
+ else:
+ markup.row(v_record_btn)
+ if v_img == "":
+ self.send_msg(msg=msg, markup=markup)
+ else:
+ try:
+ BOT.send_photo(
+ chat_id=BOT_CFG.tg_chat_id,
+ photo=v_img,
+ caption=msg,
+ parse_mode="HTML",
+ reply_markup=markup,
+ )
+ except Exception:
+ self.send_msg(msg=msg, markup=markup)
+ if magnet_send_to_pikpak != "" and send_to_pikpak:
+ self.send_magnet_to_pikpak(magnet_send_to_pikpak, v_id)
+
+ def send_magnet_to_pikpak(self, magnet: str, id: str):
+ if not PIKPAK.enabled:
+ self.send_msg_fail_reason_op(
+ reason="请在 config.yaml 中配置 PikPak 账号 (pikpak_username / pikpak_password)",
+ op=f"保存编号 {id} 的磁力链接到 PikPak",
+ )
+ return
+ self.send_msg("💾 正在保存到 PikPak 网盘 ...")
+ ok, msg = PIKPAK.offline_download(magnet)
+ if ok:
+ self.send_msg(f"✅ 保存结果:{msg}")
+ else:
+ self.send_msg_fail_reason_op(
+ reason=msg, op=f"保存编号 {id} 的磁力链接到 PikPak"
+ )
+
+ def get_bts_by_keyword(self, q):
+ """按关键词搜索 BT 资源(带缓存),返回资源列表或 None。
+
+ 并行搜索 TorrentKitty(中文)与 apibay(英文)两个来源的结果,按磁力 info_hash 去重。
+ """
+ bts = BOT_CACHE_DB.get_cache(key=q, type=BotCacheDb.TYPE_BT)
+ if bts:
+ return bts
+ merged = []
+ seen = set()
+ # 并行搜索两个来源,但每个来源最多等待短时间,避免长时间无响应。
+ with concurrent.futures.ThreadPoolExecutor(max_workers=2) as executor:
+ tk_future = executor.submit(self.search_bts_torrentkitty, q)
+ ab_future = executor.submit(self.search_bts, q)
+ srcs = []
+ for name, future in (("torrentkitty", tk_future), ("apibay", ab_future)):
+ try:
+ srcs.append(future.result(timeout=8))
+ except concurrent.futures.TimeoutError:
+ LOG.warning(f"BT source {name} timed out for query: {q}")
+ srcs.append([])
+ for src in srcs:
+ for bt in src or []:
+ if not bt.get("magnet"):
+ continue
+ m = re.search(r"urn:btih:([A-Za-z0-9]+)", bt["magnet"])
+ key = m.group(1).lower() if m else bt["magnet"]
+ if key in seen:
+ continue
+ seen.add(key)
+ merged.append(bt)
+ if not merged:
+ return None
+ if BOT_CFG.enable_nsfw == "0":
+ merged = list(filter(lambda bt: bt["category"] != "nsfw", merged))
+ merged = list(filter(lambda bt: "nsfw" not in bt["name"].lower(), merged))
+ merged = merged[:30]
+ BOT_CACHE_DB.set_cache(key=q, value=merged, type=BotCacheDb.TYPE_BT)
+ LOG.info(f"BT 搜索结果 {len(merged)} 条: {q}")
+ for _bt in merged:
+ LOG.info(f" {_bt['name']} | {_bt['size']} | {_bt['magnet']}")
+ return merged
+
+ def search_bts_and_save(self, q):
+ try:
+ bts = self.get_bts_by_keyword(q)
+ except Exception as e:
+ LOG.error(f"BT 搜索异常: {e}")
+ self.send_msg_fail_reason_op(
+ reason=f"搜索超时或网络错误:{str(e)[:50]}",
+ op=f"搜索 {html.escape(q)}",
+ )
+ return False
+ if not bts:
+ self.send_msg_fail_reason_op(
+ reason="没有找到相关资源", op=f"搜索 {html.escape(q)}"
+ )
+ return False
+ self.show_bt_results(q, bts, save_first=True)
+ return True
+
+ def search_av_keyword(self, q):
+ """按关键词搜索 AV(JavDB 标签搜索),找到则返回 True。"""
+ code, ids = JDB_UTIL.get_ids_by_tag(q)
+ if code == 200 and ids:
+ self.get_v_by_id(id=ids[0])
+ return True
+ return False
+
+ def handle_nlp_search(self, msg):
+ """AI 自然语言理解搜索流程。返回 True 表示已处理。"""
+ if not AI.enabled:
+ return False
+ LOG.info(f'AI 搜索字符: "{msg}"')
+ intent = AI.understand(msg)
+ LOG.info(f"AI 返回结果: {intent}")
+ if not intent:
+ return False
+ target = (intent.get("target") or msg).strip()
+ kind = (intent.get("intent") or "general").strip().lower()
+ explain = (intent.get("explain") or target).strip()
+ source = (intent.get("source") or "auto").strip().lower()
+
+ # AV 相关意图需先检查 NSFW 开关
+ if kind in ("av_id", "actor") and not self.check_if_enable_nsfw():
+ return True
+
+ self.send_msg(f"🔍 搜索:{html.escape(explain)}")
+ self.send_msg("⏳ 搜索中 ...")
+
+ if kind == "av_id":
+ self.get_v_by_id(id=target)
+ return True
+ if kind == "actor":
+ # 仅在 AI 明确判定为日本 AV 演员时,才走演员搜索;其他“演员/明星”类请求继续走一般搜索
+ self.search_star_by_name(target)
+ return True
+
+ # 类型 / 关键词 / 剧情 / 其他:优先 AV 关键词搜索,失败则 BT 搜索
+ if (
+ source in ("javdb", "javbus", "sukebei", "dmm")
+ and BOT_CFG.enable_nsfw == "1"
+ ):
+ if self.search_av_keyword(target):
+ return True
+ # BT 搜索(总是返回 True,表示已处理;搜索结果由 search_bts_and_save 内部反馈给用户)
+ self.search_bts_and_save(target)
+ return True
+
+ def get_sample_by_id(self, id: str):
+ op_get_sample = f"获取编号 {id} 的截图"
+ samples = BOT_CACHE_DB.get_cache(key=id, type=BotCacheDb.TYPE_SAMPLE)
+ if not samples:
+ code, samples = JBUS_UTIL.get_samples_by_id(id)
+ if not self.check_success(code, op_get_sample):
+ return
+ BOT_CACHE_DB.set_cache(key=id, value=samples, type=BotCacheDb.TYPE_SAMPLE)
+ samples_imp = []
+ sample_error = False
+ for sample in samples:
+ samples_imp.append(InputMediaPhoto(sample))
+ if len(samples_imp) == 10:
+ try:
+ BOT.send_media_group(chat_id=BOT_CFG.tg_chat_id, media=samples_imp)
+ samples_imp = []
+ except Exception:
+ sample_error = True
+ self.send_msg_fail_reason_op(
+ reason="图片解析失败", op=op_get_sample
+ )
+ break
+ if samples_imp != [] and not sample_error:
+ try:
+ BOT.send_media_group(chat_id=BOT_CFG.tg_chat_id, media=samples_imp)
+ except Exception:
+ self.send_msg_fail_reason_op(reason="图片解析失败", op=op_get_sample)
+
+ def watch_v_by_id(self, id: str, type: int):
+ id = id.lower()
+ if id.find("fc2") != -1 and id.find("ppv") == -1:
+ id = id.replace("fc2", "fc2-ppv")
+ if type == 0:
+ pv = BOT_CACHE_DB.get_cache(key=id, type=BotCacheDb.TYPE_PV)
+ if not pv:
+ op_watch_v = f"获取编号 {id} 的预览视频"
+ futures = {}
+ with concurrent.futures.ThreadPoolExecutor() as executor:
+ futures[executor.submit(DMM_UTIL.get_pv_by_id, id)] = 1
+ futures[executor.submit(VGLE_UTIL.get_pv_by_id, id)] = 2
+ for future in concurrent.futures.as_completed(futures):
+ if futures[future] == 1:
+ code_dmm, pv_dmm = future.result()
+ elif futures[future] == 2:
+ code_vgle, pv_vgle = future.result()
+ if code_dmm != 200 and code_vgle != 200:
+ if code_dmm == 502 or code_vgle == 502:
+ self.send_msg_code_op(502, op_watch_v)
+ else:
+ self.send_msg_code_op(404, op_watch_v)
+ return
+ from_site = ""
+ pv_src = ""
+ if code_dmm == 200:
+ from_site = "dmm"
+ pv_src = pv_dmm
+ elif code_vgle == 200:
+ from_site = "avgle"
+ pv_src = pv_vgle
+ pv_cache = {"from_site": from_site, "src": pv_src}
+ BOT_CACHE_DB.set_cache(key=id, value=pv_cache, type=BotCacheDb.TYPE_PV)
+ else:
+ from_site = pv["from_site"]
+ pv_src = pv["src"]
+ if from_site == "dmm":
+ try:
+ pv_src_nice = DMM_UTIL.get_nice_pv_by_src(pv_src)
+ BOT.send_video(
+ chat_id=BOT_CFG.tg_chat_id,
+ video=pv_src,
+ caption=f'来自 DMM 的搜索结果。点此观看更清晰的版本。',
+ parse_mode="HTML",
+ )
+ except Exception:
+ self.send_msg(
+ f'来自 DMM 的搜索结果,但视频解析失败:视频链接 Q_Q。'
+ )
+ elif from_site == "avgle":
+ try:
+ BOT.send_video(
+ chat_id=BOT_CFG.tg_chat_id,
+ video=pv_src,
+ caption=f'来自 Avgle 的搜索结果:视频链接。',
+ parse_mode="HTML",
+ )
+ except Exception:
+ self.send_msg(
+ f'来自 Avgle 的搜索结果,但视频解析失败:视频链接 Q_Q。'
+ )
+ elif type == 1:
+ video = BOT_CACHE_DB.get_cache(key=id, type=BotCacheDb.TYPE_FV)
+ if not video:
+ code, video = VGLE_UTIL.get_fv_by_id(id)
+ if code != 200:
+ self.send_msg("没有找到相关结果。")
+ return
+ BOT_CACHE_DB.set_cache(key=id, value=video, type=BotCacheDb.TYPE_FV)
+ self.send_msg(video)
+
+ def search_star_by_name(self, star_name: str):
+ if not self.check_if_enable_nsfw():
+ return False
+ op_search_star = f"搜索演职人员 {star_name}"
+ star = BOT_CACHE_DB.get_cache(key=star_name, type=BotCacheDb.TYPE_STAR)
+ if not star:
+ star_name_origin = star_name
+ star_name = self.get_star_ja_name_by_zh_name(star_name)
+ code, star = JBUS_UTIL.check_star_exists(star_name)
+ if not self.check_success(code, op_search_star):
+ return
+ BOT_CACHE_DB.set_cache(key=star_name, value=star, type=BotCacheDb.TYPE_STAR)
+ if star_name_origin != star_name:
+ BOT_CACHE_DB.set_cache(
+ key=star_name_origin,
+ value=star,
+ type=BotCacheDb.TYPE_STAR,
+ )
+ star_id = star["star_id"]
+ star_name = star["star_name"]
+ if BOT_DB.check_star_exists_by_id(star_id=star_id):
+ self.get_star_detail_record_by_name_id(star_name=star_name, star_id=star_id)
+ return True
+ markup = InlineKeyboardMarkup()
+ markup.row(
+ InlineKeyboardButton(
+ text="随机一部",
+ callback_data=f"{star_name}|{star_id}:{BotKey.KEY_RANDOM_GET_V_BY_STAR_ID}",
+ ),
+ InlineKeyboardButton(
+ text="最新作品",
+ callback_data=f"{star_name}|{star_id}:{BotKey.KEY_GET_NEW_VS_BY_STAR_NAME_ID}",
+ ),
+ InlineKeyboardButton(
+ text="高分作品",
+ callback_data=f"{star_name}:{BotKey.KEY_GET_NICE_VS_BY_STAR_NAME}",
+ ),
+ InlineKeyboardButton(
+ text=f"收藏 {star_name}",
+ callback_data=f"{star_name}|{star_id}:{BotKey.KEY_RECORD_STAR_BY_STAR_NAME_ID}",
+ ),
+ )
+ star_wiki = f"{WIKI_UTIL.BASE_URL_CHINA_WIKI}/{star_name}"
+ if langdetect.detect(star_name) == "ja":
+ star_wiki = f"{WIKI_UTIL.BASE_URL_JAPAN_WIKI}/{star_name}"
+ self.send_msg(
+ msg=f'{star_name} | Wiki | Javbus',
+ markup=markup,
+ )
+ return True
+
+ def get_more_magnets_by_id(self, id: str):
+ magnets = BOT_CACHE_DB.get_cache(key=id, type=BotCacheDb.TYPE_MAGNET)
+ if not magnets:
+ v = self.get_v_by_id(
+ id=id, is_nice=False, is_uncensored=False, not_send=True
+ )
+ if not v:
+ return
+ magnets = v["magnets"]
+ BOT_CACHE_DB.set_cache(key=id, value=magnets, type=BotCacheDb.TYPE_MAGNET)
+ msg = ""
+ for magnet in magnets:
+ magnet_tags = ""
+ if magnet["uc"] == "1":
+ magnet_tags += "无码 "
+ if magnet["hd"] == "1":
+ magnet_tags += "HD "
+ if magnet["zm"] == "1":
+ magnet_tags += "中字 "
+ star_tag = ""
+ if magnet["hd"] == "1" and magnet["zm"] == "1":
+ star_tag = "*"
+ msg_tmp = f"""【{star_tag}{magnet_tags}磁力 {magnet["size"]}】{magnet["link"]}
+ """
+ if len(msg + msg_tmp) >= 4000:
+ self.send_msg(msg)
+ msg = msg_tmp
+ else:
+ msg += msg_tmp
+ if msg != "":
+ self.send_msg(msg)
+
+ def get_star_new_vs_by_name_id(self, star_name: str, star_id: str):
+ op_get_star_new_vs = f"获取 {star_name} 的最新作品"
+ ids = BOT_CACHE_DB.get_cache(key=star_id, type=BotCacheDb.TYPE_NEW_VS_OF_STAR)
+ if not ids:
+ code, ids = JBUS_UTIL.get_new_ids_by_star_id(star_id=star_id)
+ if not self.check_success(code, op_get_star_new_vs):
+ return
+ BOT_CACHE_DB.set_cache(
+ key=star_id, value=ids, type=BotCacheDb.TYPE_NEW_VS_OF_STAR
+ )
+ title = f"{star_name} 的最新作品"
+ btns = [
+ InlineKeyboardButton(
+ text=id, callback_data=f"{id}:{BotKey.KEY_GET_V_BY_ID}"
+ )
+ for id in ids
+ ]
+ if len(btns) <= 4:
+ self.send_msg(msg=title, markup=InlineKeyboardMarkup().row(*btns))
+ else:
+ markup = InlineKeyboardMarkup()
+ markup.row(*btns[:4])
+ markup.row(*btns[4:])
+ self.send_msg(msg=title, markup=markup)
+
+ def get_star_ja_name_by_zh_name(self, star_name: str):
+ if langdetect.detect(star_name) == "ja":
+ return star_name
+ star_ja_name = BOT_CACHE_DB.get_cache(
+ key=star_name, type=BotCacheDb.TYPE_STAR_JA_NAME
+ )
+ if star_ja_name:
+ return star_ja_name
+ wiki_json = WIKI_UTIL.get_wiki_page_by_lang(
+ topic=star_name, from_lang="zh", to_lang="ja"
+ )
+ if wiki_json and wiki_json["lang"] == "ja":
+ BOT_CACHE_DB.set_cache(
+ key=star_name,
+ value=wiki_json["title"],
+ type=BotCacheDb.TYPE_STAR_JA_NAME,
+ )
+ return wiki_json["title"]
+ return star_name
+
+ def register_bt_session(self, q, bts):
+ token = "".join(random.choices(string.ascii_letters + string.digits, k=8))
+ BT_SESSIONS[token] = {"q": q, "bts": bts, "page": 1}
+ CHAT_BT_SESSION[BOT_CFG.tg_chat_id] = token
+ return token
+
+ def show_bt_results(self, q, bts, save_first=False):
+ token = self.register_bt_session(q, bts)
+ self.show_bt_page(token, 1)
+ if save_first and bts:
+ self.send_magnet_to_pikpak(bts[0]["magnet"], q)
+ return token
+
+ def show_bt_page(self, token, page):
+ sess = BT_SESSIONS.get(token)
+ if not sess:
+ self.send_msg("结果会话已过期,请重新搜索。")
+ return
+ bts = sess["bts"]
+ page_size = 5
+ page_count = math.ceil(len(bts) / page_size) if bts else 1
+ if page < 1:
+ page = 1
+ if page > page_count:
+ page = 1 # 换一批:最后一页回到第一页
+ sess["page"] = page
+ start = (page - 1) * page_size
+ items = bts[start : start + page_size]
+ res = (
+ f"「{html.escape(sess['q'])}」的搜索结果"
+ f"(第 {page}/{page_count} 页):\n\n"
+ )
+ for i, bt in enumerate(items):
+ idx = start + i + 1
+ name = bt.get("name") or ""
+ if len(name) > 80:
+ name = name[:77] + "..."
+ magnet = bt.get("magnet") or ""
+ magnet_preview = magnet
+ if len(magnet_preview) > 80:
+ magnet_preview = magnet_preview[:77] + "..."
+ res += (
+ f"{idx}. {html.escape(name)}\n"
+ f" 大小: {bt.get('size', '')} | 分类: {bt.get('category', 'general')}\n"
+ f" 磁力: {html.escape(magnet_preview)}\n\n"
+ )
+ res = res[:3500] + "\n\n..." if len(res) > 3500 else res
+ markup = InlineKeyboardMarkup()
+ btns = []
+ if page > 1:
+ btns.append(
+ InlineKeyboardButton(
+ "◀ 上一页",
+ callback_data=f"{token}|{page - 1}:{BotKey.KEY_BT_PAGE}",
+ )
+ )
+ btns.append(
+ InlineKeyboardButton(
+ "🔄 换一批",
+ callback_data=f"{token}|{page + 1}:{BotKey.KEY_BT_PAGE}",
+ )
+ )
+ markup.row(*btns)
+ markup.row(InlineKeyboardButton("保存到 PikPak 网盘", url=URL_PIKPAK_BOT))
+ self.send_msg(res, markup=markup)
+
+ def handle_bt_followup(self, msg):
+ """处理 BT 搜索结果的多轮追问:换一批 / 上一页 / 保存第 N 个。"""
+ token = CHAT_BT_SESSION.get(BOT_CFG.tg_chat_id)
+ if not token or token not in BT_SESSIONS:
+ return False
+ sess = BT_SESSIONS[token]
+ m = msg.strip()
+ save_match = re.match(r"^(?:保存|save)\s*第?\s*(\d+)\s*个?$", m)
+ if save_match:
+ n = int(save_match.group(1))
+ bts = sess["bts"]
+ if 1 <= n <= len(bts):
+ self.send_magnet_to_pikpak(bts[n - 1]["magnet"], sess["q"])
+ else:
+ self.send_msg_fail_reason_op(
+ reason=f"没有第 {n} 个结果", op="保存到 PikPak"
+ )
+ return True
+ if m in ("下一页", "下一批", "next"):
+ self.show_bt_page(token, sess["page"] + 1)
+ return True
+ if m in ("上一页", "prev"):
+ self.show_bt_page(token, sess["page"] - 1)
+ return True
+ if m in ("换一批", "换一页", "还有吗", "再来", "more"):
+ self.show_bt_page(token, sess["page"] + 1)
+ return True
+ return False
+
+ def random_get_new_v(self):
+ page = random.randint(1, JLIB_UTIL.MAX_RANK_PAGE)
+ ids = BOT_CACHE_DB.get_cache(key=page, type=BotCacheDb.TYPE_JLIB_PAGE_NEW_VS)
+ if not ids:
+ code, ids = JLIB_UTIL.get_random_ids_from_rank_by_page(
+ page=page, list_type=1
+ )
+ if self.check_success(code, "随机获取最新影片"):
+ BOT_CACHE_DB.set_cache(
+ key=page,
+ value=ids,
+ type=BotCacheDb.TYPE_JLIB_PAGE_NEW_VS,
+ )
+ else:
+ return
+ self.get_v_by_id(id=random.choice(ids))
+
+ def random_get_nice_v(self):
+ page = random.randint(1, JLIB_UTIL.MAX_RANK_PAGE)
+ ids = BOT_CACHE_DB.get_cache(key=page, type=BotCacheDb.TYPE_JLIB_PAGE_NICE_VS)
+ if not ids:
+ code, ids = JLIB_UTIL.get_random_ids_from_rank_by_page(
+ page=page, list_type=0
+ )
+ if self.check_success(code, "随机获取高分影片"):
+ BOT_CACHE_DB.set_cache(
+ key=page,
+ value=ids,
+ type=BotCacheDb.TYPE_JLIB_PAGE_NICE_VS,
+ )
+ else:
+ return
+ self.get_v_by_id(id=random.choice(ids))
+
+ def random_get_nice_star_vs(self, star_name_ori):
+ vs = BOT_CACHE_DB.get_cache(
+ key=star_name_ori, type=BotCacheDb.TYPE_NICE_VS_OF_STAR
+ )
+ if not vs:
+ star_name_ja = self.get_star_ja_name_by_zh_name(star_name_ori)
+ code, vs = DMM_UTIL.get_nice_vs_by_star_name(star_name=star_name_ja)
+ if self.check_success(code, f"获取演职人员 {star_name_ori} 的高分作品"):
+ vs = vs[:60]
+ BOT_CACHE_DB.set_cache(
+ key=star_name_ori,
+ value=vs,
+ type=BotCacheDb.TYPE_NICE_VS_OF_STAR,
+ )
+ if star_name_ja != star_name_ori:
+ BOT_CACHE_DB.set_cache(
+ key=star_name_ja,
+ value=vs,
+ type=BotCacheDb.TYPE_NICE_VS_OF_STAR,
+ )
+ else:
+ return
+ self.send_msg_btns(
+ max_btn_per_row=3,
+ max_row_per_msg=20,
+ key_type=BotKey.KEY_GET_V_BY_ID,
+ title=f"{star_name_ori} 的高分作品",
+ objs=vs,
+ )
+
+
+def handle_callback(call):
+ bot_utils = BotUtils()
+ bot_utils.send_action_typing()
+ LOG.info(f"Handle callback: {call.data}")
+ s = call.data.rfind(":")
+ content = call.data[:s]
+ key_type = call.data[s + 1 :]
+ if key_type == BotKey.KEY_WATCH_PV_BY_ID:
+ bot_utils.watch_v_by_id(id=content, type=0)
+ elif key_type == BotKey.KEY_WATCH_FV_BY_ID:
+ bot_utils.watch_v_by_id(id=content, type=1)
+ elif key_type == BotKey.KEY_GET_SAMPLE_BY_ID:
+ bot_utils.get_sample_by_id(id=content)
+ elif key_type == BotKey.KEY_GET_MORE_MAGNETS_BY_ID:
+ bot_utils.get_more_magnets_by_id(id=content)
+ elif key_type == BotKey.KEY_RANDOM_GET_V_BY_STAR_ID:
+ tmp = content.split("|")
+ star_name = tmp[0]
+ star_id = tmp[1]
+ code, id = JBUS_UTIL.get_id_by_star_id(star_id=star_id)
+ if bot_utils.check_success(
+ code, f"从演职人员 {star_name} 随机选取作品"
+ ):
+ bot_utils.get_v_by_id(id=id)
+ elif key_type == BotKey.KEY_GET_NEW_VS_BY_STAR_NAME_ID:
+ tmp = content.split("|")
+ star_name = tmp[0]
+ star_id = tmp[1]
+ bot_utils.get_star_new_vs_by_name_id(star_name=star_name, star_id=star_id)
+ elif key_type == BotKey.KEY_RECORD_STAR_BY_STAR_NAME_ID:
+ s = content.find("|")
+ star_name = content[:s]
+ star_id = content[s + 1 :]
+ if BOT_DB.record_star_by_name_id(star_name=star_name, star_id=star_id):
+ bot_utils.get_star_detail_record_by_name_id(
+ star_name=star_name, star_id=star_id
+ )
+ else:
+ bot_utils.send_msg_code_op(500, f"收藏演职人员 {star_name}")
+ elif key_type == BotKey.KEY_RECORD_V_BY_ID_STAR_IDS:
+ res = content.split("|")
+ id = res[0]
+ stars = []
+ if res[1] != "":
+ stars = [s for s in res[1:]]
+ if BOT_DB.record_id_by_id_stars(id=id, stars=stars):
+ bot_utils.get_v_detail_record_by_id(id=id)
+ else:
+ bot_utils.send_msg_code_op(500, f"收藏编号 {id}")
+ elif key_type == BotKey.KEY_GET_STARS_RECORD:
+ bot_utils.get_stars_record(page=int(content))
+ elif key_type == BotKey.KEY_GET_VS_RECORD:
+ bot_utils.get_vs_record(page=int(content))
+ elif key_type == BotKey.KEY_GET_STAR_DETAIL_RECORD_BY_STAR_NAME_ID:
+ s = content.find("|")
+ bot_utils.get_star_detail_record_by_name_id(
+ star_name=content[:s], star_id=content[s + 1 :]
+ )
+ elif key_type == BotKey.KEY_GET_V_DETAIL_RECORD_BY_ID:
+ bot_utils.get_v_detail_record_by_id(id=content)
+ elif key_type == BotKey.KEY_GET_V_BY_ID:
+ bot_utils.get_v_by_id(id=content)
+ elif key_type == BotKey.KEY_RANDOM_GET_V_NICE:
+ code, id = JLIB_UTIL.get_random_id_from_rank(0)
+ if bot_utils.check_success(code, "随机获取高分影片"):
+ bot_utils.get_v_by_id(id=id)
+ elif key_type == BotKey.KEY_RANDOM_GET_V_NEW:
+ code, id = JLIB_UTIL.get_random_id_from_rank(1)
+ if bot_utils.check_success(code, "随机获取最新影片"):
+ bot_utils.get_v_by_id(id=id)
+ elif key_type == BotKey.KEY_UNDO_RECORD_V_BY_ID:
+ op_undo_record_v = f"取消收藏编号 {content}"
+ if BOT_DB.undo_record_id(id=content):
+ bot_utils.send_msg_success_op(op_undo_record_v)
+ else:
+ bot_utils.send_msg_fail_reason_op(
+ reason="文件解析错误", op=op_undo_record_v
+ )
+ elif key_type == BotKey.KEY_UNDO_RECORD_STAR_BY_STAR_NAME_ID:
+ s = content.find("|")
+ op_undo_record_star = f"取消收藏演职人员 {content[:s]}"
+ if BOT_DB.undo_record_star_by_id(star_id=content[s + 1 :]):
+ bot_utils.send_msg_success_op(op_undo_record_star)
+ else:
+ bot_utils.send_msg_fail_reason_op(
+ reason="文件解析错误", op=op_undo_record_star
+ )
+ elif key_type == BotKey.KEY_SEARCH_STAR_BY_NAME:
+ star_name = content
+ star_name_alias = ""
+ idx_alias = star_name.find("(")
+ if idx_alias != -1:
+ star_name_alias = star_name[idx_alias + 1 : -1]
+ star_name = star_name[:idx_alias]
+ if not bot_utils.search_star_by_name(star_name) and star_name_alias != "":
+ bot_utils.send_msg(
+ f"尝试搜索演职人员 {star_name} 的别名 {star_name_alias}..."
+ )
+ bot_utils.search_star_by_name(star_name_alias)
+ elif key_type == BotKey.KEY_GET_NICE_VS_BY_STAR_NAME:
+ bot_utils.random_get_nice_star_vs(content)
+ elif key_type == BotKey.KEY_DEL_V_CACHE:
+ BOT_CACHE_DB.remove_cache(key=content, type=BotCacheDb.TYPE_V)
+ BOT_CACHE_DB.remove_cache(key=content, type=BotCacheDb.TYPE_STARS_MSG)
+ bot_utils.get_v_by_id(id=content)
+ elif key_type == BotKey.KEY_BT_PAGE:
+ tmp = content.split("|")
+ bot_utils.show_bt_page(token=tmp[0], page=int(tmp[1]))
+
+
+def handle_message(message):
+ bot_utils = BotUtils()
+ bot_utils.send_action_typing()
+ chat_id = str(message.chat.id)
+ if chat_id.lower() != BOT_CFG.tg_chat_id.lower():
+ return
+ bot_utils = BotUtils()
+ if message.content_type != "text":
+ msg = message.caption
+ else:
+ msg = message.text
+ if not msg:
+ return
+ LOG.info(f'Get message: "{msg}"')
+ msg = msg.lower().strip()
+ msgs = msg.split(" ", 1)
+ msg_cmd = msgs[0]
+ msg_param = ""
+ if len(msgs) > 1:
+ msg_param = msgs[1].strip()
+ if msg_cmd == "/help" or msg_cmd == "/start":
+ bot_utils.send_msg(MSG_HELP)
+ elif msg_cmd == "/stars":
+ bot_utils.get_stars_record()
+ elif msg_cmd == "/ids":
+ bot_utils.get_vs_record()
+ elif msg_cmd == "/record":
+ if not os.path.exists(PATH_RECORD_FILE):
+ bot_utils.send_msg_fail_reason_op(
+ reason="还没有任何收藏记录", op="导出收藏记录"
+ )
+ return
+ BOT.send_document(
+ chat_id=BOT_CFG.tg_chat_id, document=types.InputFile(PATH_RECORD_FILE)
+ )
+ else:
+ # 多轮会话:换一批 / 上一页 / 保存第 N 个
+ if bot_utils.handle_bt_followup(msg):
+ return
+ ids = ID_PAT.findall(msg)
+ if not ids or len(ids) == 0:
+ # 优先走 AI 自然语言理解搜索,失败则退回 BT 关键词搜索
+ if bot_utils.handle_nlp_search(msg):
+ return
+ bts = bot_utils.get_bts_by_keyword(msg)
+ if not bts:
+ bot_utils.send_msg_fail_reason_op(
+ reason="没有找到相关资源",
+ op=f"搜索 {html.escape(msg)}",
+ )
+ return
+ bot_utils.show_bt_results(msg, bts)
+ else:
+ ids = [id.lower() for id in ids]
+ ids = set(ids)
+ ids_msg = ", ".join(ids)
+ bot_utils.send_msg(f"已识别到编号:{ids_msg},开始搜索...")
+ for i, id in enumerate(ids):
+ threading.Thread(target=bot_utils.get_v_by_id, args=(id,)).start()
+
+
+@BOT.callback_query_handler(func=lambda call: True)
+def my_callback_handler(call):
+ EXECUTOR.submit(handle_callback, call)
+
+
+@BOT.message_handler(content_types=["text", "photo", "animation", "video", "document"])
+def my_message_handler(message):
+ EXECUTOR.submit(handle_message, message)
+
+
+def main():
+ try:
+ bot_info = BOT.get_me()
+ LOG.info(f"Connected to bot: @{bot_info.username} (ID: {bot_info.id})")
+ if PIKPAK.enabled:
+ ok, msg = PIKPAK.ensure_login()
+ if ok:
+ LOG.info(f"PikPak: {msg}")
+ else:
+ LOG.error(f"PikPak login failed: {msg}")
+ LOG.info("Connected to api")
+ except Exception as e:
+ LOG.error(f"Unable to connect to bot or api: {e}")
+ return
+ BOT.set_my_commands([types.BotCommand(cmd, BOT_CMDS[cmd]) for cmd in BOT_CMDS])
+ BOT.infinity_polling()
+
+
+if __name__ == "__main__":
+ main()
diff --git a/telegram/tg-search-bot/database.py b/telegram/tg-search-bot/database.py
new file mode 100644
index 0000000..1476147
--- /dev/null
+++ b/telegram/tg-search-bot/database.py
@@ -0,0 +1,304 @@
+import os
+import json
+import sqlite3
+import threading
+import time
+import logging
+
+LOG = logging.getLogger(__name__)
+
+
+class BotFileDb:
+ def __init__(self, path_record_file: str):
+ self.path_record_file = path_record_file
+ pass
+
+ def check_has_record(self):
+ record = {}
+ if os.path.exists(self.path_record_file):
+ try:
+ with open(self.path_record_file, "r", encoding="utf8") as f:
+ record = json.load(f)
+ except Exception as e:
+ LOG.error(f"Failed to load the saved records file: {e}")
+ return None, False, False
+ if not record or record == {}:
+ return None, False, False
+ is_stars_exists = False
+ is_vs_exists = False
+ if (
+ "stars" in record.keys()
+ and record["stars"] != []
+ and len(record["stars"]) > 0
+ ):
+ is_stars_exists = True
+ if "vs" in record.keys() and record["vs"] != [] and len(record["vs"]) > 0:
+ is_vs_exists = True
+ return record, is_stars_exists, is_vs_exists
+
+ def check_star_exists_by_id(self, star_id: str):
+ record, exists, _ = self.check_has_record()
+ if not record or not exists:
+ return False
+ stars = record["stars"]
+ for star in stars:
+ if star["id"].lower() == star_id.lower():
+ return True
+
+ def check_id_exists(self, id: str):
+ record, _, exists = self.check_has_record()
+ if not record or not exists:
+ return False
+ vs = record["vs"]
+ for v in vs:
+ if v["id"].lower() == id.lower():
+ return True
+
+ def renew_record(self, record: dict):
+ try:
+ with open(self.path_record_file, "w", encoding="utf8") as f:
+ json.dump(
+ record, f, separators=(",", ": "), indent=4, ensure_ascii=False
+ )
+ return True
+ except Exception as e:
+ LOG.error(f"Failed to update the saved records file: {e}")
+ return False
+
+ def record_star_by_name_id(self, star_name: str, star_id: str):
+ record, is_stars_exists, _ = self.check_has_record()
+ if not record:
+ record, stars = {}, []
+ else:
+ if not is_stars_exists:
+ stars = []
+ else:
+ stars = record["stars"]
+ for star in stars:
+ if star["id"].lower() == star_id.lower():
+ return True
+ stars.append({"name": star_name, "id": star_id.lower()})
+ record["stars"] = stars
+ return self.renew_record(record)
+
+ def record_id_by_id_stars(self, id: str, stars: list):
+ record, _, is_vs_exists = self.check_has_record()
+ if not record:
+ record, vs = {}, []
+ else:
+ if not is_vs_exists:
+ vs = []
+ else:
+ vs = record["vs"]
+ for v in vs:
+ if v["id"].lower() == id.lower():
+ return True
+ vs.append({"id": id.lower(), "stars": stars})
+ record["vs"] = vs
+ return self.renew_record(record)
+
+ def undo_record_star_by_id(self, star_id: str):
+ record, exists, _ = self.check_has_record()
+ if not record or not exists:
+ return False
+ stars = record["stars"]
+ exists = False
+ for i, star in enumerate(stars):
+ if star["id"].lower() == star_id.lower():
+ del stars[i]
+ exists = True
+ break
+ if exists:
+ record["stars"] = stars
+ return self.renew_record(record)
+ return True
+
+ def undo_record_id(self, id: str):
+ record, _, exists = self.check_has_record()
+ if not record or not exists:
+ return False
+ vs = record["vs"]
+ exists = False
+ for i, v in enumerate(vs):
+ if v["id"].lower() == id.lower():
+ del vs[i]
+ exists = True
+ break
+ if exists:
+ record["vs"] = vs
+ return self.renew_record(record)
+ return True
+
+
+class BotCacheDb:
+ CACHE_BT = {
+ "prefix": "bt-",
+ "expire": 3600 * 24 * 30,
+ }
+ CACHE_V = {
+ "prefix": "v-",
+ "expire": 3600 * 24 * 30,
+ }
+ CACHE_STAR = {
+ "prefix": "star-",
+ "expire": 0, # never expire
+ }
+ CACHE_RANK = {
+ "prefix": "rank-",
+ "expire": 3600 * 24 * 7,
+ }
+ CACHE_SAMPLE = {
+ "prefix": "sample-",
+ "expire": 3600 * 24 * 30,
+ }
+ CACHE_MAGNET = {
+ "prefix": "magnet-",
+ "expire": 3600 * 24 * 5,
+ }
+ CACHE_PV = {
+ "prefix": "pv-",
+ "expire": 3600 * 24 * 15,
+ }
+ CACHE_FV = {
+ "prefix": "fv-",
+ "expire": 3600 * 24 * 15,
+ }
+ CACHE_STARS_MSG = {
+ "prefix": "stars-msg-",
+ "expire": 3600 * 24 * 5,
+ }
+ CACHE_COMMENT = {"prefix": "comment-", "expire": 3600 * 24 * 30}
+ CACHE_NICE_VS_OF_STAR = {
+ "prefix": "nice-vs-of-star-",
+ "expire": 3600 * 24 * 15,
+ }
+ CACHE_JLIB_PAGE_NICE_VS = {
+ "prefix": "jlib-page-nice-vs-",
+ "expire": 3600 * 24 * 7,
+ }
+ CACHE_JLIB_PAGE_NEW_VS = {
+ "prefix": "jlib-page-new-vs-",
+ "expire": 3600 * 24 * 2,
+ }
+ CACHE_STAR_JA_NAME = {"prefix": "star-ja-name-", "expire": 3600 * 24 * 30 * 6}
+ CACHE_NEW_VS_OF_STAR = {
+ "prefix": "new-vs-of-star-",
+ "expire": 3600 * 24 * 12,
+ }
+
+ TYPE_V = 1
+ TYPE_STAR = 2
+ TYPE_RANK = 3
+ TYPE_SAMPLE = 4
+ TYPE_MAGNET = 5
+ TYPE_PV = 6
+ TYPE_FV = 7
+ TYPE_STARS_MSG = 8
+ TYPE_COMMENT = 10
+ TYPE_NICE_VS_OF_STAR = 11
+ TYPE_JLIB_PAGE_NICE_VS = 12
+ TYPE_JLIB_PAGE_NEW_VS = 13
+ TYPE_STAR_JA_NAME = 14
+ TYPE_NEW_VS_OF_STAR = 16
+ TYPE_BT = 17
+
+ TYPE_MAP = {
+ TYPE_V: CACHE_V,
+ TYPE_STAR: CACHE_STAR,
+ TYPE_RANK: CACHE_RANK,
+ TYPE_SAMPLE: CACHE_SAMPLE,
+ TYPE_MAGNET: CACHE_MAGNET,
+ TYPE_PV: CACHE_PV,
+ TYPE_FV: CACHE_FV,
+ TYPE_STARS_MSG: CACHE_STARS_MSG,
+ TYPE_COMMENT: CACHE_COMMENT,
+ TYPE_NICE_VS_OF_STAR: CACHE_NICE_VS_OF_STAR,
+ TYPE_JLIB_PAGE_NICE_VS: CACHE_JLIB_PAGE_NICE_VS,
+ TYPE_JLIB_PAGE_NEW_VS: CACHE_JLIB_PAGE_NEW_VS,
+ TYPE_STAR_JA_NAME: CACHE_STAR_JA_NAME,
+ TYPE_NEW_VS_OF_STAR: CACHE_NEW_VS_OF_STAR,
+ TYPE_BT: CACHE_BT,
+ }
+
+ def __init__(self, path_cache_file: str, use_cache: str = "1"):
+ self.use_cache = use_cache
+ self.path_cache_file = path_cache_file
+ self.cache = None
+ self._lock = threading.Lock()
+ if self.use_cache == "1":
+ try:
+ os.makedirs(os.path.dirname(self.path_cache_file), exist_ok=True)
+ self.cache = sqlite3.connect(
+ self.path_cache_file, check_same_thread=False
+ )
+ self.cache.execute(
+ "CREATE TABLE IF NOT EXISTS cache ("
+ "key TEXT PRIMARY KEY, value TEXT NOT NULL, expire_at INTEGER DEFAULT 0)"
+ )
+ self.cache.commit()
+ LOG.info(f"Connecting to the SQLite cache: {self.path_cache_file}")
+ except Exception as e:
+ self.cache = None
+ LOG.error(f"Unable to open SQLite cache: {self.path_cache_file}: {e}")
+
+ def remove_cache(self, key: str, type: int):
+ if self.use_cache == "0" or not self.cache:
+ return
+ key = str(key).lower()
+ cache_key = f"{BotCacheDb.TYPE_MAP[type]['prefix']}{key}"
+ try:
+ with self._lock:
+ self.cache.execute("DELETE FROM cache WHERE key=?", (cache_key,))
+ self.cache.commit()
+ except Exception as e:
+ LOG.error(f"Failed to delete cache: {cache_key}: {e}")
+
+ def set_cache(self, key: str, value, type: int, expire=None):
+ """
+ Set cache.
+
+ :param str key: Key
+ :param any value: Value
+ :param int type: Cache type
+ :param int expire: Cache expiration time (in seconds), defaults to using predefined time
+ """
+ if self.use_cache == "0" or not self.cache:
+ return
+ key = str(key).lower()
+ if not expire:
+ expire = BotCacheDb.TYPE_MAP[type]["expire"]
+ prefix = BotCacheDb.TYPE_MAP[type]["prefix"]
+ cache_key = f"{prefix}{key}"
+ expire_at = 0 if expire == 0 else int(time.time()) + expire
+ try:
+ with self._lock:
+ self.cache.execute(
+ "INSERT OR REPLACE INTO cache (key, value, expire_at) VALUES (?, ?, ?)",
+ (cache_key, json.dumps(value), expire_at),
+ )
+ self.cache.commit()
+ except Exception as e:
+ LOG.error(f"Failed to set cache: {cache_key}: {e}")
+
+ def get_cache(self, key, type: int):
+ if self.use_cache == "0" or not self.cache:
+ return
+ key = str(key).lower()
+ cache_key = f"{BotCacheDb.TYPE_MAP[type]['prefix']}{key}"
+ try:
+ with self._lock:
+ cur = self.cache.execute(
+ "SELECT value, expire_at FROM cache WHERE key=?", (cache_key,)
+ )
+ row = cur.fetchone()
+ if not row:
+ return
+ value, expire_at = row
+ if expire_at and expire_at < int(time.time()):
+ with self._lock:
+ self.cache.execute("DELETE FROM cache WHERE key=?", (cache_key,))
+ self.cache.commit()
+ return
+ return json.loads(value)
+ except Exception as e:
+ LOG.error(f"Failed to retrieve cache: {cache_key}: {e}")
diff --git a/telegram/tg-search-bot/docker-compose.yml b/telegram/tg-search-bot/docker-compose.yml
new file mode 100644
index 0000000..dd44c83
--- /dev/null
+++ b/telegram/tg-search-bot/docker-compose.yml
@@ -0,0 +1,16 @@
+version: "3"
+services:
+ tg_search_bot:
+ image: python:3.10
+ restart: always
+ working_dir: /app
+ environment:
+ - TZ=Asia/Shanghai
+ network_mode: "host"
+ volumes:
+ - .:/app
+ - ~/.tg_search_bot:/root/.tg_search_bot
+ command: >
+ sh -c "
+ pip3 install -U -r requirements.txt &&
+ python3 bot.py"
diff --git a/telegram/tg-search-bot/pikpak.py b/telegram/tg-search-bot/pikpak.py
new file mode 100644
index 0000000..37d5bbe
--- /dev/null
+++ b/telegram/tg-search-bot/pikpak.py
@@ -0,0 +1,296 @@
+# -*- coding: UTF-8 -*-
+"""PikPak 官方 OpenAPI 客户端。
+
+通过用户名 / 密码登录获取 token,再调用官方 drive API 直接提交磁力链接的
+离线下载任务,取代原先「向 PikPak6_Bot 发送消息」的保存方式。
+
+参考实现: https://pypi.org/project/pikpakapi/
+"""
+
+import hashlib
+import json
+import logging
+import os
+import time
+
+import requests
+
+LOG = logging.getLogger(__name__)
+
+CLIENT_ID = "YNxT9w7GMdWvEOKa"
+CLIENT_SECRET = "dbw2OtmVEeuUvIptb1Coyg"
+CLIENT_VERSION = "1.47.1"
+PACKAGE_NAME = "com.pikcloud.pikpak"
+
+API_HOST = "https://api-drive.mypikpak.com"
+USER_HOST = "https://user.mypikpak.com"
+
+# PikPak 客户端内置的验签盐值
+SALTS = [
+ "Gez0T9ijiI9WCeTsKSg3SMlx",
+ "zQdbalsolyb1R/",
+ "ftOjr52zt51JD68C3s",
+ "yeOBMH0JkbQdEFNNwQ0RI9T3wU/v",
+ "BRJrQZiTQ65WtMvwO",
+ "je8fqxKPdQVJiy1DM6Bc9Nb1",
+ "niV",
+ "9hFCW2R1",
+ "sHKHpe2i96",
+ "p7c5E6AcXQ/IJUuAEC9W6",
+ "",
+ "aRv9hjc9P+Pbn+u3krN6",
+ "BzStcgE8qVdqjEH16l4",
+ "SqgeZvL5j9zoHP95xWHt",
+ "zVof5yaJkPe3VFpadPof",
+]
+
+
+def captcha_sign(device_id: str, timestamp: str) -> str:
+ """生成登录所需的 captcha_sign。"""
+ sign = CLIENT_ID + CLIENT_VERSION + PACKAGE_NAME + device_id + timestamp
+ for salt in SALTS:
+ sign = hashlib.md5((sign + salt).encode()).hexdigest()
+ return "1." + sign
+
+
+class PikPakClient:
+ def __init__(
+ self,
+ username: str = "",
+ password: str = "",
+ proxy: str = "",
+ token_path: str = "",
+ ):
+ self.username = username or ""
+ self.password = password or ""
+ self.proxy = proxy or ""
+ self.proxies = {"http": self.proxy, "https": self.proxy} if self.proxy else None
+ self.token_path = token_path or os.path.expanduser(
+ "~/.tg_search_bot/pikpak_token.json"
+ )
+ self.access_token = None
+ self.refresh_token = None
+ self.user_id = None
+ self.device_id = None
+ self.expires_at = 0
+ self._load_token()
+
+ @property
+ def enabled(self):
+ return bool(self.username and self.password)
+
+ # ---- token 持久化 ----
+ def _load_token(self):
+ try:
+ if os.path.exists(self.token_path):
+ with open(self.token_path, "r", encoding="utf8") as f:
+ data = json.load(f)
+ self.access_token = data.get("access_token")
+ self.refresh_token = data.get("refresh_token")
+ self.user_id = data.get("user_id")
+ self.device_id = data.get("device_id")
+ self.expires_at = data.get("expires_at", 0)
+ except Exception as e:
+ LOG.error(f"Failed to load PikPak token: {e}")
+
+ def _save_token(self):
+ try:
+ os.makedirs(os.path.dirname(self.token_path), exist_ok=True)
+ with open(self.token_path, "w", encoding="utf8") as f:
+ json.dump(
+ {
+ "access_token": self.access_token,
+ "refresh_token": self.refresh_token,
+ "user_id": self.user_id,
+ "device_id": self.device_id,
+ "expires_at": self.expires_at,
+ },
+ f,
+ ensure_ascii=False,
+ indent=4,
+ )
+ except Exception as e:
+ LOG.error(f"Failed to save PikPak token: {e}")
+
+ # ---- 基础请求 ----
+ def _device_id(self) -> str:
+ if not self.device_id:
+ self.device_id = hashlib.md5(
+ f"{self.username}{self.password}".encode()
+ ).hexdigest()
+ self._save_token()
+ return self.device_id
+
+ def _post_json(self, url: str, data: dict, headers: dict = None, timeout: int = 30):
+ h = {"Content-Type": "application/json; charset=utf-8"}
+ if headers:
+ h.update(headers)
+ return requests.post(
+ url, json=data, headers=h, proxies=self.proxies, timeout=timeout
+ )
+
+ def _post_form(self, url: str, data: dict, headers: dict = None, timeout: int = 30):
+ h = {"Content-Type": "application/x-www-form-urlencoded"}
+ if headers:
+ h.update(headers)
+ return requests.post(
+ url, data=data, headers=h, proxies=self.proxies, timeout=timeout
+ )
+
+ def _authorized_headers(self) -> dict:
+ return {
+ "Authorization": f"Bearer {self.access_token}",
+ "X-Device-Id": self._device_id(),
+ }
+
+ # ---- 登录 / 刷新 ----
+ def _captcha_init(self, action: str):
+ device_id = self._device_id()
+ ts = str(int(time.time() * 1000))
+ meta = {
+ "captcha_sign": captcha_sign(device_id, ts),
+ "client_version": CLIENT_VERSION,
+ "package_name": PACKAGE_NAME,
+ "user_id": self.user_id or "",
+ "timestamp": ts,
+ "username": self.username,
+ }
+ payload = {
+ "client_id": CLIENT_ID,
+ "action": action,
+ "device_id": device_id,
+ "meta": meta,
+ }
+ resp = self._post_json(f"{USER_HOST}/v1/shield/captcha/init", payload)
+ if resp.status_code != 200:
+ LOG.error(
+ f"PikPak captcha init failed: {resp.status_code} {resp.text[:300]}"
+ )
+ return None
+ data = resp.json()
+ token = data.get("captcha_token")
+ if not token:
+ LOG.error(f"PikPak captcha init returned no token: {data}")
+ return None
+ return token
+
+ def login(self):
+ if not self.enabled:
+ return False, "未配置 PikPak 账号"
+ captcha_token = self._captcha_init(f"POST:{USER_HOST}/v1/auth/signin")
+ if not captcha_token:
+ return False, "验证码初始化失败"
+ data = {
+ "client_id": CLIENT_ID,
+ "client_secret": CLIENT_SECRET,
+ "password": self.password,
+ "username": self.username,
+ "captcha_token": captcha_token,
+ }
+ resp = self._post_form(f"{USER_HOST}/v1/auth/signin", data)
+ if resp.status_code != 200:
+ reason = "登录失败(账号或密码错误)"
+ try:
+ j = resp.json()
+ reason = j.get("error_description") or j.get("error") or reason
+ except Exception:
+ pass
+ LOG.error(f"PikPak login failed: {resp.status_code} {resp.text[:300]}")
+ return False, reason
+ j = resp.json()
+ if "access_token" not in j:
+ reason = j.get("error_description") or j.get("error") or "登录失败"
+ LOG.error(f"PikPak login returned error: {j}")
+ return False, reason
+ self.access_token = j["access_token"]
+ self.refresh_token = j["refresh_token"]
+ self.user_id = j.get("sub")
+ self.expires_at = int(time.time()) + int(j.get("expires_in", 7200))
+ self._save_token()
+ LOG.info("PikPak login success")
+ return True, "登录成功"
+
+ def refresh(self):
+ if not self.refresh_token:
+ return False, "缺少 refresh_token"
+ data = {
+ "client_id": CLIENT_ID,
+ "refresh_token": self.refresh_token,
+ "grant_type": "refresh_token",
+ }
+ resp = self._post_json(f"{USER_HOST}/v1/auth/token", data)
+ if resp.status_code != 200:
+ LOG.error(f"PikPak refresh failed: {resp.status_code} {resp.text[:300]}")
+ return False, "令牌刷新失败"
+ j = resp.json()
+ if "access_token" not in j:
+ return False, j.get("error_description") or j.get("error") or "令牌刷新失败"
+ self.access_token = j["access_token"]
+ self.refresh_token = j["refresh_token"]
+ self.user_id = j.get("sub")
+ self.expires_at = int(time.time()) + int(j.get("expires_in", 7200))
+ self._save_token()
+ return True, "刷新成功"
+
+ def ensure_login(self):
+ if not self.enabled:
+ return False, "未配置 PikPak 账号"
+ if not self.access_token:
+ return self.login()
+ if self.expires_at and time.time() > self.expires_at - 60:
+ ok, msg = self.refresh()
+ if ok:
+ return True, msg
+ return self.login()
+ return True, "已登录"
+
+ # ---- 离线下载 ----
+ def offline_download(
+ self, magnet_url: str, name: str = None, parent_id: str = None
+ ):
+ """将磁力链接提交为 PikPak 离线下载任务。
+
+ :return tuple[bool, str]: (是否成功, 提示信息)
+ """
+ if not self.enabled:
+ return False, "未配置 PikPak 账号"
+ ok, msg = self.ensure_login()
+ if not ok:
+ return False, msg
+ data = {
+ "kind": "drive#file",
+ "upload_type": "UPLOAD_TYPE_URL",
+ "url": {"url": magnet_url},
+ "folder_type": "DOWNLOAD" if not parent_id else "",
+ }
+ if name:
+ data["name"] = name
+ if parent_id:
+ data["parent_id"] = parent_id
+ for attempt in range(2):
+ resp = self._post_json(
+ f"{API_HOST}/drive/v1/files", data, headers=self._authorized_headers()
+ )
+ if resp.status_code == 200:
+ j = resp.json()
+ if "error" in j:
+ if j.get("error_code") == 16 and attempt == 0:
+ self.refresh()
+ continue
+ return (
+ False,
+ j.get("error_description") or j.get("error") or "未知错误",
+ )
+ return True, "已提交离线任务到 PikPak"
+ if resp.status_code in (401, 403) and attempt == 0:
+ self.refresh()
+ continue
+ reason = f"HTTP {resp.status_code}"
+ try:
+ j = resp.json()
+ reason = j.get("error_description") or j.get("error") or reason
+ except Exception:
+ pass
+ LOG.error(f"PikPak offline download failed: {resp.text[:300]}")
+ return False, reason
+ return False, "离线任务提交失败"
diff --git a/telegram/tg-search-bot/requirements.txt b/telegram/tg-search-bot/requirements.txt
new file mode 100644
index 0000000..67a8328
--- /dev/null
+++ b/telegram/tg-search-bot/requirements.txt
@@ -0,0 +1,6 @@
+langdetect==1.0.9
+pyTelegramBotAPI==4.14.0
+PyYAML==6.0.1
+Requests==2.31.0
+beautifulsoup4==4.15.0
+Jvav
diff --git a/telegram/tg-search-bot/start_windows.bat b/telegram/tg-search-bot/start_windows.bat
new file mode 100644
index 0000000..bc90647
--- /dev/null
+++ b/telegram/tg-search-bot/start_windows.bat
@@ -0,0 +1,61 @@
+@echo off
+chcp 65001 >nul
+echo ========================================
+echo tg-search-bot 部署脚本 (Windows)
+echo ========================================
+echo.
+
+cd /d "%~dp0"
+
+echo [1/4] 检查Python环境...
+python --version
+if errorlevel 1 (
+ echo ❌ 未找到Python,请先安装Python 3.9+
+ pause
+ exit /b 1
+)
+
+echo.
+echo [2/4] 安装依赖...
+pip install -r requirements.txt
+if errorlevel 1 (
+ echo ❌ 依赖安装失败
+ pause
+ exit /b 1
+)
+
+echo.
+echo [3/4] 检查配置文件...
+set CONFIG_DIR=%USERPROFILE%\.tg_search_bot
+if not exist "%CONFIG_DIR%" (
+ mkdir "%CONFIG_DIR%"
+ echo 已创建配置目录: %CONFIG_DIR%
+)
+
+if not exist "%CONFIG_DIR%\config.yaml" (
+ echo.
+ echo ⚠️ 配置文件不存在,请先创建: %CONFIG_DIR%\config.yaml
+ echo.
+ echo 配置模板:
+ echo tg_chat_id: 你的Telegram用户ID
+ echo tg_bot_token: 你的Bot Token
+ echo use_proxy: 0
+ echo enable_nsfw: 0
+ echo.
+ pause
+ exit /b 1
+)
+echo ✅ 配置文件存在
+
+echo.
+echo [4/4] 启动机器人...
+echo.
+echo ========================================
+echo 机器人启动中...
+echo 按 Ctrl+C 停止
+echo ========================================
+echo.
+
+python bot.py
+
+pause