VibeCode|RSS订阅关键词监控推送Telegram Bot

2026年5月22日

这是一个基于 Telegram Bot 的 RSS 关键词监控推送系统,支持全量/关键词双模式随心切换,全图形化交互,分享给有需要的朋友!

✨ 核心功能

  • 全交互式操作:无需频繁改代码,添加 RSS、删除源、管理关键词全部在 Telegram 聊天框内通过按钮完成。

  • 模式随心切换:支持全量推送模式与关键词监控模式(默认),可在中控台一键切换。

  • 历史记录追踪:可直接在 Bot 中调取最近 24 小时内命中的关键词推送列表流水。

  • 灵活频率调整:支持动态设置 RSS 轮询频率(支持到秒级,最低 30 秒)。

  • 多用户审批流:非 Admin 用户使用需向 Admin 提交申请,Admin 拥有专属按钮一键批准/拒绝。

📸 界面预览

IMG_0092.png IMG_0091.png IMG_0094.png

🛠️ 部署前置准备

在运行代码前,你需要准备两样东西:

  • Telegram Bot Token:在 Telegram 搜索 @BotFather,发送 /newbot 按照提示创建一个机器人,获取形如 123456789:ABCdefGhIJKlmNoPQRsTUVwxyZ 的 Token。

  • 你的 Telegram ID:在 Telegram 搜索 @userinfobot,给它发条消息,它会返回你的 Id(一串纯数字),这就是 ADMIN_ID。

怎么使用?

  1. 安装依赖 pip install aiogram aiosqlite feedparser pytz
  2. cd到你想放脚本的位置 例如/opt/tgbot
  3. nano tg-rssbot.py
  4. 粘贴并保存修改好的内容
  5. nano /etc/systemd/system/tg-rssbot.service
  6. 粘贴并保存修改好的下面内容
[Unit]
Description=Telegram RSS Keywords push
After=network.target

[Service]
# 如果在 root 目录下操作,这里可以直接用 root,或者换成你的常用用户名
User=root
# 脚本所在的绝对路径
WorkingDirectory=/opt/tgbot
# 解释器路径 + 脚本路径
ExecStart=/usr/bin/python3 /opt/tgbot/tg-rssbot.py
# 崩溃自动重启
Restart=always
RestartSec=5
# 确保日志能实时刷新到 journalctl
Environment=PYTHONUNBUFFERED=1

[Install]
WantedBy=multi-user.target
  1. systemctl daemon-reload
  2. systemctl enable --now tg-rssbot
  3. systemctl status tg-rssbot查看状态
  4. 完成了

Python代码

⚠️ 注意:请在运行前,修改代码中 第 22 行 到 第 26 行 的 # ================= 配置区 =================。

import asyncio
import logging
import feedparser
import aiosqlite
import pytz
import time
import re
from datetime import datetime
from aiogram import Bot, Dispatcher, F
from aiogram.filters import Command
from aiogram.types import Message, InlineKeyboardMarkup, InlineKeyboardButton, CallbackQuery
from aiogram.fsm.storage.memory import MemoryStorage
from aiogram.fsm.state import State, StatesGroup
from aiogram.fsm.context import FSMContext

# ================= 配置区 =================
API_TOKEN = '填入你的token'
ADMIN_ID = 你的TGID
DB_NAME = "rss_v2_data.db"
TIMEZONE = pytz.timezone('Asia/Shanghai')
# ==========================================

bot = Bot(token=API_TOKEN)
dp = Dispatcher(storage=MemoryStorage())

class BotStates(StatesGroup):
    waiting_for_rss_url = State()
    waiting_for_rss_alias = State()
    waiting_for_kw = State()
    waiting_for_interval = State()

