forked from riffi/hermes-max-plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathadapter.py
More file actions
1889 lines (1661 loc) · 76.5 KB
/
Copy pathadapter.py
File metadata and controls
1889 lines (1661 loc) · 76.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
Max Messenger platform adapter for Hermes Gateway.
Uses Webhook (POST /subscriptions) or long-polling (GET /updates) for
receiving messages and REST API (POST /messages) for sending.
API docs: https://dev.max.ru/docs-api
Base URL: https://platform-api2.max.ru (platform-api.max.ru retired 2026-07-19;
the old host still answers as of this patch but is not guaranteed to stay up)
"""
import asyncio
import hashlib
import hmac
import json
import logging
import os
import re
import ssl
import time
from pathlib import Path
from typing import Any, Dict, Optional
import aiohttp
from aiohttp import web
from gateway.platforms.base import (
BasePlatformAdapter,
MessageEvent,
MessageType,
SendResult,
)
from gateway.config import Platform, PlatformConfig
from hermes_constants import get_hermes_home
logger = logging.getLogger(__name__)
# 2026-07-19: MAX moved its Bot API to platform-api2.max.ru, whose cert
# chains to the Russian Ministry of Digital Development's own root ("Russian
# Trusted Root CA") — not present in the standard system/Mozilla CA bundle.
# _max_ssl_context() below extends (not replaces) the default trust store
# with that root so both the new and the still-answering old host keep
# working through the transition, instead of failing TLS verification.
DEFAULT_MAX_API_BASE_URL = "https://platform-api2.max.ru"
_PLUGIN_DIR = Path(__file__).resolve().parent
_RUSSIAN_CA_BUNDLE_FILES = (
_PLUGIN_DIR / "ca" / "russian_trusted_sub_ca.pem",
_PLUGIN_DIR / "ca" / "russian_trusted_root_ca.pem",
)
_ssl_context_cache: Optional[ssl.SSLContext] = None
def _max_ssl_context() -> ssl.SSLContext:
"""Build (and cache) an SSL context trusting system CAs plus MAX's
Mintsifry-issued chain, so platform-api2.max.ru verifies cleanly without
disabling verification for anything else this adapter talks to."""
global _ssl_context_cache
if _ssl_context_cache is not None:
return _ssl_context_cache
ctx = ssl.create_default_context()
loaded_extra = False
for ca_path in _RUSSIAN_CA_BUNDLE_FILES:
if not ca_path.exists():
continue
try:
ctx.load_verify_locations(cafile=str(ca_path))
loaded_extra = True
except ssl.SSLError as exc:
logger.warning("Max: failed to load CA bundle %s: %s", ca_path, exc)
if not loaded_extra:
logger.warning(
"Max: Russian Trusted Root CA not found under %s — "
"platform-api2.max.ru TLS verification will fail. Expected files: %s",
_PLUGIN_DIR / "ca",
", ".join(p.name for p in _RUSSIAN_CA_BUNDLE_FILES),
)
_ssl_context_cache = ctx
return ctx
def _max_poll_state_path() -> Path:
"""Disk location for the long-poll marker (survives gateway restarts)."""
return get_hermes_home() / "plugins" / "max" / "state" / "poll_state.json"
def _load_persisted_marker() -> int:
path = _max_poll_state_path()
try:
data = json.loads(path.read_text(encoding="utf-8"))
marker = int(data.get("marker", 0))
if marker > 0:
logger.info("Max: resuming long-poll from persisted marker=%s (%s)", marker, path)
return marker
except FileNotFoundError:
return 0
except Exception as exc:
logger.warning("Max: could not read persisted marker from %s (%s) — starting at 0", path, exc)
return 0
def _save_persisted_marker(marker: int) -> None:
path = _max_poll_state_path()
try:
path.parent.mkdir(parents=True, exist_ok=True)
tmp_path = path.with_suffix(".json.tmp")
tmp_path.write_text(json.dumps({"marker": marker}), encoding="utf-8")
tmp_path.replace(path)
except Exception as exc:
logger.warning("Max: failed to persist marker=%s to %s: %s", marker, path, exc)
DEFAULT_WEBHOOK_HOST = "0.0.0.0"
DEFAULT_WEBHOOK_PORT = 8650
DEFAULT_WEBHOOK_PATH = "/max/webhook"
DEFAULT_UPDATE_TYPES = ["message_created", "message_callback", "bot_started"]
MAX_WEBHOOK_MAX_BODY_BYTES = 2 * 1024 * 1024
# MAX documents POST /messages text as "up to 4000 characters". Keep a
# transport margin because the API has rejected boundary-sized markdown text.
MAX_MESSAGE_TEXT_LIMIT = 4000
MAX_MESSAGE_TEXT_CHUNK_SIZE = 3900
MAX_INLINE_KEYBOARD_COLUMNS = 1
MAX_CALLBACK_NOTIFICATION_LIMIT = 1024
MAX_ATTACHMENT_TYPES = {"image", "file", "voice", "video", "audio", "contact", "inline_keyboard", "clipboard", "location"}
MAX_NATIVE_COMMANDS = [
# Only "description" (the menu subtitle) is localized here — "name" is
# the literal slash-command trigger the gateway's command dispatcher
# matches against a fixed set of canonical English names
# (gateway/run.py). MAX would happily show a Russian trigger in the
# menu, but tapping it would send unrecognized text and the command
# would silently no-op, so "name" stays English.
{"name": "help", "description": "Показать доступные команды."},
{"name": "commands", "description": "Список всех слэш-команд."},
{"name": "status", "description": "Показать текущий статус."},
{"name": "whoami", "description": "Показать ваш ID отправителя."},
{"name": "model", "description": "Показать или задать модель."},
{"name": "reset", "description": "Сбросить текущую сессию."},
{"name": "new", "description": "Начать новую сессию."},
{"name": "think", "description": "Задать уровень размышления."},
{"name": "verbose", "description": "Переключить подробный режим."},
{"name": "reasoning", "description": "Переключить видимость рассуждений."},
{"name": "usage", "description": "Сводка использования/стоимости."},
{"name": "stop", "description": "Остановить текущий запуск."},
]
MAX_ATTACHMENT_MESSAGE_TYPES = {
"image": MessageType.PHOTO,
"photo": MessageType.PHOTO,
"voice": MessageType.VOICE,
"audio": MessageType.VOICE, # Max API does not distinguish voice from audio; treat all audio as voice for STT
"video": MessageType.VIDEO,
"file": MessageType.DOCUMENT,
"document": MessageType.DOCUMENT,
"location": MessageType.LOCATION,
}
MAX_ATTACHMENT_MEDIA_TYPES = {
"image": "image/jpeg",
"photo": "image/jpeg",
"voice": "audio/ogg",
"audio": "audio/mpeg",
"video": "video/mp4",
"file": "application/octet-stream",
"document": "application/octet-stream",
}
MAX_INBOUND_MEDIA_MAX_BYTES = 50 * 1024 * 1024
MAX_BUTTONS_COMMENT_RE = re.compile(
r"<!--\s*(?:max_buttons|max_inline_keyboard)\s*:\s*(?P<payload>.*?)\s*-->",
re.IGNORECASE | re.DOTALL,
)
MAX_BUTTONS_FENCE_RE = re.compile(
r"(?:^|\n)```(?:max_buttons|max_inline_keyboard)\s*\n(?P<payload>.*?)(?:\n```)",
re.IGNORECASE | re.DOTALL,
)
MAX_NUMBERED_OPTION_RE = re.compile(
r"^\s*(?:[1-9][\.)]|[1-9]\ufe0f?\u20e3)\s+(?P<text>\S.+?)\s*$"
)
def _redact_sensitive(value: Any) -> Any:
if isinstance(value, dict):
redacted: dict[Any, Any] = {}
for key, nested in value.items():
if str(key).lower() in {"token", "access_token", "authorization"}:
redacted[key] = "<redacted>"
else:
redacted[key] = _redact_sensitive(nested)
return redacted
if isinstance(value, list):
return [_redact_sensitive(item) for item in value]
return value
def _json_preview(value: Any, limit: int = 4000) -> str:
try:
text = json.dumps(_redact_sensitive(value), default=str, ensure_ascii=False)
except Exception:
text = str(value)
return text if len(text) <= limit else f"{text[:limit]}...<truncated>"
def _max_attachment_type(attachment: Any) -> str:
if not isinstance(attachment, dict):
return ""
return str(attachment.get("type") or attachment.get("attachment_type") or "").lower()
def _max_message_type(text: str, attachments: list[Any]) -> MessageType:
if not attachments:
return MessageType.TEXT
for attachment in attachments:
attachment_type = _max_attachment_type(attachment)
if attachment_type in MAX_ATTACHMENT_MESSAGE_TYPES:
return MAX_ATTACHMENT_MESSAGE_TYPES[attachment_type]
return MessageType.TEXT if text else MessageType.DOCUMENT
def _first_http_url(value: Any) -> Optional[str]:
if isinstance(value, str):
return value if value.startswith(("http://", "https://")) else None
if isinstance(value, dict):
for key in ("url", "file_url", "download_url", "link", "src", "href"):
found = _first_http_url(value.get(key))
if found:
return found
for nested in value.values():
found = _first_http_url(nested)
if found:
return found
if isinstance(value, list):
for item in value:
found = _first_http_url(item)
if found:
return found
return None
def _max_attachment_media(attachments: list[Any]) -> tuple[list[str], list[str]]:
media_urls: list[str] = []
media_types: list[str] = []
for attachment in attachments:
url = _first_http_url(attachment)
if not url:
continue
attachment_type = _max_attachment_type(attachment)
media_urls.append(url)
media_types.append(MAX_ATTACHMENT_MEDIA_TYPES.get(attachment_type, "application/octet-stream"))
return media_urls, media_types
def _max_attachment_summary(attachments: list[Any]) -> str:
if not attachments:
return ""
counts: dict[str, int] = {}
for attachment in attachments:
attachment_type = _max_attachment_type(attachment) or "unknown"
counts[attachment_type] = counts.get(attachment_type, 0) + 1
parts = [f"{count} {attachment_type}" for attachment_type, count in sorted(counts.items())]
return "[MAX attachment: " + ", ".join(parts) + "]"
def _max_attachments_from_candidate(candidate: Any) -> list[Any]:
if isinstance(candidate, list):
return candidate
if isinstance(candidate, dict):
if "type" in candidate or "payload" in candidate:
return [candidate]
for key in ("attachments", "attachment"):
value = candidate.get(key)
if isinstance(value, list):
return value
if isinstance(value, dict):
return [value]
return []
def _max_find_first_key(value: Any, names: set[str]) -> str:
if isinstance(value, dict):
for key, nested in value.items():
if str(key).lower() in names and nested not in (None, ""):
return str(nested)
for nested in value.values():
found = _max_find_first_key(nested, names)
if found:
return found
elif isinstance(value, list):
for nested in value:
found = _max_find_first_key(nested, names)
if found:
return found
return ""
def _max_callback_payload(update: dict, callback: Any) -> str:
if isinstance(callback, str):
return callback.strip()
if isinstance(callback, dict):
direct = callback.get("payload") or callback.get("callback_payload") or callback.get("data")
if direct:
return str(direct).strip()
found = _max_find_first_key(callback, {"payload", "callback_payload", "data"})
if found:
return found.strip()
return str(update.get("payload") or update.get("callback_payload") or update.get("data") or "").strip()
def _max_callback_id(update: dict, callback: Any) -> str:
if isinstance(callback, dict):
direct = callback.get("callback_id")
if direct:
return str(direct).strip()
found = _max_find_first_key(callback, {"callback_id"})
if found:
return found.strip()
return str(update.get("callback_id") or "").strip()
def _max_callback_text(update: dict, callback: Any) -> str:
if isinstance(callback, dict):
found = _max_find_first_key(callback, {"text", "title", "label"})
if found:
return found.strip()
return str(update.get("text") or update.get("title") or update.get("label") or "").strip()
def _max_message_text(message: Any) -> str:
if not isinstance(message, dict):
return ""
body = message.get("body")
if isinstance(body, dict):
text = body.get("text")
if text:
return str(text)
text = message.get("text")
return str(text) if text else ""
def _max_trim_callback_text(text: str, limit: int = MAX_CALLBACK_NOTIFICATION_LIMIT) -> str:
value = " ".join(str(text or "").split())
if len(value) <= limit:
return value
return value[: max(1, limit - 1)].rstrip() + "…"
def _max_extract_attachments(update: dict, message: dict, body: dict) -> tuple[list[Any], str]:
"""Extract inbound MAX message attachments from known compatible shapes."""
candidates = (
("message.body.attachments", body.get("attachments")),
("message.attachments", message.get("attachments")),
("update.attachments", update.get("attachments")),
("message.body.attachment", body.get("attachment")),
("message.attachment", message.get("attachment")),
("update.attachment", update.get("attachment")),
)
empty_source = ""
for source, candidate in candidates:
attachments = _max_attachments_from_candidate(candidate)
if attachments:
return attachments, source
if isinstance(candidate, list) and not empty_source:
empty_source = source
return [], empty_source or "none"
def _split_max_text(text: str, limit: int = MAX_MESSAGE_TEXT_CHUNK_SIZE) -> list[str]:
"""Split outbound text into MAX-sized chunks without silently truncating."""
text = str(text or "")
if not text:
return []
if limit <= 0:
return [text]
chunks: list[str] = []
remaining = text
while len(remaining) > limit:
window = remaining[:limit]
split_at = -1
for separator in ("\n\n", "\n", " "):
pos = window.rfind(separator)
if pos > 0:
split_at = pos + len(separator)
break
if split_at <= 0:
split_at = limit
chunk = remaining[:split_at]
if not chunk:
chunk = remaining[:limit]
split_at = limit
chunks.append(chunk)
remaining = remaining[split_at:]
if remaining:
chunks.append(remaining)
return chunks
def _max_button(value: Any) -> Optional[dict[str, Any]]:
"""Normalize a compact button description into a MAX Button object."""
if not isinstance(value, dict):
return None
text = str(value.get("text") or value.get("label") or "").strip()
if not text:
return None
button_type = str(value.get("type") or "").strip().lower()
clipboard_payload = value.get("clipboard") or value.get("copy") or value.get("copy_text") or value.get("clipboard_text")
if button_type == "clipboard":
payload = str(value.get("payload") or clipboard_payload or "")
if not payload:
return None
button = dict(value)
button["type"] = "clipboard"
button["text"] = text
button["payload"] = payload
for alias in ("clipboard", "copy", "copy_text", "clipboard_text"):
button.pop(alias, None)
return button
if clipboard_payload is not None:
payload = str(clipboard_payload)
if payload:
return {"type": "clipboard", "text": text, "payload": payload}
if button_type in {"callback", "link", "message", "open_app"}:
button = dict(value)
button["type"] = button_type
button["text"] = text
return button
if "payload" in value or "callback_data" in value or "data" in value:
payload = str(value.get("payload") or value.get("callback_data") or value.get("data") or "")
if payload:
return {"type": "callback", "text": text, "payload": payload}
if "url" in value:
url = str(value.get("url") or "").strip()
if url:
return {"type": "link", "text": text, "url": url}
return None
def _max_inline_keyboard_attachment(buttons: Any) -> Optional[dict[str, Any]]:
"""Build an inline_keyboard attachment from row/button metadata."""
if not isinstance(buttons, list):
return None
rows: list[list[dict[str, Any]]] = []
for row in buttons:
candidates = row if isinstance(row, list) else [row]
normalized_row = [button for item in candidates if (button := _max_button(item))]
for index in range(0, len(normalized_row), MAX_INLINE_KEYBOARD_COLUMNS):
chunk = normalized_row[index : index + MAX_INLINE_KEYBOARD_COLUMNS]
if chunk:
rows.append(chunk)
if not rows:
return None
return {"type": "inline_keyboard", "payload": {"buttons": rows}}
def _max_metadata_attachments(metadata: Any) -> list[dict[str, Any]]:
"""Extract MAX attachments from send metadata.
Supported shapes:
- {"max_inline_keyboard": [[{"text": "Open", "url": "https://..."}]]}
- {"max_inline_keyboard": [[{"text": "Pick", "payload": "resume:<id>"}]]}
- {"max_attachments": [{"type": "inline_keyboard", "payload": {...}}]}
"""
if not isinstance(metadata, dict):
return []
attachments: list[dict[str, Any]] = []
raw_attachments = metadata.get("max_attachments") or metadata.get("attachments")
if isinstance(raw_attachments, list):
attachments.extend(item for item in raw_attachments if isinstance(item, dict) and item.get("type"))
keyboard = (
metadata.get("max_inline_keyboard")
or metadata.get("inline_keyboard")
or metadata.get("max_buttons")
or metadata.get("buttons")
)
keyboard_attachment = _max_inline_keyboard_attachment(keyboard)
if keyboard_attachment:
attachments.append(keyboard_attachment)
return attachments
def _max_buttons_from_directive_payload(payload: str) -> Optional[dict[str, Any]]:
"""Parse a plugin-local inline keyboard directive into a MAX attachment."""
try:
value = json.loads(payload)
except Exception as exc:
logger.warning("Max: ignored invalid inline keyboard directive: %s", exc)
return None
if isinstance(value, dict):
if value.get("type") == "inline_keyboard":
attachments = _max_attachments_from_candidate(value)
for attachment in attachments:
if _max_attachment_type(attachment) == "inline_keyboard":
return attachment
return None
value = value.get("buttons") or value.get("max_buttons") or value.get("inline_keyboard")
return _max_inline_keyboard_attachment(value)
def _max_extract_inline_keyboard_directives(text: str) -> tuple[str, list[dict[str, Any]]]:
"""Remove MAX inline keyboard directives from text and return attachments.
This is intentionally plugin-local: Hermes core only sends plain text plus
routing metadata, so the MAX adapter owns the MAX-specific UI hint.
"""
lowered = text.lower()
if "max_buttons" not in lowered and "max_inline_keyboard" not in lowered:
return text, []
attachments: list[dict[str, Any]] = []
def replace(match: re.Match) -> str:
attachment = _max_buttons_from_directive_payload(match.group("payload").strip())
if attachment:
attachments.append(attachment)
return ""
text = MAX_BUTTONS_COMMENT_RE.sub(replace, text)
text = MAX_BUTTONS_FENCE_RE.sub(replace, text)
text = re.sub(
r"<!--\s*(?:max_buttons|max_inline_keyboard)\s*:.*$",
"",
text,
flags=re.IGNORECASE | re.DOTALL,
)
text = re.sub(
r"(?:^|\n)```(?:max_buttons|max_inline_keyboard)\s*\n.*$",
"",
text,
flags=re.IGNORECASE | re.DOTALL,
)
text = re.sub(r"\n{3,}", "\n\n", text).strip()
return text, attachments
def _max_auto_keyboard_from_numbered_options(text: str) -> Optional[dict[str, Any]]:
"""Infer buttons from a trailing numbered choice list when max_buttons is omitted."""
lines = str(text or "").splitlines()
options: list[str] = []
for line in reversed(lines):
if not line.strip():
if options:
break
continue
match = MAX_NUMBERED_OPTION_RE.match(line)
if not match:
break
options.append(" ".join(match.group("text").split()))
options.reverse()
if len(options) < 2 or len(options) > 6:
return None
buttons = [
[{"type": "callback", "text": option, "payload": option}]
for option in options
]
return _max_inline_keyboard_attachment(buttons)
class MaxAdapter(BasePlatformAdapter):
"""MAX Messenger adapter supporting webhook and long-polling transports."""
def __init__(self, config: PlatformConfig):
super().__init__(config, Platform("max"))
extra = config.extra or {}
# 1. env var → 2. config token → 3. extra.token
self.token = os.getenv("MAX_BOT_TOKEN") or getattr(config, "token", None) or extra.get("token", "")
self._session: Optional[aiohttp.ClientSession] = None
self._poll_task: Optional[asyncio.Task] = None
self._last_event_id: int = extra.get("last_event_id", 0)
self._running = False
self._known_message_events: set = set() # Dedup by message id + event payload
self._last_chat_action_at: Dict[tuple[str, str], float] = {}
self._clarify_state: dict[str, str] = {}
self._api_base_url = str(
os.getenv("MAX_API_BASE_URL")
or extra.get("api_base_url")
or extra.get("base_url")
or DEFAULT_MAX_API_BASE_URL
).rstrip("/")
self._bot_user_id = ""
configured_transport = (
os.getenv("MAX_TRANSPORT")
or os.getenv("MAX_MODE")
or extra.get("transport")
or extra.get("mode")
or ""
)
self._webhook_url = str(
os.getenv("MAX_WEBHOOK_URL") or extra.get("webhook_url") or ""
).strip()
self._transport = str(configured_transport or ("webhook" if self._webhook_url else "polling")).strip().lower()
self._webhook_secret = str(
os.getenv("MAX_WEBHOOK_SECRET") or extra.get("webhook_secret") or extra.get("secret") or ""
).strip()
self._webhook_host = str(
os.getenv("MAX_WEBHOOK_HOST") or extra.get("webhook_host") or DEFAULT_WEBHOOK_HOST
).strip()
self._webhook_port = int(
os.getenv("MAX_WEBHOOK_PORT") or extra.get("webhook_port") or DEFAULT_WEBHOOK_PORT
)
self._webhook_path = self._normalize_path(
os.getenv("MAX_WEBHOOK_PATH") or extra.get("webhook_path") or DEFAULT_WEBHOOK_PATH
)
self._webhook_update_types = self._parse_update_types(
os.getenv("MAX_UPDATE_TYPES") or extra.get("update_types") or DEFAULT_UPDATE_TYPES
)
self._webhook_runner: Optional[web.AppRunner] = None
self._webhook_tasks: set[asyncio.Task] = set()
@staticmethod
def _normalize_path(value: Any) -> str:
path = str(value or DEFAULT_WEBHOOK_PATH).strip() or DEFAULT_WEBHOOK_PATH
return path if path.startswith("/") else f"/{path}"
@staticmethod
def _parse_update_types(value: Any) -> list[str]:
if isinstance(value, str):
items = [item.strip() for item in value.split(",")]
elif isinstance(value, (list, tuple, set)):
items = [str(item).strip() for item in value]
else:
items = []
return [item for item in items if item] or list(DEFAULT_UPDATE_TYPES)
# ── connection ──────────────────────────────────────────────
async def connect(self, *, is_reconnect: bool = False) -> bool:
if not self.token:
logger.error("Max: MAX_BOT_TOKEN not set")
return False
self._session = aiohttp.ClientSession(
headers={
"Authorization": self.token,
},
timeout=aiohttp.ClientTimeout(total=120),
connector=aiohttp.TCPConnector(ssl=_max_ssl_context()),
)
# Verify token without consuming updates. MAX requires Authorization header.
try:
async with self._session.get(
f"{self._api_base_url}/me", timeout=aiohttp.ClientTimeout(total=15)
) as resp:
if resp.status != 200:
logger.error(f"Max: /me returned {resp.status}")
await self._session.close()
self._session = None
return False
data = await resp.json()
self._bot_user_id = str(data.get("user_id") or "")
logger.info("Max: connected OK as %s", data.get("username") or data.get("name") or data.get("user_id") or "?")
except Exception as e:
logger.error(f"Max: token check failed: {e}")
await self._session.close()
self._session = None
return False
await self._register_native_commands()
self._running = True
if self._transport == "webhook":
if not self._webhook_url:
logger.error("Max: webhook transport requires MAX_WEBHOOK_URL")
await self.disconnect()
return False
if not self._webhook_url.startswith("https://"):
logger.error("Max: MAX_WEBHOOK_URL must start with https://")
await self.disconnect()
return False
await self._start_webhook_server()
if not await self._subscribe_webhook():
await self.disconnect()
return False
else:
self._poll_task = asyncio.create_task(self._poll_loop())
self._mark_connected()
return True
async def disconnect(self) -> None:
self._running = False
if self._poll_task:
self._poll_task.cancel()
try:
await self._poll_task
except asyncio.CancelledError:
pass
self._poll_task = None
for task in list(self._webhook_tasks):
task.cancel()
if self._webhook_tasks:
await asyncio.gather(*self._webhook_tasks, return_exceptions=True)
self._webhook_tasks.clear()
if self._webhook_runner:
try:
await self._webhook_runner.cleanup()
except Exception:
logger.exception("Max webhook server cleanup failed")
self._webhook_runner = None
if self._session:
await self._session.close()
self._session = None
self._mark_disconnected()
async def _start_webhook_server(self) -> None:
app = web.Application(client_max_size=MAX_WEBHOOK_MAX_BODY_BYTES)
app.router.add_get(self._webhook_path, self._handle_webhook_health)
app.router.add_post(self._webhook_path, self._handle_webhook_request)
self._webhook_runner = web.AppRunner(app)
await self._webhook_runner.setup()
site = web.TCPSite(self._webhook_runner, self._webhook_host, self._webhook_port)
await site.start()
logger.info(
"Max webhook listening on %s:%d%s for %s",
self._webhook_host,
self._webhook_port,
self._webhook_path,
self._webhook_url,
)
if not self._webhook_secret:
logger.warning("Max webhook secret is not set; MAX recommends X-Max-Bot-Api-Secret validation")
async def _subscribe_webhook(self) -> bool:
body: dict[str, Any] = {
"url": self._webhook_url,
"update_types": self._webhook_update_types,
}
if self._webhook_secret:
body["secret"] = self._webhook_secret
result = await self._api_post("/subscriptions", json_body=body)
if result.get("success") is True:
logger.info("Max webhook subscribed: url=%s types=%s", self._webhook_url, self._webhook_update_types)
return True
if result:
logger.error("Max webhook subscription failed: %s", _json_preview(result))
return False
async def _handle_webhook_health(self, request: "web.Request") -> "web.Response":
return web.json_response({"status": "ok", "platform": "max"})
async def _handle_webhook_request(self, request: "web.Request") -> "web.Response":
if self._webhook_secret:
provided = request.headers.get("X-Max-Bot-Api-Secret", "")
if not hmac.compare_digest(provided, self._webhook_secret):
logger.warning("Max webhook rejected: invalid X-Max-Bot-Api-Secret")
return web.Response(status=401)
try:
raw = await request.read()
except Exception:
return web.Response(status=400)
if len(raw) > MAX_WEBHOOK_MAX_BODY_BYTES:
return web.Response(status=413)
try:
payload = json.loads(raw)
except Exception:
logger.warning("Max webhook rejected: invalid JSON body")
return web.Response(status=400)
if not isinstance(payload, dict):
return web.Response(status=400)
task = asyncio.create_task(self._dispatch_webhook_payload(payload))
self._webhook_tasks.add(task)
task.add_done_callback(self._webhook_tasks.discard)
return web.Response(status=200)
async def _dispatch_webhook_payload(self, payload: dict) -> None:
try:
updates = payload.get("updates")
if isinstance(updates, list):
for update in updates:
if isinstance(update, dict):
await self._handle_update(update)
return
await self._handle_update(payload)
except asyncio.CancelledError:
raise
except Exception:
logger.exception("Max webhook dispatch failed: %s", _json_preview(payload, limit=1200))
# ── message sending ─────────────────────────────────────────
async def _api_post(self, path: str, params: dict = None, json_body: dict = None) -> dict:
"""Helper: POST to Max API, return parsed JSON or {}."""
if not self._session:
return {}
try:
async with self._session.post(f"{self._api_base_url}{path}", params=params, json=json_body) as resp:
if resp.status == 200:
text = await resp.text()
if text.strip():
return json.loads(text)
else:
body = await resp.text()
logger.warning(f"Max API POST {path} → {resp.status}: {body[:300]}")
except Exception as e:
logger.warning(f"Max API POST {path} error: {e}")
return {}
async def _api_post_message(self, params: dict, body: Dict[str, Any]) -> dict:
"""POST /messages and retry as plain text if MAX rejects markdown."""
if not self._session:
return {}
try:
async with self._session.post(
f"{self._api_base_url}/messages", params=params, json=body
) as resp:
text = await resp.text()
if resp.status == 200:
return json.loads(text) if text.strip() else {}
logger.warning(f"Max API POST /messages → {resp.status}: {text[:300]}")
if resp.status not in (400, 422) or body.get("format") != "markdown":
return {}
except Exception as e:
logger.warning(f"Max API POST /messages error: {e}")
return {}
fallback = dict(body)
fallback.pop("format", None)
logger.info("Max: retrying message without markdown formatting")
return await self._api_post("/messages", params=params, json_body=fallback)
async def _answer_callback(
self,
callback_id: str,
*,
notification: str = "",
message: Optional[dict[str, Any]] = None,
) -> bool:
if not callback_id:
return False
body: dict[str, Any] = {}
if notification:
body["notification"] = _max_trim_callback_text(notification)
if message is not None:
body["message"] = message
if not body:
return False
result = await self._api_post(
"/answers",
params={"callback_id": callback_id},
json_body=body,
)
return bool(result)
async def _ack_callback_selection(
self,
callback_id: str,
message: dict[str, Any],
selected_text: str,
) -> None:
if not callback_id:
logger.warning("Max callback ack skipped: missing callback_id")
return
selected = _max_trim_callback_text(selected_text, limit=180)
original_text = _max_message_text(message).strip()
if original_text:
updated_text = f"{original_text}\n\nВы выбрали: {selected}"
else:
updated_text = f"Вы выбрали: {selected}"
answer_message: dict[str, Any] = {
"text": updated_text,
"attachments": [],
}
ok = await self._answer_callback(
callback_id,
notification=f"Выбрано: {selected}",
message=answer_message,
)
if not ok:
logger.warning("Max callback ack failed (callback_id=%s)", callback_id)
async def _api_patch(self, path: str, json_body: dict = None) -> dict:
"""Helper: PATCH to Max API, return parsed JSON or {}."""
if not self._session:
return {}
try:
async with self._session.patch(f"{self._api_base_url}{path}", json=json_body) as resp:
text = await resp.text()
if resp.status == 200:
return json.loads(text) if text.strip() else {}
logger.warning(f"Max API PATCH {path} → {resp.status}: {text[:300]}")
except Exception as e:
logger.warning(f"Max API PATCH {path} error: {e}")
return {}
async def _register_native_commands(self) -> None:
"""Register MAX native command menu entries.
Was ``PATCH /me`` with an embedded ``commands`` field — that 404s
with ``method.not.found`` on platform-api2.max.ru. Current MAX docs
(dev.max.ru/docs-api/methods/PATCH/me/commands) split this into its
own endpoint; the request/response body shape
(``{"commands": [{"name", "description"}, ...]}``, max 32) is
unchanged, only the path moved.
"""
result = await self._api_patch("/me/commands", {"commands": MAX_NATIVE_COMMANDS})
if result:
logger.info("Max: native commands registered (%s)", len(MAX_NATIVE_COMMANDS))
else:
logger.warning("Max: native command registration failed (non-fatal, bot still works)")
async def _send_text_message(
self,
chat_id,
text: str,
*,
reply_to=None,
attachments: Optional[list[dict[str, Any]]] = None,
) -> SendResult:
body: Dict[str, Any] = {"text": text, "format": "markdown"}
if reply_to:
body["reply_to"] = reply_to
if attachments:
body["attachments"] = attachments
for attachment in attachments:
if _max_attachment_type(attachment) != "inline_keyboard":
continue
buttons = (attachment.get("payload") or {}).get("buttons")
if isinstance(buttons, list):
logger.info(
"Max: sending inline keyboard rows=%s preview=%s",
[
len(row) if isinstance(row, list) else 1
for row in buttons
],
_json_preview(buttons, limit=500),
)
result = await self._api_post_message({"chat_id": chat_id}, body)
if result:
msg_id = str(result.get("message_id") or result.get("message", {}).get("body", {}).get("mid", ""))
return SendResult(success=True, message_id=msg_id)
return SendResult(success=False, error="API returned empty response")
async def send(self, chat_id, content, reply_to=None, metadata=None) -> SendResult:
if not self._session:
return SendResult(success=False, error="No HTTP session (disconnected)")
if not content:
return SendResult(success=False, error="Empty content")
content, directive_attachments = _max_extract_inline_keyboard_directives(str(content))
attachments = _max_metadata_attachments(metadata)
attachments.extend(directive_attachments)
if not attachments:
auto_keyboard = _max_auto_keyboard_from_numbered_options(content)
if auto_keyboard:
logger.info("Max: inferred inline keyboard from trailing numbered options")
attachments.append(auto_keyboard)
if not content:
return SendResult(success=False, error="Empty content")
chunks = _split_max_text(str(content))
if len(chunks) > 1:
logger.info(
"Max: splitting outbound text into %d chunks (chars=%d, chunk_limit=%d)",
len(chunks),
len(str(content)),
MAX_MESSAGE_TEXT_CHUNK_SIZE,
)
message_ids: list[str] = []
for index, chunk in enumerate(chunks):
result = await self._send_text_message(
chat_id,
chunk,
reply_to=reply_to if index == 0 else None,
attachments=attachments if index == 0 else None,
)
if not result.success:
return SendResult(
success=False,
error=f"Max text chunk {index + 1}/{len(chunks)} failed: {result.error}",
message_id=message_ids[-1] if message_ids else "",
continuation_message_ids=tuple(message_ids[:-1]),
)
message_ids.append(result.message_id or "")
return SendResult(