Files
buryan-infra/ops/userbot/userbot.py
T
buryan-agent 3af6737511 Telegram userbot на втором номере: сервис, CLI и связка с книжным ботом
Второй аккаунт (+79105469668, id 6922233999) авторизован через Telethon
по api_id от mautrix. Работает через прокси CT161 (прямого интернета нет).

Что есть: CLI (whoami/dialogs/find/join/files/save) и HTTP-сервис на 9122
(/health, /files, /save), который скачивает файлы в /opt/books/ingest —
дальше Calibre-Web импортирует сам. В книжном боте появились /tg <запрос>
и /tg скачать N.

Выяснилось: публичные книжные каналы — витрины со ссылками на ботов, файлов
там нет. Нужны каналы, где книги выкладывают файлами, или книжный бот,
которому userbot будет писать запрос.

Ловушка: PowerShell добавляет BOM в файлы — Python падает на U+FEFF.
2026-10-21 11:53:56 +03:00

247 lines
8.5 KiB
Python

#!/usr/bin/env python3
"""Userbot на втором номере Telegram (Telethon).
Шаги:
python3 userbot.py login-start +7XXXXXXXXXX — отправить код
python3 userbot.py login-code 12345 [пароль] — ввести код (и облачный пароль)
python3 userbot.py whoami — проверить, кто вошёл
python3 userbot.py dialogs [фильтр] — список чатов
python3 userbot.py search <запрос> — поиск по каналам
python3 userbot.py save <ссылка|id> [папка] — скачать файл из чата
"""
import asyncio
import json
import os
import sys
from telethon import TelegramClient
from telethon.errors import SessionPasswordNeededError
API_ID = 39725134
API_HASH = "65542daa8cb9a8aa1ad54cf1860ad414"
PROXY_HOST = os.environ.get("VPN_PROXY_HOST", "192.168.1.161")
PROXY_PORT = int(os.environ.get("VPN_PROXY_PORT", "7890"))
SESSION = os.environ.get("USERBOT_SESSION", "/root/.telegram-userbot/second")
STATE = "/root/.telegram-userbot/state.json"
INGEST = os.environ.get("INGEST_DIR", "/ingest")
NOTIFY = os.environ.get("NOTIFY_URL", "http://127.0.0.1:9120/notify")
def client() -> TelegramClient:
proxy = ("http", PROXY_HOST, PROXY_PORT)
return TelegramClient(SESSION, API_ID, API_HASH, proxy=proxy,
device_model="Buryans Hub", system_version="Linux",
app_version="1.0")
def save_state(**kw):
os.makedirs(os.path.dirname(STATE), exist_ok=True)
try:
st = json.load(open(STATE))
except Exception:
st = {}
st.update(kw)
json.dump(st, open(STATE, "w"))
def notify(title, message):
import urllib.request
body = json.dumps({"title": title, "message": message}).encode()
req = urllib.request.Request(NOTIFY, data=body, method="POST",
headers={"Content-Type": "application/json"})
try:
urllib.request.urlopen(req, timeout=10).read()
except Exception as e:
print("notify:", e)
async def login_start(phone):
c = client()
await c.connect()
if await c.is_user_authorized():
me = await c.get_me()
print(f"уже авторизован: @{me.username or me.id}")
await c.disconnect()
return
sent = await c.send_code_request(phone)
save_state(phone=phone, phone_code_hash=sent.phone_code_hash)
print("код отправлен. Введите: python3 userbot.py login-code <код> [пароль]")
await c.disconnect()
async def login_code(code, password=None):
st = json.load(open(STATE))
c = client()
await c.connect()
try:
await c.sign_in(phone=st["phone"], code=code,
phone_code_hash=st.get("phone_code_hash"))
except SessionPasswordNeededError:
if not password:
print("НУЖЕН_ПАРОЛЬ")
await c.disconnect()
return
await c.sign_in(password=password)
me = await c.get_me()
save_state(authed=True, user_id=me.id, username=me.username)
print(f"вошли как {me.first_name} (@{me.username or me.id})")
notify("Telegram userbot подключён",
f"Аккаунт @{me.username or me.id} авторизован на сервере.")
await c.disconnect()
async def whoami():
c = client()
await c.connect()
if not await c.is_user_authorized():
print("не авторизован")
await c.disconnect()
return
me = await c.get_me()
print(f"id={me.id} username=@{me.username} name={me.first_name} phone={me.phone}")
await c.disconnect()
async def dialogs(flt=""):
c = client()
await c.connect()
async for d in c.iter_dialogs(limit=200):
name = d.name or ""
if flt and flt.lower() not in name.lower():
continue
kind = "канал" if d.is_channel else ("группа" if d.is_group else "личный")
print(f"{d.id}\t{kind}\t{name}")
await c.disconnect()
async def search(query, limit=20):
c = client()
await c.connect()
found = 0
async for d in c.iter_dialogs(limit=200):
if not (d.is_channel or d.is_group):
continue
try:
async for msg in c.iter_messages(d, search=query, limit=5):
text = (msg.message or "").replace("\n", " ")[:150]
fname = ""
if msg.document:
fname = next((a.file_name for a in msg.document.attributes
if hasattr(a, "file_name")), "") or ""
print(f"{d.id}\t{d.name}\t{msg.id}\t{fname}\t{text}")
found += 1
except Exception:
continue
if not found:
print("ничего не найдено")
await c.disconnect()
async def find_channels(query, limit=15):
"""Ищет публичные каналы/группы по названию (глобальный поиск)."""
from telethon.tl.functions.contacts import SearchRequest
c = client()
await c.connect()
res = await c(SearchRequest(q=query, limit=limit))
for chat in res.chats:
username = getattr(chat, "username", None)
title = getattr(chat, "title", None)
kind = "канал" if getattr(chat, "broadcast", False) else "группа"
members = getattr(chat, "participants_count", None)
print(f"{chat.id}\t{kind}\t{title}\t@{username or '—'}\t{members or '?'}")
await c.disconnect()
async def join(target):
from telethon.tl.functions.channels import JoinChannelRequest
c = client()
await c.connect()
try:
ent = await c.get_entity(target)
await c(JoinChannelRequest(ent))
print(f"подписался: {getattr(ent, 'title', target)}")
except Exception as e:
print("не удалось:", str(e)[:160])
await c.disconnect()
async def files(query, limit=30):
"""Ищет файлы (книги) в каналах, где аккаунт уже состоит."""
c = client()
await c.connect()
found = 0
async for d in c.iter_dialogs(limit=200):
if not (d.is_channel or d.is_group):
continue
try:
async for msg in c.iter_messages(d, search=query, limit=8):
if not msg.document:
continue
name = next((a.file_name for a in msg.document.attributes
if hasattr(a, "file_name")), "") or ""
if not name:
continue
size = msg.document.size or 0
print(f"{d.id}\t{d.name}\t{msg.id}\t{name}\t{size}")
found += 1
except Exception:
continue
if not found:
print("файлов не найдено")
await c.disconnect()
async def save(link, folder=None):
c = client()
await c.connect()
target = link
msg_id = None
if "/" in link and not link.lstrip("-").isdigit():
parts = link.rstrip("/").split("/")
target, msg_id = parts[-2], int(parts[-1])
msg = await c.get_messages(target, ids=msg_id) if msg_id else None
if not msg or not msg.document:
print("в сообщении нет файла")
await c.disconnect()
return
dest = folder or INGEST
os.makedirs(dest, exist_ok=True)
path = await c.download_media(msg, file=dest)
print("сохранено:", path)
notify("Книга из Telegram", f"Скачано: {os.path.basename(path)}")
await c.disconnect()
def main():
if len(sys.argv) < 2:
print(__doc__)
return
cmd = sys.argv[1]
args = sys.argv[2:]
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
if cmd == "login-start":
loop.run_until_complete(login_start(args[0]))
elif cmd == "login-code":
loop.run_until_complete(login_code(args[0], args[1] if len(args) > 1 else None))
elif cmd == "whoami":
loop.run_until_complete(whoami())
elif cmd == "dialogs":
loop.run_until_complete(dialogs(args[0] if args else ""))
elif cmd == "search":
loop.run_until_complete(search(args[0]))
elif cmd == "find":
loop.run_until_complete(find_channels(args[0]))
elif cmd == "join":
loop.run_until_complete(join(args[0]))
elif cmd == "files":
loop.run_until_complete(files(args[0]))
elif cmd == "save":
loop.run_until_complete(save(args[0], args[1] if len(args) > 1 else None))
else:
print(__doc__)
if __name__ == "__main__":
main()