# --- 数据库初始化 ---
async def init_db():
    async with aiosqlite.connect(DB_NAME) as db:
        await db.execute("""
            CREATE TABLE IF NOT EXISTS rss_sources (
                url TEXT PRIMARY KEY, 
                mode TEXT DEFAULT 'keyword',
                alias TEXT
            )
        """)
        await db.execute("CREATE TABLE IF NOT EXISTS keywords (word TEXT PRIMARY KEY)")
        await db.execute("CREATE TABLE IF NOT EXISTS seen_links (link TEXT PRIMARY KEY)")
        await db.execute("CREATE TABLE IF NOT EXISTS users (user_id INTEGER PRIMARY KEY, status TEXT)")
        await db.execute("CREATE TABLE IF NOT EXISTS settings (key TEXT PRIMARY KEY, value TEXT)")
        await db.execute("CREATE TABLE IF NOT EXISTS push_history (id INTEGER PRIMARY KEY, keyword TEXT, title TEXT, ts INTEGER)")

        await db.execute("INSERT OR IGNORE INTO users (user_id, status) VALUES (?, 'admin')", (ADMIN_ID,))
        await db.execute("INSERT OR IGNORE INTO settings (key, value) VALUES ('check_interval', '300')")

        try:
            async with db.execute("PRAGMA table_info(rss_sources)") as cursor:
                columns = [col[1] for col in await cursor.fetchall()]
                if 'alias' not in columns:
                    await db.execute("ALTER TABLE rss_sources ADD COLUMN alias TEXT")
        except: pass
        await db.commit()

async def get_interval():
    async with aiosqlite.connect(DB_NAME) as db:
        async with db.execute("SELECT value FROM settings WHERE key='check_interval'") as c:
            row = await c.fetchone()
            return int(row[0]) if row else 300

# --- 权限验证 ---
async def check_auth(user_id: int, user_name: str) -> bool:
    async with aiosqlite.connect(DB_NAME) as db:
        async with db.execute("SELECT status FROM users WHERE user_id = ?", (user_id,)) as c:
            row = await c.fetchone()
            if row and row[0] in ('admin', 'approved'):
                return True
            if not row:
                await db.execute("INSERT INTO users (user_id, status) VALUES (?, 'pending')", (user_id,))
                await db.commit()
                keyboard = InlineKeyboardMarkup(inline_keyboard=[
                    [InlineKeyboardButton(text="✅ 批准", callback_data=f"auth_approve_{user_id}"),
                     InlineKeyboardButton(text="❌ 拒绝", callback_data=f"auth_reject_{user_id}")]
                ])
                await bot.send_message(
                    ADMIN_ID,
                    f"🛡 **新的使用申请**\n\n👤 用户: {user_name}\n🆔 ID: `{user_id}`",
                    reply_markup=keyboard, parse_mode="Markdown"
                )
            return False

@dp.callback_query(F.data.startswith("auth_"))
async def process_auth_callback(callback: CallbackQuery):
    if callback.from_user.id != ADMIN_ID: return await callback.answer("无权操作", show_alert=True)
    action, user_id_str = callback.data.split("_")[1:3]
    user_id = int(user_id_str)

    async with aiosqlite.connect(DB_NAME) as db:
        if action == "approve":
            await db.execute("UPDATE users SET status = 'approved' WHERE user_id = ?", (user_id,))
            msg_text, user_msg = "✅ 已批准", "🎉 管理员已批准。键入 /start 唤出中控。"
        else:
            await db.execute("UPDATE users SET status = 'rejected' WHERE user_id = ?", (user_id,))
            msg_text, user_msg = "❌ 已拒绝", "⚠️ 抱歉,申请被拒。"
        await db.commit()

    await callback.message.edit_text(callback.message.text + f"\n\n**处理:{msg_text}**", parse_mode="Markdown")
    try: await bot.send_message(user_id, user_msg)
    except: pass
    await callback.answer()

