| 1 | """Telegram public channel posts via ScrapeCreators API for /last30days. |
| 2 | |
| 3 | Uses ScrapeCreators REST API to fetch recent posts from named public Telegram |
| 4 | channels. No keyword search - channel handles only. |
| 5 | |
| 6 | Requires SCRAPECREATORS_API_KEY in config plus a channel list (TELEGRAM_SOURCES |
| 7 | env var or --telegram-sources CLI flag). |
| 8 | |
| 9 | API docs: https://docs.scrapecreators.com/v1/telegram/channel/posts |
| 10 | """ |
| 11 | |
| 12 | import math |
| 13 | import os |
| 14 | import re |
| 15 | from typing import Any |
| 16 | |
| 17 | from . import auth_safety, dates, health, http, log |
| 18 | from .relevance import token_overlap_relevance as _compute_relevance |
| 19 | |
| 20 | SCRAPECREATORS_BASE = "https://api.scrapecreators.com/v1/telegram" |
| 21 | |
| 22 | |
| 23 | def _sc_base() -> str: |
| 24 | if SCRAPECREATORS_BASE != "https://api.scrapecreators.com/v1/telegram": |
| 25 | return SCRAPECREATORS_BASE |
| 26 | from . import env |
| 27 | return f"{env.get_scrapecreators_base_url()}/v1/telegram" |
| 28 | |
| 29 | DEPTH_PAGE_CAPS = { |
| 30 | "quick": 1, |
| 31 | "default": 3, |
| 32 | "deep": 6, |
| 33 | } |
| 34 | |
| 35 | |
| 36 | def _log(msg: str): |
| 37 | log.source_log("Telegram", msg, tty_only=False) |
| 38 | |
| 39 | |
| 40 | class InvalidChannelHandle(ValueError): |
| 41 | """Raised when a channel handle is rejected (joinchat, numeric -100 ID).""" |
| 42 | |
| 43 | |
| 44 | def parse_channel_handle(raw: str) -> str: |
| 45 | """Normalize a Telegram channel identifier to a bare handle. |
| 46 | |
| 47 | Accepts: |
| 48 | - bare username: aipost |
| 49 | - @handle: @aipost |
| 50 | - t.me URL: https://t.me/aipost |
| 51 | - t.me/s preview URL: https://t.me/s/aipost |
| 52 | |
| 53 | Rejects (raises InvalidChannelHandle): |
| 54 | - joinchat links: https://t.me/joinchat/xxxxx |
| 55 | - numeric -100 supergroup IDs: -1001234567890 |
| 56 | |
| 57 | Returns: |
| 58 | Bare handle string (no @ prefix). |
| 59 | """ |
| 60 | handle = raw.strip() |
| 61 | if not handle: |
| 62 | raise InvalidChannelHandle("Empty channel handle") |
| 63 | |
| 64 | if handle.lstrip("-").isdigit() and handle.startswith("-100"): |
| 65 | raise InvalidChannelHandle( |
| 66 | f"Numeric supergroup IDs are not supported: {handle}" |
| 67 | ) |
| 68 | |
| 69 | if handle.startswith("@"): |
| 70 | handle = handle[1:] |
| 71 | if not handle: |
| 72 | raise InvalidChannelHandle("Empty handle after @ prefix") |
| 73 | return handle |
| 74 | |
| 75 | url_match = re.match( |
| 76 | r"(?:https?://)?(?:www\.)?t\.me/(?:s/)?([^/?#]+)", |
| 77 | handle, |
| 78 | re.IGNORECASE, |
| 79 | ) |
| 80 | if url_match: |
| 81 | extracted = url_match.group(1) |
| 82 | if extracted.lower() == "joinchat": |
| 83 | raise InvalidChannelHandle( |
| 84 | f"Private joinchat links are not supported: {raw}" |
| 85 | ) |
| 86 | return extracted |
| 87 | |
| 88 | if "joinchat" in handle.lower(): |
| 89 | raise InvalidChannelHandle( |
| 90 | f"Private joinchat links are not supported: {raw}" |
| 91 | ) |
| 92 | |
| 93 | return handle |
| 94 | |
| 95 | |
| 96 | def parse_channel_sources(raw: str) -> list[str]: |
| 97 | """Parse a comma-separated list of channel handles. |
| 98 | |
| 99 | Filters out invalid handles (logs a warning) and returns valid ones. |
| 100 | """ |
| 101 | handles: list[str] = [] |
| 102 | for part in raw.split(","): |
| 103 | part = part.strip() |
| 104 | if not part: |
| 105 | continue |
| 106 | try: |
| 107 | handle = parse_channel_handle(part) |
| 108 | if handle.lower() not in {h.lower() for h in handles}: |
| 109 | handles.append(handle) |
| 110 | except InvalidChannelHandle as exc: |
| 111 | _log(f"Skipping invalid channel: {exc}") |
| 112 | return handles |
| 113 | |
| 114 | |
| 115 | def _get_channel_sources(config: dict[str, Any]) -> list[str]: |
| 116 | """Get configured Telegram channel sources from config or env.""" |
| 117 | raw = config.get("TELEGRAM_SOURCES") or os.environ.get("TELEGRAM_SOURCES") or "" |
| 118 | return parse_channel_sources(raw) |
| 119 | |
| 120 | |
| 121 | def is_telegram_configured(config: dict[str, Any]) -> bool: |
| 122 | """True when Telegram has both API key and at least one channel.""" |
| 123 | return bool( |
| 124 | config.get("SCRAPECREATORS_API_KEY") |
| 125 | and _get_channel_sources(config) |
| 126 | ) |
| 127 | |
| 128 | |
| 129 | def _parse_date(item: dict[str, Any]) -> str | None: |
| 130 | """Parse date from Telegram post to YYYY-MM-DD.""" |
| 131 | for key in ("published_at", "date", "created_at"): |
| 132 | val = item.get(key) |
| 133 | if val is None: |
| 134 | continue |
| 135 | dt = dates.parse_date(str(val)) |
| 136 | if dt: |
| 137 | return dt.strftime("%Y-%m-%d") |
| 138 | return None |
| 139 | |
| 140 | |
| 141 | def _parse_post( |
| 142 | raw: dict[str, Any], |
| 143 | channel: dict[str, Any], |
| 144 | topic: str, |
| 145 | index: int, |
| 146 | ) -> dict[str, Any]: |
| 147 | """Parse a single Telegram post into normalized dict.""" |
| 148 | post_id = str(raw.get("id") or f"TG{index + 1}") |
| 149 | text = str(raw.get("text") or "").strip() |
| 150 | url = str(raw.get("url") or "") |
| 151 | date_str = _parse_date(raw) |
| 152 | |
| 153 | handle = str(raw.get("channel_handle") or channel.get("handle") or "") |
| 154 | author_name = str(raw.get("author_name") or channel.get("name") or handle) |
| 155 | |
| 156 | view_count = raw.get("view_count") or 0 |
| 157 | reaction_count = raw.get("reaction_count") or 0 |
| 158 | subscriber_count = channel.get("subscriber_count") or 0 |
| 159 | |
| 160 | text_relevance = _compute_relevance(topic, text) |
| 161 | rank_score = max(0.3, 1.0 - (index * 0.02)) |
| 162 | engagement_boost = min(0.2, math.log1p(view_count + reaction_count * 10) / 50) |
| 163 | relevance = min(1.0, text_relevance * 0.5 + rank_score * 0.3 + engagement_boost + 0.1) |
| 164 | |
| 165 | return { |
| 166 | "id": post_id, |
| 167 | "handle": handle, |
| 168 | "display_name": author_name, |
| 169 | "text": text, |
| 170 | "url": url, |
| 171 | "date": date_str, |
| 172 | "engagement": { |
| 173 | "views": view_count, |
| 174 | "reactions": reaction_count, |
| 175 | "subscribers": subscriber_count, |
| 176 | }, |
| 177 | "relevance": round(relevance, 2), |
| 178 | "why_relevant": f"Telegram @{handle}: {text[:60]}" if text else f"Telegram: @{handle}", |
| 179 | } |
| 180 | |
| 181 | |
| 182 | def _error_severity(message: str, status_code: int | None = None) -> int: |
| 183 | state = http.classify_failure(status_code=status_code, message=message) |
| 184 | return health.FAILURE_SPECIFICITY.get( |
| 185 | state, health.FAILURE_SPECIFICITY[health.ERROR], |
| 186 | ) |
| 187 | |
| 188 | |
| 189 | def _select_primary_error(errors: list[tuple[int, str]]) -> str: |
| 190 | return min(errors, key=lambda item: item[0])[1] |
| 191 | |
| 192 | |
| 193 | def _fetch_channel_posts( |
| 194 | handle: str, |
| 195 | token: str, |
| 196 | *, |
| 197 | from_date: str, |
| 198 | topic: str, |
| 199 | max_pages: int, |
| 200 | errors_out: list[tuple[int, str]] | None = None, |
| 201 | ) -> list[dict[str, Any]]: |
| 202 | """Fetch posts from a single channel, paginating until date cutoff.""" |
| 203 | raw_token = token |
| 204 | clean_token, token_err = auth_safety.normalize_header_token(raw_token) |
| 205 | if token_err or not clean_token: |
| 206 | err_msg = token_err or "No SCRAPECREATORS_API_KEY configured" |
| 207 | _log(f"Skipping @{handle}: {err_msg}") |
| 208 | if errors_out is not None: |
| 209 | errors_out.append((_error_severity(err_msg), f"@{handle}: {err_msg}")) |
| 210 | return [] |
| 211 | |
| 212 | items: list[dict[str, Any]] = [] |
| 213 | cursor: str | None = None |
| 214 | pages_fetched = 0 |
| 215 | |
| 216 | while pages_fetched < max_pages: |
| 217 | _log(f"Fetching @{handle} (page {pages_fetched + 1}/{max_pages})") |
| 218 | |
| 219 | params: dict[str, Any] = {"handle": handle} |
| 220 | if cursor: |
| 221 | params["cursor"] = cursor |
| 222 | |
| 223 | try: |
| 224 | data = http.get( |
| 225 | f"{_sc_base()}/channel/posts", |
| 226 | params=params, |
| 227 | headers=http.scrapecreators_headers(clean_token), |
| 228 | timeout=30, |
| 229 | retries=2, |
| 230 | ) |
| 231 | except http.HTTPError as exc: |
| 232 | safe_err = auth_safety.scrub_secrets(str(exc), (raw_token, clean_token)) |
| 233 | if exc.status_code is not None and str(exc.status_code) not in safe_err: |
| 234 | safe_err = f"HTTP {exc.status_code}: {safe_err}" |
| 235 | _log(f"HTTP error fetching @{handle}: {safe_err}") |
| 236 | if errors_out is not None: |
| 237 | errors_out.append( |
| 238 | (_error_severity(safe_err, status_code=exc.status_code), f"@{handle}: {safe_err}") |
| 239 | ) |
| 240 | break |
| 241 | except Exception as exc: |
| 242 | safe_err = auth_safety.scrub_secrets(str(exc), (raw_token, clean_token)) |
| 243 | detail = f"{type(exc).__name__}: {safe_err}" |
| 244 | _log(f"Error fetching @{handle}: {detail}") |
| 245 | if errors_out is not None: |
| 246 | errors_out.append((_error_severity(detail), f"@{handle}: {detail}")) |
| 247 | break |
| 248 | |
| 249 | if not isinstance(data, dict) or not data.get("success"): |
| 250 | raw_msg = ( |
| 251 | data.get("error") or data.get("message") or "Unknown error" |
| 252 | if isinstance(data, dict) else "Unexpected response shape" |
| 253 | ) |
| 254 | safe_msg = auth_safety.scrub_secrets(str(raw_msg), (raw_token, clean_token)) |
| 255 | _log(f"API error for @{handle}: {safe_msg}") |
| 256 | if errors_out is not None: |
| 257 | errors_out.append((_error_severity(safe_msg), f"@{handle}: {safe_msg}")) |
| 258 | break |
| 259 | |
| 260 | channel = data.get("channel") or {} |
| 261 | posts = data.get("posts") or [] |
| 262 | |
| 263 | if not posts: |
| 264 | _log(f"No posts returned for @{handle}") |
| 265 | break |
| 266 | |
| 267 | page_all_old = True |
| 268 | for idx, raw_post in enumerate(posts): |
| 269 | parsed = _parse_post(raw_post, channel, topic, len(items) + idx) |
| 270 | items.append(parsed) |
| 271 | if parsed["date"] and parsed["date"] >= from_date: |
| 272 | page_all_old = False |
| 273 | |
| 274 | pages_fetched += 1 |
| 275 | |
| 276 | if page_all_old: |
| 277 | _log(f"All posts on page older than {from_date}, stopping pagination") |
| 278 | break |
| 279 | |
| 280 | cursor = data.get("cursor") |
| 281 | if not data.get("has_more") or not cursor: |
| 282 | break |
| 283 | |
| 284 | return items |
| 285 | |
| 286 | |
| 287 | def search_telegram( |
| 288 | topic: str, |
| 289 | from_date: str, |
| 290 | to_date: str, |
| 291 | depth: str = "default", |
| 292 | token: str | None = None, |
| 293 | config: dict[str, Any] | None = None, |
| 294 | ) -> dict[str, Any]: |
| 295 | """Fetch recent posts from configured Telegram channels. |
| 296 | |
| 297 | Args: |
| 298 | topic: Search topic (for relevance scoring) |
| 299 | from_date: Start date (YYYY-MM-DD) |
| 300 | to_date: End date (YYYY-MM-DD) |
| 301 | depth: 'quick', 'default', or 'deep' |
| 302 | token: ScrapeCreators API key |
| 303 | config: Config dict (for TELEGRAM_SOURCES) |
| 304 | |
| 305 | Returns: |
| 306 | Dict with 'items' list and optional 'error'. |
| 307 | """ |
| 308 | config = config or {} |
| 309 | |
| 310 | raw_token = token |
| 311 | clean_token, token_err = auth_safety.normalize_header_token(raw_token) |
| 312 | if token_err: |
| 313 | _log(f"ScrapeCreators error: {token_err}") |
| 314 | return {"items": [], "error": token_err} |
| 315 | if not clean_token: |
| 316 | return {"items": [], "error": "No SCRAPECREATORS_API_KEY configured"} |
| 317 | |
| 318 | channels = _get_channel_sources(config) |
| 319 | if not channels: |
| 320 | return {"items": [], "error": "No TELEGRAM_SOURCES configured (channel list required)"} |
| 321 | |
| 322 | base_cap = DEPTH_PAGE_CAPS.get(depth, DEPTH_PAGE_CAPS["default"]) |
| 323 | override = config.get("TELEGRAM_MAX_PAGES") |
| 324 | if override: |
| 325 | try: |
| 326 | max_pages = max(base_cap, int(override)) |
| 327 | except (ValueError, TypeError): |
| 328 | max_pages = base_cap |
| 329 | else: |
| 330 | max_pages = base_cap |
| 331 | |
| 332 | _log(f"Searching {len(channels)} channel(s) for '{topic}' (depth={depth}, max_pages={max_pages})") |
| 333 | |
| 334 | all_items: list[dict[str, Any]] = [] |
| 335 | errors: list[tuple[int, str]] = [] |
| 336 | for handle in channels: |
| 337 | channel_items = _fetch_channel_posts( |
| 338 | handle, |
| 339 | clean_token, |
| 340 | from_date=from_date, |
| 341 | topic=topic, |
| 342 | max_pages=max_pages, |
| 343 | errors_out=errors, |
| 344 | ) |
| 345 | all_items.extend(channel_items) |
| 346 | |
| 347 | in_range = [ |
| 348 | item for item in all_items |
| 349 | if item["date"] and from_date <= item["date"] <= to_date |
| 350 | ] |
| 351 | out_of_range = len(all_items) - len(in_range) |
| 352 | if in_range: |
| 353 | items = in_range |
| 354 | if out_of_range: |
| 355 | _log(f"Filtered {out_of_range} posts outside date range") |
| 356 | else: |
| 357 | items = all_items |
| 358 | _log(f"No posts within date range, keeping all {len(items)}") |
| 359 | |
| 360 | items.sort(key=lambda x: x.get("relevance", 0), reverse=True) |
| 361 | |
| 362 | primary_error = _select_primary_error(errors) if errors else None |
| 363 | if not items and primary_error: |
| 364 | return {"items": [], "error": primary_error} |
| 365 | |
| 366 | result: dict[str, Any] = {"items": items} |
| 367 | if primary_error: |
| 368 | result["partial"] = True |
| 369 | result["error"] = primary_error |
| 370 | _log(f"PARTIAL — {len(errors)} channel failure(s); primary: {primary_error}") |
| 371 | |
| 372 | _log(f"Found {len(items)} Telegram posts") |
| 373 | return result |
| 374 | |
| 375 | |
| 376 | def parse_telegram_response(response: dict[str, Any]) -> list[dict[str, Any]]: |
| 377 | """Parse Telegram search response to normalized format. |
| 378 | |
| 379 | Returns: |
| 380 | List of item dicts ready for normalization. |
| 381 | """ |
| 382 | return response.get("items", []) |
| 383 |