1"""Telegram error reporting for actors (the workspace's error bot).
2
3Differences from the old copy-pasted reporter (55 variants across 170 actors):
4 * The finished HTML message is capped *after* escaping. Telegram rejects >4096 characters, and
5 escaping can grow text (``<`` becomes ``<``); the traceback/input are shrunk until the whole
6 message fits, and cuts only ever happen in raw text so the HTML stays well formed.
7 * ``datetime.now(timezone.utc)``, HTML-escaped actor name, guarded ``error_report.html`` write.
8 * Needs no Apify SDK import, so it is importable/testable anywhere.
9
10Credentials come from the environment (set in ``.actor/actor.json`` ``environmentVariables``):
11``APIFY_ERROR_BOT_TOKEN`` and ``APIFY_ERROR_CHAT_ID``.
12
13 report_error_to_telegram(exc, actor_name="My Actor", actor_input=actor_input) # unexpected error
14 report_handled_failure("unsupported country", actor_input=actor_input) # known failure, once per run
15"""
16from __future__ import annotations
17
18import functools
19import html
20import json
21import logging
22import os
23import traceback
24from typing import Any
25
26from .clock import utc_now_iso
27
28_logger = logging.getLogger(__name__)
29
30TELEGRAM_LIMIT = 4096
31BUDGET = 3900
32_sent_keys: set[str] = set()
33_last_input: dict | None = None
34
35SDK_UNCAUGHT_EXIT_CODE = 91
36
37
38def _actor_name(explicit: str | None) -> str:
39 """Explicit name, else `.actor/actor.json` title/name, else the ACTOR_ID env var."""
40 if explicit:
41 return explicit
42 try:
43 with open(os.path.join(".actor", "actor.json"), encoding="utf-8") as f:
44 data = json.load(f)
45 return str(data.get("title") or data.get("name") or "Actor")
46 except Exception:
47 return os.environ.get("ACTOR_ID") or "Actor"
48
49
50def _sdk_version() -> str:
51 try:
52 from importlib.metadata import version
53
54 return version("apify")
55 except Exception:
56 return "unknown"
57
58
59def build_message(
60 exc: BaseException,
61 actor_name: str | None = None,
62 actor_input: dict | None = None,
63 tb: str | None = None,
64) -> str:
65 """Build the HTML message, guaranteed <= ``BUDGET`` characters."""
66 name = _actor_name(actor_name)
67 if tb is None:
68 tb = "".join(traceback.format_exception(type(exc), exc, exc.__traceback__)) or "(no traceback)"
69 input_raw = ""
70 if actor_input:
71 try:
72 input_raw = json.dumps(actor_input, indent=2, ensure_ascii=False, default=str)
73 except Exception:
74 input_raw = repr(actor_input)
75 esc = html.escape
76 head = (
77 f"<b>{esc(name)} failed with an unexpected error</b>\n"
78 f"<b>Time (UTC):</b> {esc(utc_now_iso())}\n"
79 f"<b>Exception:</b> {esc(type(exc).__name__)}: {esc(str(exc)[:500])}\n"
80 )
81 tail = (
82 f"\n<i>Environment:</i> ACTOR_ID={esc(os.environ.get('ACTOR_ID', ''))}, "
83 f"APIFY_IS_AT_HOME={esc(os.environ.get('APIFY_IS_AT_HOME', ''))}, "
84 f"Apify-SDK={esc(_sdk_version())}"
85 )
86
87 def assemble(tb_limit: int, in_limit: int) -> str:
88 body = f"<pre>{esc(tb[-tb_limit:])}</pre>" if tb_limit > 0 else ""
89 inp = f"\n<b>Input:</b>\n<pre>{esc(input_raw[:in_limit])}</pre>" if input_raw and in_limit > 0 else ""
90 return head + body + inp + tail
91
92 tb_limit, in_limit = 2200, 900
93 msg = assemble(tb_limit, in_limit)
94 while len(msg) > BUDGET and (tb_limit > 0 or in_limit > 0):
95 tb_limit = int(tb_limit * 0.75) if tb_limit > 100 else 0
96 if tb_limit <= 100:
97 in_limit = int(in_limit * 0.75) if in_limit > 100 else 0
98 msg = assemble(tb_limit, in_limit)
99 if len(msg) > BUDGET:
100 msg = msg[:BUDGET].rsplit("<", 1)[0] if msg.count("<") else msg[:BUDGET]
101 return msg
102
103
104def _post(msg: str, token: str | None = None, chat_id: str | None = None) -> dict | None:
105 """POST to the Telegram Bot API with the standard library (no extra dependency for actors).
106
107 ``token``/``chat_id`` default to the error bot; other bots (``free_plan``) pass their own.
108 Returns the parsed Telegram response, or None if not configured / not delivered.
109 """
110 token = token or os.getenv("APIFY_ERROR_BOT_TOKEN")
111 chat_id = chat_id or os.getenv("APIFY_ERROR_CHAT_ID")
112 if not token or not chat_id:
113 _logger.warning("Telegram error reporting not configured.")
114 return None
115 import urllib.error
116 import urllib.request
117
118 req = urllib.request.Request(
119 f"https://api.telegram.org/bot{token}/sendMessage",
120 data=json.dumps({"chat_id": chat_id, "text": msg, "parse_mode": "HTML"}).encode("utf-8"),
121 headers={"Content-Type": "application/json"},
122 )
123 try:
124 with urllib.request.urlopen(req, timeout=10) as r:
125 return json.load(r)
126 except urllib.error.HTTPError as e:
127 _logger.warning("Telegram send failed: %s %s", e.code, e.read()[:300])
128 return None
129
130
131def report_error_to_telegram(
132 exc: BaseException,
133 actor_name: str | None = None,
134 actor_input: dict | None = None,
135) -> bool:
136 """Report an unexpected error. Never raises. Returns True if Telegram accepted the message."""
137 delivered = False
138 try:
139 msg = build_message(exc, actor_name=actor_name, actor_input=actor_input)
140 try:
141 with open("error_report.html", "w", encoding="utf-8") as f:
142 f.write(msg)
143 except OSError:
144 pass
145 delivered = bool((_post(msg) or {}).get("ok"))
146 except Exception as e:
147 _logger.warning("Exception while reporting to Telegram: %s", e)
148 _logger.error("Reporting error to Telegram: %s", exc)
149 return delivered
150
151
152def report_handled_failure(
153 reason: str,
154 actor_name: str | None = None,
155 actor_input: dict | None = None,
156 key: str | None = None,
157) -> None:
158 """Short note for a *handled* failure (bad input, unsupported market, blocked) so its volume is visible.
159
160 Sent at most once per ``key`` (default: the reason) per run. Never raises.
161 """
162 try:
163 k = key or reason
164 if k in _sent_keys:
165 return
166 _sent_keys.add(k)
167 esc = html.escape
168 inp = ""
169 if actor_input:
170 try:
171 inp = "\n<pre>" + esc(json.dumps(actor_input, ensure_ascii=False, default=str)[:600]) + "</pre>"
172 except Exception:
173 inp = ""
174 msg = (
175 f"<b>{esc(_actor_name(actor_name))}</b> handled failure: {esc(reason[:500])}\n"
176 f"<i>{esc(utc_now_iso())}</i>{inp}"
177 )
178 _post(msg[:BUDGET])
179 except Exception as e:
180 _logger.warning("Exception while reporting handled failure: %s", e)
181
182
183def remember_input(actor_input: dict | None) -> None:
184 """Store the actor input so `guard` can attach it to an alert (the SDK has closed by then)."""
185 global _last_input
186 _last_input = actor_input
187
188
189def guard(actor_name: str | None = None):
190 """Decorator for an actor's ``main()``: report uncaught exceptions to Telegram, then re-raise.
191
192 Needed because an exception raised inside ``async with Actor:`` does NOT reach an outer
193 ``except Exception``: the SDK logs it and calls ``sys.exit(91)``. Python keeps the original on
194 ``SystemExit.__context__``, which is what gets reported. Only exit code 91 is handled, so actors that
195 already report in their own ``except`` and call ``Actor.fail`` (exit code 1) are not alerted twice.
196
197 @guard("Idealista Scraper")
198 async def main() -> None:
199 async with Actor:
200 remember_input(actor_input := await Actor.get_input() or {})
201 ...
202 """
203
204 def decorator(fn):
205 @functools.wraps(fn)
206 async def wrapper(*args, **kwargs):
207 try:
208 return await fn(*args, **kwargs)
209 except SystemExit as e:
210 cause = e.__context__
211 if e.code == SDK_UNCAUGHT_EXIT_CODE and isinstance(cause, Exception):
212 report_error_to_telegram(cause, actor_name=actor_name, actor_input=_last_input)
213 raise
214 except Exception as e:
215 report_error_to_telegram(e, actor_name=actor_name, actor_input=_last_input)
216 raise
217
218 return wrapper
219
220 return decorator