Files

272 lines
9.6 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""FEED — пост-процессор findings: обогащение, фильтры, дедуп, скоринг,
пост топ-N в Telegram-канал через Telethon (user-сессия).
Читает output/findings.jsonl инкрементально (offset в sqlite), обогащает
(size_mb, контакты, бейджи), фильтрует malware-мусор, дедуплицирует по
нормализованному title+domain, скорит и постит топ-N.
Настройка (ОДИН РАЗ):
1. Получи api_id/api_hash на https://my.telegram.org
2. export TG_API_ID=123456 TG_API_HASH=xxxx (или впиши в data/creds.json)
3. python feed.py --login # интерактивный логин, сессия -> data/feed_session
4. Впиши id/username канала в config.json -> "feed_chat"
Запуск: python feed.py [--dry] [--limit N] [--reset]
Cron: 40 */2 * * *
Важно: сессия — ОТДЕЛЬНОЙ копией, коннект короткий.
При AuthKeyDuplicated — скип рана (не ретраить, иначе ключ сгорит).
"""
import json
import os
import re
import sqlite3
import sys
from datetime import datetime, timezone
from pathlib import Path
try:
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
except Exception:
pass
BASE = Path(__file__).resolve().parent
DATA = BASE / "data"
DATA.mkdir(exist_ok=True)
FINDINGS = BASE / "output" / "findings.jsonl"
DB = DATA / "feed_state.db"
SESS = DATA / "feed_session"
def _load_json(path: Path, default):
if path.exists():
try:
return json.loads(path.read_text(encoding="utf-8"))
except Exception:
return default
return default
CFG = _load_json(BASE / "config.json", {})
CREDS = _load_json(DATA / "creds.json", {})
ENVGET = os.environ.get
API_ID = int(ENVGET("TG_API_ID") or CREDS.get("tg_api_id") or 0)
API_HASH = ENVGET("TG_API_HASH") or CREDS.get("tg_api_hash") or ""
FEED_CHAT = ENVGET("FEED_CHAT") or CFG.get("feed_chat") or ""
# ── фильтры (никакой малвари, только инфо/тулзы) ──
EXCLUDE_RE = re.compile(
r"\b(rat\b|stealer|ransom|backdoor|drainer|worm\b|botnet|virus|keylogger|"
r"malware|trojan|crypter|fud\b|exploit kit|ddos tool|booter|stresser)\b",
re.I)
HOT_RE = re.compile(
r"combolist|combo list|combo\b|\bhq\b|full capture|valid\b|checker|config\b|"
r"openbullet|silverbullet|storm\b|ob2\b|database|\bleak|smtp|proxy|proxies|"
r"sms\b|email|accounts?\b|dorks?\b|crack", re.I)
SIZE_RE = re.compile(r"(\d+(?:[.,]\d+)?)\s*(GB|MB|KB)\b", re.I)
CONTACT_RE = re.compile(r"@([A-Za-z][A-Za-z0-9_]{4,31})\b")
def norm_key(name: str, url: str) -> str:
dom = ""
m = re.match(r"https?://([^/]+)", url or "")
if m:
dom = m.group(1).lower().replace("www.", "").split(".")[0]
n = re.sub(r"[^a-z0-9а-я]+", "", (name or "").lower())[:60]
return f"{dom}:{n}"
def db_open() -> sqlite3.Connection:
con = sqlite3.connect(str(DB), timeout=30)
con.execute("PRAGMA busy_timeout=20000")
con.execute("CREATE TABLE IF NOT EXISTS meta(k TEXT PRIMARY KEY, v TEXT)")
con.execute("CREATE TABLE IF NOT EXISTS seen(key TEXT PRIMARY KEY, first_at TEXT, name TEXT, source TEXT)")
con.execute("CREATE TABLE IF NOT EXISTS posted(key TEXT PRIMARY KEY, msg_id INTEGER, at TEXT)")
return con
def load_new(con) -> list:
row = con.execute("SELECT v FROM meta WHERE k='offset'").fetchone()
off = int(row[0]) if row else 0
out = []
if not FINDINGS.exists():
return out
with open(FINDINGS, "r", encoding="utf-8") as f:
f.seek(off)
for line in f:
line = line.strip()
if not line:
continue
try:
out.append(json.loads(line))
except json.JSONDecodeError:
continue
new_off = f.tell()
con.execute("INSERT INTO meta(k,v) VALUES('offset',?) ON CONFLICT(k) DO UPDATE SET v=excluded.v", (str(new_off),))
con.commit()
return out
def enrich(f: dict) -> dict:
text = f"{f.get('name','')} {f.get('description','')}"
size_mb = 0.0
for num, unit in SIZE_RE.findall(text):
v = float(num.replace(",", "."))
size_mb += v * 1024 if unit.upper() == "GB" else (v if unit.upper() == "MB" else v / 1024)
f["_size_mb"] = round(size_mb, 1)
contacts = CONTACT_RE.findall(text)
f["_contacts"] = ["@" + c for c in dict.fromkeys(contacts)
if c.lower() not in ("telegram", "gmail", "yahoo", "hotmail", "outlook")][:2]
price = (f.get("price") or "").lower()
score = 0.0
score += min(f["_size_mb"] / 60.0, 4.0) if f["_size_mb"] <= 50000 else 0.5
if HOT_RE.search(text):
score += 2.0
if "free" in price or "бесплат" in price:
score += 1.0
t = (f.get("type") or "").lower()
score += {"combolist": 2.5, "config": 2.0, "configs": 2.0, "database": 2.0, "leak": 2.0, "checker": 1.5,
"proxy": 1.5, "smtp": 1.5, "sms": 1.2, "email": 1.2, "autoreg": 1.0,
"freebie": 1.8, "ai-credits": 2.0, "vpn": 1.2, "accounts": 1.2, "tool": 1.0,
"traffic": 0.5, "inviter": 0.5}.get(t, 0.8)
try:
age_h = (datetime.now(timezone.utc) - datetime.fromisoformat(f["scraped_at"])).total_seconds() / 3600
score += max(0.0, 2.0 - age_h / 24)
except Exception:
pass
f["_score"] = round(score, 2)
return f
def pick(items: list, limit: int, con) -> list:
fresh = []
for f in items:
name, url = f.get("name") or "", f.get("url") or ""
if not name or not url.startswith("http"):
continue
text = f"{name} {f.get('description','')}"
if EXCLUDE_RE.search(text):
continue
try:
age_h = (datetime.now(timezone.utc) - datetime.fromisoformat(f.get("scraped_at", ""))).total_seconds() / 3600
except Exception:
age_h = 9999
if age_h > 72:
continue
key = norm_key(name, url)
if con.execute("SELECT 1 FROM seen WHERE key=?", (key,)).fetchone():
continue
f = enrich(f)
f["_key"] = key
fresh.append(f)
fresh.sort(key=lambda x: -x["_score"])
return fresh[:limit]
def md_escape(s: str) -> str:
return re.sub(r"[*_`\[\]]", "", s or "").strip()
def fmt_message(items: list) -> str:
stamp = datetime.now().strftime("%d.%m %H:%M")
lines = [f"DARK FORUM FEED - {stamp} | *новых: {len(items)}*", ""]
for f in items:
name = md_escape(f.get("name", ""))[:70]
url = f.get("url", "")
desc = md_escape(f.get("description", ""))[:130]
meta = []
if f.get("_size_mb") and f["_size_mb"] <= 50000:
meta.append(f"{f['_size_mb']:g} MB")
if f.get("type"):
meta.append(f"тип: {md_escape(f['type'])}")
if f.get("price") and "not specified" not in f["price"].lower():
meta.append(f"{md_escape(f['price'])[:30]}")
if f.get("_contacts"):
meta.append(" ".join(f"`{c}`" for c in f["_contacts"]))
meta.append(f"src: {md_escape(f.get('source','?'))}")
lines.append(f"- [{name}]({url})")
if desc:
lines.append(f" {desc}")
lines.append(f" {' | '.join(meta)}")
lines.append("")
return "\n".join(lines).strip()
def _client():
from telethon import TelegramClient
if not API_ID or not API_HASH:
raise RuntimeError("TG_API_ID/TG_API_HASH не заданы (env или data/creds.json). Получи на my.telegram.org")
return TelegramClient(str(SESS), API_ID, API_HASH)
def login():
import asyncio
async def _run():
c = _client()
await c.start()
me = await c.get_me()
await c.disconnect()
print(f"LOGIN OK: id={me.id} @{me.username}")
asyncio.run(_run())
def post(msg: str):
import asyncio
if not FEED_CHAT:
raise RuntimeError("feed_chat не задан в config.json (id или @username канала)")
async def _run():
c = _client()
await c.start()
m = await c.send_message(FEED_CHAT, msg, parse_mode="md", link_preview=False)
mid = m.id
back = await c.get_messages(FEED_CHAT, ids=mid)
await c.disconnect()
return mid, bool(back)
return asyncio.run(_run())
def main():
if "--login" in sys.argv:
login()
return 0
dry = "--dry" in sys.argv
limit = 12
if "--limit" in sys.argv:
limit = int(sys.argv[sys.argv.index("--limit") + 1])
con = db_open()
if "--reset" in sys.argv:
con.execute("DELETE FROM meta WHERE k='offset'")
con.commit()
items = load_new(con)
print(f"[feed] new findings: {len(items)}")
top = pick(items, limit, con)
if not top:
print("[feed] nothing fresh to post")
con.commit()
return 0
msg = fmt_message(top)
if dry:
print("=== DRY ===")
print(msg)
return 0
try:
mid, ok = post(msg)
except Exception as e:
print(f"[feed] POST FAIL: {type(e).__name__}: {str(e)[:150]}")
return 1
now = datetime.now().isoformat()
for f in top:
con.execute("INSERT OR IGNORE INTO seen(key,first_at,name,source) VALUES(?,?,?,?)",
(f["_key"], now, f.get("name", ""), f.get("source", "")))
con.execute("INSERT OR IGNORE INTO posted(key,msg_id,at) VALUES(?,?,?)", (f["_key"], mid, now))
con.commit()
print(f"[feed] POSTED msg_id={mid} verify={ok} items={len(top)}")
return 0
if __name__ == "__main__":
raise SystemExit(main())