# --- 消息推送 ---
async def send_report(match_type, title, link, source_alias):
    display_alias = source_alias or "未命名源"
    push_time_str = datetime.now(TIMEZONE).strftime('%Y-%m-%d %H:%M:%S')
    current_ts = int(time.time())

    if match_type == "全量模式":
        header = f"📰 **{display_alias} 有新文章**"
        content = f"👀 **{title}**\n\n 🔗 {link}\n"
    else:
        header = f"🎯 **发现关键词:{match_type}**"
        content = f"🗞 **来源**:{display_alias}\n\n 👀 {title}\n\n 🔗 {link}\n"
        pure_kw = match_type.replace("#", "")
        try:
            async with aiosqlite.connect(DB_NAME) as db:
                await db.execute("INSERT INTO push_history (keyword, title, ts) VALUES (?, ?, ?)", (pure_kw, title, current_ts))
                await db.commit()
        except Exception as e:
            logging.error(f"历史写入失败: {e}")

    report = f"{header}\n━━━━━━━━━━━━\n{content}\n⏰ `{push_time_str}`"

    async with aiosqlite.connect(DB_NAME) as db:
        async with db.execute("SELECT user_id FROM users WHERE status IN ('admin', 'approved')") as c:
            users = await c.fetchall()
    for (uid,) in users:
        try:
            await bot.send_message(uid, report, parse_mode="Markdown", disable_web_page_preview=False)
        except: pass

# ==========================================
# UI 中控台与交互流
# ==========================================

def get_main_menu():
    return InlineKeyboardMarkup(inline_keyboard=[
        [InlineKeyboardButton(text="➕ 添加新订阅", callback_data="wizard_add")],
        [InlineKeyboardButton(text="📋 RSS抓取列表", callback_data="btn_manage_rss"),
         InlineKeyboardButton(text="🔑 关键词管理", callback_data="btn_manage_kw")],
        [InlineKeyboardButton(text="🕒 近期抓取列表", callback_data="btn_history")],
        [InlineKeyboardButton(text="⚙️ 抓取频率设定", callback_data="btn_interval")],
        [InlineKeyboardButton(text="❌ 收起面板", callback_data="btn_close")]
    ])

@dp.message(Command("start"))
async def cmd_start_main(message: Message, state: FSMContext):
    await state.clear()
    if not await check_auth(message.from_user.id, message.from_user.full_name):
        return await message.answer("✋ 您的账号暂未获批使用此 Bot。已向管理员发送申请,请耐心等待。")

    welcome = (
        "🤖 **Leo's RSS 关键词监控系统**\n"
        "━━━━━━━━━━━━━━━━━━━━━\n"
        "欢迎使用全交互式控制中心。请点击下方按钮操作:"
    )
    await message.answer(welcome, reply_markup=get_main_menu(), parse_mode="Markdown")

@dp.message(Command(re.compile(r".*"))) # 拦截所有除 /start 以外的命令提示
async def cmd_fallback_all(message: Message, state: FSMContext):
    await cmd_start_main(message, state)

# --- 1. 向导添加模块 (拆分 URL 和 Alias) ---

@dp.callback_query(F.data == "wizard_add")
async def wizard_add_menu(callback: CallbackQuery):
    kb = InlineKeyboardMarkup(inline_keyboard=[
        [InlineKeyboardButton(text="📡 添加 RSS 链接", callback_data="add_rss")],
        [InlineKeyboardButton(text="🎯 添加监控关键词", callback_data="add_kw")],
        [InlineKeyboardButton(text="🔙 放弃并返回", callback_data="btn_to_main")]
    ])
    await callback.message.edit_text("🎯 **添加向导**\n请选择您要添加的对象种类:", reply_markup=kb, parse_mode="Markdown")

@dp.callback_query(F.data == "add_rss")
async def step_add_rss_url(callback: CallbackQuery, state: FSMContext):
    await state.set_state(BotStates.waiting_for_rss_url)
    kb = InlineKeyboardMarkup(inline_keyboard=[[InlineKeyboardButton(text="🔙 取消", callback_data="btn_to_main")]])
    await callback.message.edit_text("📡 **请输入RSS源订阅链接**\n", reply_markup=kb, parse_mode="Markdown")
    await callback.answer()

