208 lines
7.5 KiB
Python
208 lines
7.5 KiB
Python
# -*- coding: utf-8 -*-
|
|
"""SOURCE DISCOVERY — ищет НОВЫЕ источники (форумы/тулзы/каналы).
|
|
|
|
web search (Firecrawl /search API, env FIRECRAWL_API_KEY) -> AI-экстракция
|
|
новых URL -> data/discovery_state.json. Дальше promote.py валидирует их
|
|
и добавляет в sources_extra.json (parse.py подхватывает автоматически).
|
|
|
|
Запуск: python discovery.py
|
|
Cron: 0 */3 * * *
|
|
"""
|
|
import json
|
|
import os
|
|
import re
|
|
import sys
|
|
import time
|
|
from datetime import datetime, timezone
|
|
from pathlib import Path
|
|
|
|
import requests
|
|
|
|
try:
|
|
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
|
except Exception:
|
|
pass
|
|
|
|
BASE = Path(__file__).resolve().parent
|
|
OUTPUT = BASE / "output"
|
|
OUTPUT.mkdir(exist_ok=True)
|
|
STATE = BASE / "data" / "discovery_state.json"
|
|
STATE.parent.mkdir(exist_ok=True)
|
|
|
|
|
|
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(BASE / "data" / "creds.json", {})
|
|
ENVGET = os.environ.get
|
|
AI_URL = ENVGET("AI_URL") or CFG.get("ai_url") or CREDS.get("ai_url") or "http://127.0.0.1:8000/v1/chat/completions"
|
|
AI_MODEL = ENVGET("AI_MODEL") or CFG.get("ai_model") or "gpt-4o-mini"
|
|
AI_KEY = ENVGET("AI_KEY") or CREDS.get("ai_key") or CFG.get("ai_key") or ""
|
|
|
|
SEARCH_QUERIES = [
|
|
"telegram spam software forum 2026",
|
|
"telegram marketing tool free download 2026",
|
|
"telegram scraper parser tool github 2026",
|
|
"telegram mass dm inviter bot 2026",
|
|
"telegram autoreg account creator tool",
|
|
"telegram userbot python telethon 2026",
|
|
"форум телеграм софт рассылка 2026",
|
|
"cracking forum telegram tools 2026",
|
|
"carding forum telegram software 2026",
|
|
"трафик арбитраж телеграм софт форум 2026",
|
|
"darknet forum telegram spam 2026",
|
|
"hacking forum telegram tools list 2026",
|
|
"telegram proxy checker tool free 2026",
|
|
"telegram session converter tdata tool 2026",
|
|
"telegram channel scraper member extractor 2026",
|
|
"telegram bot builder no code free 2026",
|
|
"telegram marketing software SaaS pricing 2026",
|
|
"best telegram bulk sender 2026 comparison",
|
|
"telegram outreach automation tool 2026",
|
|
"telegram CRM pipeline management 2026",
|
|
]
|
|
|
|
DISCOVERY_PROMPT = """You are a source discovery agent for Telegram tools and traffic software.
|
|
From this search result, extract:
|
|
1. NEW forum URLs (not in the known list below)
|
|
2. NEW GitHub repos for Telegram tools
|
|
3. NEW SaaS/commercial tools for Telegram
|
|
4. NEW Telegram channels about traffic/spam/tools
|
|
5. NEW darknet resources (.onion, Tor forums)
|
|
|
|
Skip anything already in sources.json / sources_extra.json of this repo (they are passed in KNOWN SOURCES).
|
|
|
|
Return ONLY a JSON array of NEW sources. Each: {"id":"...", "url":"...", "topic":"...", "name":"...", "type":"forum|github|saas|tg-channel|darknet"}"""
|
|
|
|
|
|
def known_urls() -> str:
|
|
urls = set()
|
|
for s in _load_json(BASE / "sources.json", []) + _load_json(BASE / "sources_extra.json", []):
|
|
try:
|
|
urls.add(re.sub(r"^https?://(www\.)?", "", s["url"]).split("/")[0])
|
|
except Exception:
|
|
continue
|
|
return ", ".join(sorted(urls)[:200])
|
|
|
|
|
|
def firecrawl_keys():
|
|
ks = ENVGET("FIRECRAWL_API_KEY") or ENVGET("FIRECRAWL_KEYS") or CREDS.get("firecrawl_keys") or ""
|
|
return [x.strip() for x in ks.split(",") if x.strip()]
|
|
|
|
|
|
def web_search(query: str) -> str:
|
|
for key in firecrawl_keys():
|
|
try:
|
|
r = requests.post(
|
|
"https://api.firecrawl.dev/v1/search",
|
|
json={"query": query, "limit": 10},
|
|
headers={"Authorization": "Bearer " + key},
|
|
timeout=30,
|
|
)
|
|
if r.status_code == 200:
|
|
data = r.json().get("data", [])
|
|
if isinstance(data, dict):
|
|
results = data.get("web", []) or data.get("results", [])
|
|
else:
|
|
results = data if isinstance(data, list) else []
|
|
return "\n".join(
|
|
f"- {res.get('title','')}: {res.get('url','')} - {res.get('description','')}"
|
|
for res in results if isinstance(res, dict)
|
|
)
|
|
if r.status_code in (401, 402, 429):
|
|
continue
|
|
return ""
|
|
except Exception as e:
|
|
print(f" search error: {e}")
|
|
return ""
|
|
|
|
|
|
def extract_sources(search_text: str) -> list:
|
|
headers = {"Content-Type": "application/json"}
|
|
if AI_KEY:
|
|
headers["Authorization"] = "Bearer " + AI_KEY
|
|
try:
|
|
r = requests.post(AI_URL, headers=headers, json={
|
|
"model": AI_MODEL,
|
|
"messages": [
|
|
{"role": "system", "content": DISCOVERY_PROMPT + "\n\nKNOWN SOURCES:\n" + known_urls()},
|
|
{"role": "user", "content": search_text[:6000]},
|
|
],
|
|
"max_tokens": 1500, "temperature": 0.1,
|
|
}, timeout=300)
|
|
if r.status_code == 200:
|
|
content = r.json()["choices"][0]["message"]["content"].strip()
|
|
if content.startswith("```"):
|
|
content = content.split("\n", 1)[1].rsplit("\n", 1)[0]
|
|
try:
|
|
return json.loads(content)
|
|
except json.JSONDecodeError:
|
|
m = re.search(r"\[.*\]", content, re.S)
|
|
if m:
|
|
try:
|
|
return json.loads(m.group(0))
|
|
except json.JSONDecodeError:
|
|
pass
|
|
except Exception as e:
|
|
print(f" AI error: {e}")
|
|
return []
|
|
|
|
|
|
def load_state():
|
|
return _load_json(STATE, {"found": [], "queries_done": {}})
|
|
|
|
|
|
def save_state(state):
|
|
STATE.write_text(json.dumps(state, ensure_ascii=False, indent=2), encoding="utf-8")
|
|
|
|
|
|
def main():
|
|
if not firecrawl_keys():
|
|
print("WARN: FIRECRAWL_API_KEY не задан — web search работать не будет.")
|
|
print(" задай ключ в env FIRECRAWL_API_KEY или в дашборде (firecrawl.dev)")
|
|
state = load_state()
|
|
print(f"DISCOVERY: {len(state['found'])} sources already found")
|
|
|
|
now = datetime.now(timezone.utc)
|
|
for q in SEARCH_QUERIES:
|
|
last = state["queries_done"].get(q, "")
|
|
if last and (now - datetime.fromisoformat(last)).total_seconds() < 86400:
|
|
print(f"SKIP (fresh): {q[:60]}")
|
|
continue
|
|
|
|
print(f"\nSEARCH: {q[:80]}")
|
|
text = web_search(q)
|
|
if not text:
|
|
state["queries_done"][q] = now.isoformat()
|
|
save_state(state)
|
|
continue
|
|
|
|
added = 0
|
|
for s in extract_sources(text):
|
|
if isinstance(s, dict) and s.get("url") and s["url"] not in {x["url"] for x in state["found"]}:
|
|
s["found_by"] = q
|
|
s["found_at"] = now.isoformat()
|
|
state["found"].append(s)
|
|
added += 1
|
|
print(f" + {s.get('name','?')}: {s['url']} [{s.get('type','?')}]")
|
|
|
|
state["queries_done"][q] = now.isoformat()
|
|
save_state(state)
|
|
print(f" +{added} new. Total: {len(state['found'])}")
|
|
time.sleep(2)
|
|
|
|
report = OUTPUT / f"discovery_{now.strftime('%Y%m%d_%H%M')}.json"
|
|
report.write_text(json.dumps(state, ensure_ascii=False, indent=2), encoding="utf-8")
|
|
print(f"\nDONE. {len(state['found'])} sources in {report}")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|