5 Commits
Author SHA1 Message Date
kislovdm 1ef5cf4e38 ИСправление списка каналов
Docker Hub / build-and-push (push) Failing after 14s
2026-04-15 14:30:45 +03:00
kislovdm 1fd5e4ea39 после миграции группы в супергруппу необходимо обновить её id
Docker Hub / build-and-push (push) Failing after 14s
2026-04-14 11:13:21 +03:00
kislovdm bcf9366cf6 remove sha builds 2026-04-11 11:00:32 +03:00
kislovdm 102009369a clear caches in image 2026-04-11 10:58:08 +03:00
kislovdm 7a3c7317ea fix actions 2026-04-11 10:55:07 +03:00
5 changed files with 163 additions and 28 deletions
+6 -3
View File
@@ -6,6 +6,10 @@
#
# Опционально: Variables → DOCKERHUB_IMAGE (например org/max2telegram), если имя образа
# отличается от <DOCKERHUB_USERNAME>/max2telegram.
#
# Теги образа:
# push в master → dev (+ sha)
# push тега v* → {{version}}, {{major}}.{{minor}}, latest (+ sha)
name: Docker Hub
@@ -57,11 +61,10 @@ jobs:
with:
images: ${{ steps.image.outputs.name }}
tags: |
type=ref,event=branch
type=raw,value=dev,enable=${{ github.ref == 'refs/heads/master' }}
type=semver,pattern={{version}}
type=semver,pattern={{major}}.{{minor}}
type=sha,prefix=
type=raw,value=latest,enable={{is_default_branch}}
type=raw,value=latest,enable=${{ startsWith(github.ref, 'refs/tags/') }}
- name: Build and push
uses: docker/build-push-action@v6
+3 -1
View File
@@ -2,7 +2,9 @@ FROM python:3.12-slim
WORKDIR /app
RUN apt-get update; apt-get install -y git
RUN apt-get update \
&& apt-get install -y --no-install-recommends git \
&& rm -rf /var/lib/apt/lists/*
COPY ./src/requirements.txt .
RUN pip install --no-cache-dir -r ./requirements.txt
+69 -19
View File
@@ -1,4 +1,5 @@
import logging
from collections.abc import Awaitable, Callable
from typing import Any
from max_parser import parse_message
@@ -6,7 +7,7 @@ from models import ParsedMessage
from pymax import MaxClient
from pymax.types import PhotoAttach, VideoAttach
from storage import BridgeStorage
from telegram_api import TelegramClient
from telegram_api import TelegramApiError, TelegramClient
logger = logging.getLogger(__name__)
@@ -80,12 +81,17 @@ class MaxToTelegramBridge:
total_media = len(parsed.image_urls) + len(parsed.video_urls)
if total_media > 1:
# Отправляем одним альбомом в Telegram (единое сообщение).
sent_messages = await self._telegram.send_media_group(
chat_id=target_chat_id,
image_urls=parsed.image_urls,
video_urls=parsed.video_urls,
caption=text,
reply_to_message_id=reply_telegram_mid,
target_chat_id, sent_messages = await self._send_with_migration_retry(
target_chat_id=target_chat_id,
max_chat_title_norm=normalized,
max_chat_title=parsed.chat_name,
send_action=lambda chat_id: self._telegram.send_media_group(
chat_id=chat_id,
image_urls=parsed.image_urls,
video_urls=parsed.video_urls,
caption=text,
reply_to_message_id=reply_telegram_mid,
),
)
for sent in sent_messages:
mid = sent.get("message_id")
@@ -109,8 +115,13 @@ class MaxToTelegramBridge:
sent_any = False
if parsed.text.strip() and total_media == 0:
sent = await self._telegram.send_text(
target_chat_id, text, reply_to_message_id=reply_telegram_mid
target_chat_id, sent = await self._send_with_migration_retry(
target_chat_id=target_chat_id,
max_chat_title_norm=normalized,
max_chat_title=parsed.chat_name,
send_action=lambda chat_id: self._telegram.send_text(
chat_id, text, reply_to_message_id=reply_telegram_mid
),
)
mid = sent.get("result", {}).get("message_id") if isinstance(sent.get("result"), dict) else None
if mid is not None:
@@ -124,11 +135,16 @@ class MaxToTelegramBridge:
for index, image_url in enumerate(parsed.image_urls):
caption = text if not sent_any and index == 0 else None
sent = await self._telegram.send_photo(
target_chat_id,
image_url,
caption=caption,
reply_to_message_id=reply_telegram_mid if not sent_any and index == 0 else None,
target_chat_id, sent = await self._send_with_migration_retry(
target_chat_id=target_chat_id,
max_chat_title_norm=normalized,
max_chat_title=parsed.chat_name,
send_action=lambda chat_id: self._telegram.send_photo(
chat_id,
image_url,
caption=caption,
reply_to_message_id=reply_telegram_mid if not sent_any and index == 0 else None,
),
)
mid = sent.get("result", {}).get("message_id") if isinstance(sent.get("result"), dict) else None
if mid is not None:
@@ -142,11 +158,16 @@ class MaxToTelegramBridge:
for index, video_url in enumerate(parsed.video_urls):
caption = text if not sent_any and index == 0 else None
sent = await self._telegram.send_video(
target_chat_id,
video_url,
caption=caption,
reply_to_message_id=reply_telegram_mid if not sent_any and index == 0 else None,
target_chat_id, sent = await self._send_with_migration_retry(
target_chat_id=target_chat_id,
max_chat_title_norm=normalized,
max_chat_title=parsed.chat_name,
send_action=lambda chat_id: self._telegram.send_video(
chat_id,
video_url,
caption=caption,
reply_to_message_id=reply_telegram_mid if not sent_any and index == 0 else None,
),
)
mid = sent.get("result", {}).get("message_id") if isinstance(sent.get("result"), dict) else None
if mid is not None:
@@ -167,6 +188,35 @@ class MaxToTelegramBridge:
len(parsed.video_urls),
)
async def _send_with_migration_retry(
self,
*,
target_chat_id: str,
max_chat_title_norm: str,
max_chat_title: str,
send_action: Callable[[str], Awaitable[Any]],
) -> tuple[str, Any]:
try:
sent = await send_action(target_chat_id)
return target_chat_id, sent
except TelegramApiError as exc:
migrated_chat_id = exc.migrate_to_chat_id
if not migrated_chat_id or migrated_chat_id == str(target_chat_id):
raise
logger.warning(
"Telegram chat %s upgraded to %s for MAX chat '%s'; update route and retry",
target_chat_id,
migrated_chat_id,
max_chat_title,
)
self._storage.set_chat_route(
max_chat_title_norm=max_chat_title_norm,
telegram_chat_id=migrated_chat_id,
telegram_chat_title=max_chat_title,
)
sent = await send_action(migrated_chat_id)
return migrated_chat_id, sent
def _resolve_telegram_reply_to(
self, *, telegram_chat_id: str, max_chat_id: str, parsed: ParsedMessage
) -> int | None:
+52 -3
View File
@@ -1,11 +1,34 @@
import asyncio
import json
from typing import Any
import requests
class TelegramApiError(RuntimeError):
pass
def __init__(
self,
message: str,
*,
method: str | None = None,
status_code: int | None = None,
error_code: int | None = None,
description: str | None = None,
parameters: dict[str, Any] | None = None,
) -> None:
super().__init__(message)
self.method = method
self.status_code = status_code
self.error_code = error_code
self.description = description
self.parameters = parameters or {}
@property
def migrate_to_chat_id(self) -> str | None:
value = self.parameters.get("migrate_to_chat_id")
if value is None:
return None
return str(value)
class TelegramClient:
@@ -209,10 +232,36 @@ class TelegramClient:
response = await asyncio.to_thread(_do_request)
if response.status_code >= 400:
error_code: int | None = None
description: str | None = None
parameters: dict[str, Any] = {}
try:
payload_data = response.json()
if isinstance(payload_data, dict):
if isinstance(payload_data.get("error_code"), int):
error_code = payload_data.get("error_code")
if isinstance(payload_data.get("description"), str):
description = payload_data.get("description")
if isinstance(payload_data.get("parameters"), dict):
parameters = payload_data.get("parameters", {})
except (json.JSONDecodeError, ValueError):
payload_data = None
raise TelegramApiError(
f"Telegram HTTP error on {method}: {response.status_code} {response.text}"
f"Telegram HTTP error on {method}: {response.status_code} {response.text}",
method=method,
status_code=response.status_code,
error_code=error_code,
description=description,
parameters=parameters,
)
data = response.json()
if not data.get("ok"):
raise TelegramApiError(f"Telegram API error on {method}: {data}")
raise TelegramApiError(
f"Telegram API error on {method}: {data}",
method=method,
error_code=data.get("error_code") if isinstance(data.get("error_code"), int) else None,
description=data.get("description") if isinstance(data.get("description"), str) else None,
parameters=data.get("parameters") if isinstance(data.get("parameters"), dict) else None,
)
return data
+33 -2
View File
@@ -90,6 +90,37 @@ def _normalize(value: str) -> str:
return str(value or "").strip().casefold()
def _deduplicate_chats(chats: list[Any]) -> list[Any]:
"""
Возвращает уникальные чаты с сохранением исходного порядка.
Сначала пытаемся уникализировать по chat.id, затем по нормализованному title.
"""
unique: list[Any] = []
seen_ids: set[str] = set()
seen_titles: set[str] = set()
for chat in chats:
chat_id = getattr(chat, "id", None)
if chat_id is not None:
key_id = str(chat_id).strip()
if key_id in seen_ids:
continue
seen_ids.add(key_id)
unique.append(chat)
continue
key_title = _normalize(_max_chat_title(chat))
if not key_title:
unique.append(chat)
continue
if key_title in seen_titles:
continue
seen_titles.add(key_title)
unique.append(chat)
return unique
async def _refresh_chats_best_effort(max_client: MaxClient) -> None:
# group.py: fetch_chats(marker=None) заполняет max_client.chats
try:
@@ -104,7 +135,7 @@ def _find_chat_by_title(max_client: MaxClient, title: str) -> Any | None:
wanted = _normalize(title)
if not wanted:
return None
chats = list(getattr(max_client, "chats", []) or [])
chats = _deduplicate_chats(list(getattr(max_client, "chats", []) or []))
for c in chats:
if _normalize(_max_chat_title(c)) == wanted:
return c
@@ -166,7 +197,7 @@ async def handle_control_command(
if cmd == "/list":
await _refresh_chats_best_effort(max_client)
chats = list(getattr(max_client, "chats", []) or [])
chats = _deduplicate_chats(list(getattr(max_client, "chats", []) or []))
if not chats:
return "Список чатов пуст (или клиент MAX ещё не успел их загрузить)."