@dp.message(BotStates.waiting_for_rss_url)
async def process_add_rss_url(message: Message, state: FSMContext):
    url = message.text.strip()
    if not url.startswith("http") or " " in url:
        return await message.answer("❌ 不是规范的 URL。请检查格式重新发送。")

    async with aiosqlite.connect(DB_NAME) as db:
        async with db.execute("SELECT 1 FROM rss_sources WHERE url = ?", (url,)) as c:
            if await c.fetchone():
                await state.clear()
                return await message.answer("⚠️ 失败:该RSS已存在,跳过添加", reply_markup=InlineKeyboardMarkup(inline_keyboard=[[InlineKeyboardButton(text="返回中控", callback_data="btn_to_main")]]))

    await state.update_data(rss_url=url)
    await state.set_state(BotStates.waiting_for_rss_alias)
    kb = InlineKeyboardMarkup(inline_keyboard=[[InlineKeyboardButton(text="🔙 取消", callback_data="btn_to_main")]])
    await message.answer(f"✅ URL合法: `{url}`\n\n🏷 **请为该订阅设置昵称**\n(例如:`Nodeseek`、`V2EX` 等)", reply_markup=kb, parse_mode="Markdown")

@dp.message(BotStates.waiting_for_rss_alias)
async def process_add_rss_alias(message: Message, state: FSMContext):
    alias = message.text.strip()
    user_data = await state.get_data()
    url = user_data.get("rss_url")

    async with aiosqlite.connect(DB_NAME) as db:
        await db.execute("INSERT INTO rss_sources (url, mode, alias) VALUES (?, ?, ?)", (url, 'keyword', alias))
        await db.commit()

    await state.clear()
    wait_msg = await message.answer(f"⏳ 正在拉取 `{alias}` 初始化防刷屏基线...")

    try:
        feed = await asyncio.to_thread(feedparser.parse, url)
        if getattr(feed, 'bozo_exception', None) and not feed.entries:
            return await wait_msg.edit_text(f"❌ 警告:无法解析该源 ({feed.bozo_exception}),但已强行加入数据库。", reply_markup=InlineKeyboardMarkup(inline_keyboard=[[InlineKeyboardButton(text="返回中控", callback_data="btn_to_main")]]))

        async with aiosqlite.connect(DB_NAME) as db:
            sample_entries = feed.entries[:3]
            all_links = [(e.get('link'),) for e in feed.entries if e.get('link')]
            await db.executemany("INSERT OR IGNORE INTO seen_links (link) VALUES (?)", all_links)
            await db.commit()

        success_text = f"🎉 **RSS 源添加成功**\n🏷 代号:`{alias}`\n🔰 模式:默认关键词检索\n\n**近期测试抓取:**\n"
        for i, entry in enumerate(sample_entries, 1):
            success_text += f"• [{entry.get('title', '无标题')}]({entry.get('link', '#')})\n"
        await wait_msg.edit_text(success_text, reply_markup=InlineKeyboardMarkup(inline_keyboard=[[InlineKeyboardButton(text="👉 返回中控配置项", callback_data="btn_to_main")]]), parse_mode="Markdown", disable_web_page_preview=True)
    except Exception as e:
        await wait_msg.edit_text(f"❌ 网络错误: {e}")

@dp.callback_query(F.data == "add_kw")
async def step_add_kw_only(callback: CallbackQuery, state: FSMContext):
    await state.set_state(BotStates.waiting_for_kw)
    kb = InlineKeyboardMarkup(inline_keyboard=[[InlineKeyboardButton(text="🔙 取消", callback_data="btn_to_main")]])
    await callback.message.edit_text("🎯 **增加关键词条目**\n请直接回复要监控的关键词(精准文本监控 / 不分大小写):", reply_markup=kb, parse_mode="Markdown")
    await callback.answer()

@dp.message(BotStates.waiting_for_kw)
async def process_kw_input_only(message: Message, state: FSMContext):
    word = message.text.strip()
    async with aiosqlite.connect(DB_NAME) as db:
        await db.execute("INSERT OR IGNORE INTO keywords (word) VALUES (?)", (word,))
        await db.commit()
    await state.clear()
    kb = InlineKeyboardMarkup(inline_keyboard=[[InlineKeyboardButton(text="返回", callback_data="btn_to_main")]])
    await message.answer(f"✅ 成功添加关键词 `[ {word} ]`", reply_markup=kb, parse_mode="Markdown")

# --- 2. 列表管理模块 ---

