初始化多平台机器人部署项目 - Telegram/Discord/QQ资源搜索机器人

This commit is contained in:
2026-09-11 11:19:56 +08:00
commit 2253a2d774
21 changed files with 4004 additions and 0 deletions
+125
View File
@@ -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?或者先把文件上传到首尔服务器?
+73
View File
@@ -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
+18
View File
@@ -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
+5
View File
@@ -0,0 +1,5 @@
# Discord机器人配置
DISCORD_TOKEN=your_discord_bot_token_here
# 资源数据库路径(默认使用Telegram采集的数据库)
# RESOURCE_DB_PATH=F:\开源项目\telegram-resource-collector\web_collected.db
+436
View File
@@ -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()
Binary file not shown.
+2
View File
@@ -0,0 +1,2 @@
discord.py>=2.3.0
python-dotenv>=1.0.0
+46
View File
@@ -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
+24
View File
@@ -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
+26
View File
@@ -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:
+6
View File
@@ -0,0 +1,6 @@
__pycache__
.vscode
.DS_Store
.idea
.venv
*.sqlite
+674
View File
@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
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.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
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 <https://www.gnu.org/licenses/>.
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:
<program> Copyright (C) <year> <name of author>
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
<https://www.gnu.org/licenses/>.
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
<https://www.gnu.org/licenses/why-not-lgpl.html>.
+142
View File
@@ -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<br/>title / plot / number / genre / performer"] --> B["2. AI understands intent<br/>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<br/>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<br/>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
<a href="https://www.jetbrains.com/">
<img src="https://resources.jetbrains.com/storage/products/company/brand/logos/jb_beam.png" alt="JetBrains Logo (Main) logo." style="width: 200px;"></a>
Thanks to JetBrains for supporting this project.
+143
View File
@@ -0,0 +1,143 @@
# tg-search-bot
[English](README.md)[中文](README.zh.md)
一个基于 Python3 的 Telegram 资源搜索机器人:搜索各类视频磁力链接,支持收藏、导出记录、自动保存到网盘,可配置 NSFW 开关与代理上网;同时集成 AI 自然语言理解能力,可直接根据用户自然语言意图自动识别搜索目标、类型与数据源。
- 数据来源:TorrentKitty(中文)+ apibay(英文)+ 影视磁力索引 APIJvav)
- 网盘: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["① 用户输入<br/>电影 / 电视剧 / 编号 / 剧情 / 演职人员 / 类型"] --> B["② AI 理解意图<br/>intent · target · source · explain"]
B --> C["③ 回复 🔍 搜索:目标"]
C --> D["④ 选择最合适的爬虫 / API"]
D --> D1{意图 intent}
D1 -->|编号| E["按编号搜索<br/>编号索引站"]
D1 -->|演职人员| F["演职人员搜索"]
D1 -->|关键词 / 类型 / 剧情| G["关键词 → BT 种子"]
E --> H["⑤ 回复 ⏳ 搜索中"]
F --> H
G --> H
H --> I["⑥ 搜索得到磁力链接<br/>(无磁力则返回 BT 等其他格式)"]
I --> J["⑦ 回复 📄 搜索结果"]
J --> K["⑧ 保存最优磁力链接到 PikPak"]
K --> L["⑨ 回复 ✅ 保存结果"]
```
## 目录结构
```
bot.py 主程序:配置、日志、消息 / 回调处理、AI 搜索流程
ai.py AI 意图理解客户端(OpenAI 兼容 /chat/completions
pikpak.py Pikpak 官方 OpenAPI 客户端(登录 / 刷新 token、离线下载)
database.py 数据层:BotFileDbJSON 收藏)+ BotCacheDbSQLite 缓存)
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
```
## 致谢
<a href="https://www.jetbrains.com/">
<img src="https://resources.jetbrains.com/storage/products/company/brand/logos/jb_beam.png" alt="JetBrains Logo (Main) logo." style="width: 200px;"></a>
感谢 JetBrains 对这个项目的支持!
+135
View File
@@ -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
File diff suppressed because it is too large Load Diff
+304
View File
@@ -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}")
+16
View File
@@ -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"
+296
View File
@@ -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, "离线任务提交失败"
+6
View File
@@ -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
+61
View File
@@ -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