#!/usr/bin/env python3 """ book_bot.py — книжный бот в Matrix. ЧТО УМЕЕТ: /find <название> — искать книгу во всех источниках (магазин, каталоги, архивы, библиотеки) и прислать что нашлось; /lib <запрос> — поиск по своей библиотеке (что уже есть); /wanted — список книг, которые ещё не найдены; /tg <название> — поиск постов в добавленных Telegram-каналах (через веб-предпросмотр, без аккаунта); /tgadd <канал> — добавить канал в список для поиска; /tglist — какие каналы добавлены; /tgdel <канал> — убрать канал; /help — помощь. Работает через long-polling /sync, без внешних библиотек. """ import json import os import re import sqlite3 import sys import time import urllib.parse import urllib.request from datetime import datetime HS = os.environ.get("MATRIX_HS", "http://192.168.1.155:8008") TOKEN = os.environ.get("MATRIX_TOKEN", "") CFG = os.environ.get("BOT_CONFIG", "/app/config.json") VPN = os.environ.get("VPN_PROXY", "http://192.168.1.161:7890") LIB_DB = os.environ.get("CALIBRE_DB", "/calibre/metadata.db") UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/155" ALLOWED = set() def log(msg): line = f"[{datetime.now():%Y-%m-%d %H:%M:%S}] {msg}" print(line, flush=True) def load_cfg(): try: with open(CFG, encoding="utf-8") as f: return json.load(f) except Exception: return {"users": [], "tg_channels": []} def save_cfg(cfg): with open(CFG, "w", encoding="utf-8") as f: json.dump(cfg, f, ensure_ascii=False, indent=2) def api(method, path, body=None): url = f"{HS}{path}" sep = "&" if "?" in url else "?" url += f"{sep}access_token={TOKEN}" data = json.dumps(body).encode() if body is not None else None req = urllib.request.Request(url, data=data, method=method, headers={"Content-Type": "application/json"}) with urllib.request.urlopen(req, timeout=40) as r: raw = r.read().decode() return json.loads(raw) if raw else {} def send(room, text): tx = str(int(time.time() * 1000)) try: api("PUT", f"/_matrix/client/v3/rooms/{urllib.parse.quote(room)}" f"/send/m.room.message/{tx}", {"msgtype": "m.text", "body": text}) return True except Exception as e: log(f"не отправить в {room}: {e}") return False def fetch(url, via_vpn=False): req = urllib.request.Request(url, headers={"User-Agent": UA, "Accept-Language": "ru,en;q=0.8"}) opener = (urllib.request.build_opener( urllib.request.ProxyHandler({"http": VPN, "https": VPN})) if via_vpn else urllib.request.build_opener()) try: with opener.open(req, timeout=30) as r: return r.read().decode("utf-8", "replace") except Exception: return "" def norm(s): return re.sub(r"\s+", " ", (s or "").lower()).strip() # ---------- поиск ---------- def search_library(query): """Что уже есть в библиотеке.""" try: con = sqlite3.connect(f"file:{LIB_DB}?mode=ro", uri=True) rows = con.execute( "select b.title, group_concat(a.name, ', ') from books b " "left join books_authors_link l on l.book=b.id " "left join authors a on a.id=l.author " "where lower(b.title) like ? group by b.id limit 8", (f"%{norm(query)}%",), ).fetchall() con.close() return rows except Exception as e: log(f"библиотека не читается: {e}") return [] def search_litres(title): html = fetch("https://www.litres.ru/search/?q=" + urllib.parse.quote(title)) if not html: return [] html = html.replace('\\"', '"') out = [] pat = re.compile( r'"id":\d+,"uuid":"[^"]*","cover_url":"[^"]*","url":"(/book/[^"]+)","title":"((?:[^"\\]|\\.){1,150})"') for m in pat.finditer(html): tail = html[m.end(): m.end() + 900] price = re.search(r'"final_price":(\d+)', tail) out.append((m.group(2).strip(), int(price.group(1)) if price else None, "https://www.litres.ru" + m.group(1))) if len(out) >= 3: break return out def search_openlibrary(title): url = "https://openlibrary.org/search.json?" + urllib.parse.urlencode({"title": title, "limit": 3}) raw = fetch(url) if not raw: return [] try: d = json.loads(raw) except Exception: return [] out = [] for doc in (d.get("docs") or [])[:3]: out.append((doc.get("title"), doc.get("first_publish_year"), "https://openlibrary.org" + (doc.get("key") or ""))) return out def search_archive(title): q = f'title:("{title}")' url = ("https://archive.org/advancedsearch.php?" + urllib.parse.urlencode({"q": q, "rows": 3, "output": "json", "fl[]": ["identifier", "title", "year"]}, doseq=True)) raw = fetch(url, via_vpn=True) if not raw: return [] try: d = json.loads(raw) except Exception: return [] out = [] for doc in (d.get("response", {}).get("docs") or [])[:3]: if doc.get("identifier"): out.append((doc.get("title"), doc.get("year"), f"https://archive.org/details/{doc['identifier']}")) return out def search_flibusta(title): html = fetch("https://flibusta.is/booksearch?ask=" + urllib.parse.quote(title), via_vpn=True) if not html: return [] out = [] for m in re.finditer(r'href="(/b/\d+)"[^>]*>([^<]{2,120})', html): out.append((m.group(2).strip(), None, "https://flibusta.is" + m.group(1))) if len(out) >= 3: break return out def search_libgen(title): html = fetch("https://libgen.li/index.php?req=" + urllib.parse.quote(title), via_vpn=True) if not html: return [] out = [] for m in re.finditer(r'href="edition\.php\?id=(\d+)"[^>]*>(.{0,300}?)', html, re.S): raw = re.sub(r"<[^>]+>", " ", m.group(2)) raw = re.sub(r"\s+", " ", raw).strip() if raw: out.append((raw[:80], None, f"https://libgen.li/edition.php?id={m.group(1)}")) if len(out) >= 3: break return out def search_telegram_channels(query, channels): """Ищет посты в публичных каналах через веб-предпросмотр.""" out = [] for ch in channels[:5]: name = ch.lstrip("@").replace("https://t.me/", "").strip("/") html = fetch(f"https://t.me/s/{name}?q={urllib.parse.quote(query)}", via_vpn=True) if not html: continue posts = re.findall(r'class="tgme_widget_message_text[^"]*"[^>]*>(.*?)', html, re.S) for p in posts[:2]: text = re.sub(r"<[^>]+>", " ", p) text = re.sub(r"\s+", " ", text).strip() if text: out.append((name, text[:200], f"https://t.me/{name}")) if out: break return out def cmd_find(query, cfg): lines = [f"🔎 Ищу: **{query}**", ""] lib = search_library(query) if lib: lines.append("✅ **Уже есть в вашей библиотеке:**") for t, a in lib[:5]: lines.append(f"• {t}" + (f" — {a}" if a else "")) lines.append("") found = False for name, fn, note in ( ("ЛитРес", search_litres, "цена"), ("Open Library", search_openlibrary, ""), ("archive.org", search_archive, "VPN"), ("Флибуста", search_flibusta, "VPN"), ("libgen", search_libgen, "VPN"), ): try: res = fn(query) except Exception: res = [] if res: found = True lines.append(f"📚 **{name}**" + (f" ({note})" if note else "")) for item in res[:3]: t, extra, url = item price = "" if isinstance(extra, int) and extra > 100: price = f" — {extra} ₽" elif extra: price = f" — {extra}" lines.append(f"• [{t}]({url}){price}") lines.append("") chans = cfg.get("tg_channels") or [] if chans: tg = search_telegram_channels(query, chans) if tg: found = True lines.append("📨 **В Telegram-каналах:**") for ch, text, url in tg[:3]: lines.append(f"• @{ch}: {text}") lines.append("") if not found and not lib: lines.append("Ничего не нашлось. Попробуйте другое название или " "добавьте Telegram-канал: `/tgadd @имя`.") return "\n".join(lines) def cmd_wanted(): try: con = sqlite3.connect("/app/catalog.db") rows = con.execute( "select next_title, name, authors from series where next_title is not null " "and coalesce(next_availability,'') not in ('scheduled','announced_no_date') " "order by name limit 15").fetchall() con.close() except Exception: return "Каталог недоступен." if not rows: return "Список пуст." out = ["📋 **Книги, которые ещё не найдены:**", ""] for t, s, a in rows: out.append(f"• {t} — серия «{s}»" + (f", {a}" if a else "")) out.append("") out.append("Найти: `/find название`") return "\n".join(out) def cmd_tg_add(arg, cfg): name = arg.lstrip("@").replace("https://t.me/", "").strip("/").strip() if not name: return "Укажите канал: `/tgadd @имя_канала`" chans = cfg.setdefault("tg_channels", []) if name in chans: return f"Канал @{name} уже в списке." chans.append(name) save_cfg(cfg) # проверяю, читается ли ok = bool(fetch(f"https://t.me/s/{name}", via_vpn=True)) return (f"✅ Добавил @{name}." + ("" if ok else "\n⚠️ Не удалось прочитать — проверьте имя.")) def main(): cfg = load_cfg() allowed = set(cfg.get("users") or []) log(f"бот запущен, разрешённых пользователей: {len(allowed)}") since = None me = None try: me = api("GET", "/_matrix/client/v3/account/whoami")["user_id"] log(f"я — {me}") except Exception as e: log(f"не смог определить себя: {e}") while True: try: params = {"timeout": 25000} if since: params["since"] = since res = api("GET", "/_matrix/client/v3/sync?" + urllib.parse.urlencode(params)) since = res.get("next_batch") or since for room, data in (res.get("rooms", {}).get("join", {}) or {}).items(): for ev in (data.get("timeline", {}).get("events") or []): if ev.get("type") != "m.room.message": continue sender = ev.get("sender", "") body = (ev.get("content", {}).get("body") or "").strip() if not body.startswith("/"): continue if allowed and sender not in allowed: send(room, "⛔ У вас нет доступа к книжному боту.\n" f"Ваш адрес: `{sender}` — попросите администратора добавить.") continue parts = body.split(maxsplit=1) cmd = parts[0].lower() arg = parts[1].strip() if len(parts) > 1 else "" log(f"{sender}: {cmd} {arg}") if cmd in ("/help", "/start"): reply = ( "📚 **Книжный бот**\n\n" "`/find название` — искать книгу везде\n" "`/lib запрос` — что уже есть в библиотеке\n" "`/wanted` — что ещё не найдено\n" "`/tgadd @канал` — добавить Telegram-канал для поиска\n" "`/tglist` — список каналов\n" "`/tgdel @канал` — убрать канал\n\n" "Бот ищет в ЛитРес, Open Library, archive.org, " "Флибусте, libgen и в добавленных каналах Telegram." ) elif cmd == "/find": reply = cmd_find(arg, cfg) if arg else "Напишите название: `/find Дюна`" elif cmd == "/lib": if not arg: reply = "Что искать? `/lib Дюна`" else: rows = search_library(arg) reply = ("📖 **В библиотеке:**\n" + "\n".join( f"• {t}" + (f" — {a}" if a else "") for t, a in rows)) if rows \ else f"В библиотеке нет «{arg}»." elif cmd == "/wanted": reply = cmd_wanted() elif cmd == "/tgadd": reply = cmd_tg_add(arg, cfg) elif cmd == "/tglist": ch = cfg.get("tg_channels") or [] reply = ("📨 Каналы: " + ", ".join("@" + c for c in ch)) if ch else "Список пуст. `/tgadd @канал`" elif cmd == "/tgdel": name = arg.lstrip("@").strip() ch = cfg.get("tg_channels") or [] if name in ch: ch.remove(name) save_cfg(cfg) reply = f"Убрал @{name}." else: reply = f"@{name} нет в списке." else: reply = "Не знаю такой команды. `/help`" send(room, reply) except Exception as e: log(f"ошибка цикла: {e}") time.sleep(5) if __name__ == "__main__": main()