@dp.callback_query(F.data == "btn_manage_rss")
async def show_rss_menu(callback: CallbackQuery):
    async with aiosqlite.connect(DB_NAME) as db:
        async with db.execute("SELECT rowid, alias, mode FROM rss_sources") as c:
            sources = await c.fetchall()

    if not sources:
        kb = InlineKeyboardMarkup(inline_keyboard=[
            [InlineKeyboardButton(text="➕ 去添加", callback_data="wizard_add")],
            [InlineKeyboardButton(text="🔙 返回", callback_data="btn_to_main")]
        ])
        return await callback.message.edit_text("🗂 您目前没有订阅任何 RSS 资源。", reply_markup=kb)

    keyb = []
    for rowid, alias, mode in sources:
        m_txt = "📢全量订阅模式" if mode == 'normal' else "🎯关键词模式"
        display = alias or f"未命名的源 #{rowid}"
        keyb.append([
            InlineKeyboardButton(text=f"[{m_txt}] {display}", callback_data=f"trss_{rowid}"),
            InlineKeyboardButton(text="❌ 删除", callback_data=f"drss_{rowid}")
        ])
    keyb.append([InlineKeyboardButton(text="🔙 返回中控台", callback_data="btn_to_main")])
    await callback.message.edit_text("📦 ** RSS 兵工厂管理 **\n(点击左侧切换 全量订阅/关键词监控 模式,右侧执行删除)", reply_markup=InlineKeyboardMarkup(inline_keyboard=keyb), parse_mode="Markdown")

@dp.callback_query(F.data == "btn_manage_kw")
async def show_kw_menu(callback: CallbackQuery):
    async with aiosqlite.connect(DB_NAME) as db:
        async with db.execute("SELECT rowid, word FROM keywords") as c:
            keys = await c.fetchall()

    if not keys:
        kb = InlineKeyboardMarkup(inline_keyboard=[
            [InlineKeyboardButton(text="➕ 去添加", callback_data="step_add_kw")],
            [InlineKeyboardButton(text="🔙 返回", callback_data="btn_to_main")]
        ])
        return await callback.message.edit_text("🛡 您的词库空空荡荡。", reply_markup=kb)

    keyb = []
    for rowid, word in keys:
        keyb.append([InlineKeyboardButton(text=f"🗑 抹除: {word}", callback_data=f"dkw_{rowid}")])

    keyb.append([
        InlineKeyboardButton(text="➕ 新增词", callback_data="add_kw"),
        InlineKeyboardButton(text="🔙 返航", callback_data="btn_to_main")
    ])
    await callback.message.edit_text("🔑 ** 嗅探词库部署 **\n(点击列表项立刻从数据库剔除)", reply_markup=InlineKeyboardMarkup(inline_keyboard=keyb), parse_mode="Markdown")

# 面板深层原子回调:
@dp.callback_query(F.data.startswith("trss_"))
async def db_toggle_rss(callback: CallbackQuery):
    row_id = callback.data.split("_")[1]
    async with aiosqlite.connect(DB_NAME) as db:
        async with db.execute("SELECT mode FROM rss_sources WHERE rowid = ?", (row_id,)) as c:
            row = await c.fetchone()
            if not row: return await callback.answer("未找到数据。", show_alert=True)
            mode = row[0]
            new_mode = 'normal' if mode == 'keyword' else 'keyword'
            await db.execute("UPDATE rss_sources SET mode = ? WHERE rowid = ?", (new_mode, row_id))
            await db.commit()
    await callback.answer(f"已变更为: {'📢 全量订阅模式' if new_mode=='normal' else '🎯 关键词监控模式'}。")
    await show_rss_menu(callback)

@dp.callback_query(F.data.startswith("drss_"))
async def db_del_rss(callback: CallbackQuery):
    row_id = callback.data.split("_")[1]
    async with aiosqlite.connect(DB_NAME) as db:
        await db.execute("DELETE FROM rss_sources WHERE rowid = ?", (row_id,))
        await db.commit()
    await callback.answer("🗑 订阅源已摧毁。")
    await show_rss_menu(callback)

@dp.callback_query(F.data.startswith("dkw_"))
async def db_del_kw(callback: CallbackQuery):
    row_id = callback.data.split("_")[1]
    async with aiosqlite.connect(DB_NAME) as db:
        await db.execute("DELETE FROM keywords WHERE rowid = ?", (row_id,))
        await db.commit()
    await callback.answer("🗑 词库削减成功。")
    await show_kw_menu(callback)

# --- 3. 历史记录系统 ---
@dp.callback_query(F.data == "btn_history")
async def show_history(callback: CallbackQuery):
    target_ts = int(time.time()) - 86400  # 过去 24h
    async with aiosqlite.connect(DB_NAME) as db:
        async with db.execute("SELECT keyword, title, ts FROM push_history WHERE ts >= ? ORDER BY ts DESC LIMIT 30", (target_ts,)) as c:
            items = await c.fetchall()

    if not items:
        return await callback.answer("过去 24h 内没有任何因关键词碰撞而推送的记录。", show_alert=True)

    res = "🕒 **近 24 小时关键词命中流水**\n━━━━━━━━━━━━━━━━\n"
    for kw, title, ts in items:
        dt = datetime.fromtimestamp(ts, TIMEZONE).strftime('%m-%d %H:%M')
        res += f"`{dt}` [**{kw}**] {title}\n"

    if len(res) > 3500:
        res = res[:3500] + "...\n*(篇幅限制截断)*"

    kb = InlineKeyboardMarkup(inline_keyboard=[[InlineKeyboardButton(text="🔙 查阅完毕,返回主界面", callback_data="btn_to_main")]])
    await callback.message.edit_text(res, reply_markup=kb, parse_mode="Markdown")

# --- 4. 频率调节 ---
@dp.callback_query(F.data == "btn_interval")
async def edit_interval(callback: CallbackQuery, state: FSMContext):
    if callback.from_user.id != ADMIN_ID: return await callback.answer("仅系统超级管理员有权调整全局参数!", show_alert=True)
    await state.set_state(BotStates.waiting_for_interval)
    kb = InlineKeyboardMarkup(inline_keyboard=[[InlineKeyboardButton(text="🔙 取消设定", callback_data="btn_to_main")]])
    await callback.message.edit_text("⏱ **全局休眠调整:** \n(请输入纯数字的秒数,如 `300`,最低要求为 30)", reply_markup=kb, parse_mode="Markdown")

@dp.message(BotStates.waiting_for_interval)
async def process_interval_input(message: Message, state: FSMContext):
    try:
        val = int(message.text.strip())
        if val < 30: raise ValueError
    except:
        return await message.answer("❌ 无效。必须 >= 30。\n请重新发送纯数字。", reply_markup=InlineKeyboardMarkup(inline_keyboard=[[InlineKeyboardButton(text="退出", callback_data="btn_to_main")]]))

    async with aiosqlite.connect(DB_NAME) as db:
        await db.execute("UPDATE settings SET value = ? WHERE key = 'check_interval'", (str(val),))
        await db.commit()
    await state.clear()
    await message.answer(f"✅ 系统轮询已定档 **{val}** 秒。\n将在后台自动接管。", reply_markup=InlineKeyboardMarkup(inline_keyboard=[[InlineKeyboardButton(text="返回中控", callback_data="btn_to_main")]]))

# --- 全局返回按钮 ---
@dp.callback_query(F.data == "btn_to_main")
async def back_to_main(callback: CallbackQuery, state: FSMContext):
    await state.clear()
    welcome = (
        "🤖 **Leo's RSS 关键词监控系统**\n"
        "━━━━━━━━━━━━━━━━━━━━━\n"
        "欢迎回来!\n"
        "请点击下方按钮操作:"
    )
    await callback.message.edit_text(welcome, reply_markup=get_main_menu(), parse_mode="Markdown")

@dp.callback_query(F.data == "btn_close")
async def close_menu(callback: CallbackQuery, state: FSMContext):
    await state.clear()
    await callback.message.delete()

# ==========================================
# 后台监控核心
# ==========================================

async def fetch_rss_task():
    while True:
        try:
            current_interval = await get_interval()
            async with aiosqlite.connect(DB_NAME) as db:
                async with db.execute("SELECT url, mode, alias FROM rss_sources") as c:
                    sources = await c.fetchall()
                async with db.execute("SELECT word FROM keywords") as c:
                    keywords = [row[0] for row in await c.fetchall()]

                for url, mode, alias in sources:
                    try:
                        feed = await asyncio.to_thread(feedparser.parse, url)
                        if getattr(feed, 'bozo_exception', None): pass # 静默报错

                        for entry in feed.entries:
                            link = entry.get('link')
                            if not link: continue

                            async with db.execute("SELECT 1 FROM seen_links WHERE link = ?", (link,)) as c:
                                if await c.fetchone(): continue

                            title = entry.get('title', '无标题')
                            summary = entry.get('summary', '')
                            full_content = ""
                            if 'content' in entry and len(entry.content) > 0:
                                full_content = entry.content[0].get('value', '')

                            content = (title + summary + full_content).lower()

                            should_push = False
                            match_label = ""

                            if mode == 'normal':
                                should_push = True
                                match_label = "全量模式"
                            else:
                                matched = next((k for k in keywords if k.lower() in content), None)
                                if matched:
                                    should_push = True
                                    match_label = f"#{matched}"

                            if should_push:
                                await send_report(match_label, title, link, alias)

                            await db.execute("INSERT OR IGNORE INTO seen_links (link) VALUES (?)", (link,))
                        await db.commit()
                    except Exception as e:
                        logging.error(f"解析 {alias} 单线程异常: {e}")
                        continue
        except Exception as e:
            logging.error(f"队列总阻塞: {e}")

        await asyncio.sleep(current_interval)

# --- 启动 ---

async def main():
    await init_db()
    logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

    import re
    background_task = asyncio.create_task(fetch_rss_task())
    await bot.delete_webhook(drop_pending_updates=True)
    try:
        await dp.start_polling(bot)
    finally:
        background_task.cancel()
        await bot.session.close()

if __name__ == "__main__":
    try:
        loop = asyncio.get_running_loop()
    except RuntimeError:
        loop = None

    if loop and loop.is_running():
        try:
            import nest_asyncio
            nest_asyncio.apply()
        except ImportError: pass

    try:
        asyncio.run(main())
    except (KeyboardInterrupt, SystemExit):
        logging.info("程序断开")

🐋 进阶选项:使用 Docker 一键部署

如果你不想在系统里安装各种 Python 插件,或者希望更方便地迁移和管理,可以尝试 Docker 部署。这也是目前非常推荐的运行方式。

1. 准备配置文件

在你的脚本目录下(例如 /opt/tgbot),确保你已经创建好了修改过配置(Token 和 ADMIN_ID)的 tg-rssbot.py 脚本。

2. 编写 Dockerfile

在该目录下创建一个名为 Dockerfile 的文件: nano Dockerfile

粘贴以下内容:

# 使用轻量级 Python 镜像
FROM python:3.10-slim

# 设置工作目录
WORKDIR /app

# 安装必要的系统依赖和 Python 库
RUN pip install --no-cache-dir \
    aiogram \
    aiosqlite \
    feedparser \
    pytz \
    nest_asyncio

# 将当前目录下的脚本复制到容器中
COPY tg-rssbot.py .

# 设置环境变量,确保日志实时输出
ENV PYTHONUNBUFFERED=1

# 启动脚本
CMD ["python", "tg-rssbot.py"]

3. 构建镜像并启动

在当前目录下执行以下命令:

# 构建名为 tg-rssbot 的镜像
docker build -t tg-rssbot .

# 启动容器
# -v $(pwd):/app 的作用是将数据库文件持久化在宿主机,防止容器重启数据丢失
docker run -d \
  --name my-rss-bot \
  --restart always \
  -v $(pwd):/app \
  tg-rssbot

4. 如何查看日志?

如果 Bot 没有反应,可以通过以下命令检查运行状态或报错信息:

docker logs -f my-rss-bot

LeoKnox

Leo Leo Leo

文章评论