tasks.py:
import json
import os
import time
import dramatiq
import socks
import asyncio
from telethon import TelegramClient, errors
from telethon.errors import FloodError
from telethon.tl.functions.channels import JoinChannelRequest
from telethon.errors.rpcerrorlist import ChannelInvalidError, ChannelPublicGroupNaError
from telethon.tl.functions.messages import GetMessagesViewsRequest
import asyncio
import random
from telethon import errors
from logger import logger
from logger import logger
from dramatiq.brokers.redis import RedisBroker
from telethon.tl.types import InputMessageID
redis_broker = RedisBroker(url="redis://localhost:6379")
dramatiq.set_broker(redis_broker)
def load_client_params(session_file_path):
json_file = os.path.splitext(session_file_path)[0] + '.json'
if not os.path.exists(json_file):
logger.debug(f"[load_client_params] JSON файл не найден: {json_file}")
return {}
try:
with open(json_file, 'r', encoding='utf-8') as f:
data = json.load(f)
params = {}
if 'device' in data and data['device']:
params['device_model'] = data['device']
if 'sdk' in data and data['sdk']:
params['system_version'] = data['sdk']
if 'app_version' in data and data['app_version']:
params['app_version'] = data['app_version']
if 'lang_code' in data and data['lang_code']:
params['lang_code'] = "ru"
logger.debug(f"[load_client_params] Параметры из {json_file}: {params}")
return params
except Exception as e:
logger.warning(f"[load_client_params] Ошибка чтения {json_file}: {e}")
return {}
async def get_channel_entity(client, channel):
logger.debug(f"[get_channel_entity] Начало получения entity для: '{channel}'")
# Очистка ссылки
if isinstance(channel, str):
for prefix in ["https://t.me/", "http://t.me/", "t.me/"]:
if channel.startswith(prefix):
logger.debug(f"[get_channel_entity] Очистка ссылки канала: удаляем префикс '{prefix}'")
channel = channel[len(prefix):]
channel_id = None
if isinstance(channel, str) and channel.isdigit():
channel_id = int(channel)
logger.debug(f"[get_channel_entity] Определено как числовой ID: {channel_id}")
try:
if channel_id is None:
entity = await client.get_entity(channel)
logger.info(f"[get_channel_entity] Получена entity для username/ссылки '{channel}' -> {entity}")
return entity
else:
try:
entity = await client.get_entity(channel_id)
logger.info(f"[get_channel_entity] Получена entity для ID {channel_id} -> {entity}")
return entity
except (ValueError, ChannelInvalidError, ChannelPublicGroupNaError) as exc:
logger.warning(f"[get_channel_entity] get_entity не нашел entity по ID {channel_id}: {exc}")
dialogs = await client.get_dialogs()
logger.debug(f"[get_channel_entity] Проверяем {len(dialogs)} диалогов для поиска ID {channel_id}")
for dialog in dialogs:
e = dialog.entity
if getattr(e, 'id', None) == channel_id:
input_entity = await client.get_input_entity(e)
logger.info(f"[get_channel_entity] Найдена entity в диалогах: {input_entity}")
return input_entity
raise ValueError(f"Канал с ID {channel_id} не найден в диалогах")
except Exception as e:
logger.error(f"[get_channel_entity] Ошибка при получении entity для '{channel}': {e}", exc_info=True)
raise
def proxy_tuple_from_str(proxy_line):
logger.debug(f"[proxy_tuple_from_str] Парсим прокси из строки: {proxy_line}")
parts = proxy_line.strip().split(":")
if len(parts) != 4:
logger.error(f"[proxy_tuple_from_str] Некорректный формат прокси: {proxy_line}")
raise ValueError(f"Некорректный формат прокси: {proxy_line}")
ip, port, user, password = parts
proxy = (socks.SOCKS5, ip, int(port), True, user, password)
logger.debug(f"[proxy_tuple_from_str] Результат: {proxy}")
return proxy
async def subscribe_account_async(session_file, proxy_line, channel):
logger.info(f"[subscribe_account_async] Старт подписки, аккаунт: {session_file}, прокси: {proxy_line.split(':')[0]}:{proxy_line.split(':')[1]}, канал: {channel}")
start = time.monotonic()
proxy = proxy_tuple_from_str(proxy_line)
params = load_client_params(session_file)
logger.info(f"[subscribe_account_async] Создаём клиент с прокси {proxy}")
client = TelegramClient(session_file, api_id=28248459, api_hash="1d964bad240e82afed769b82c89292fe", proxy=proxy, **params)
await client.start()
logger.info(f"[subscribe_account_async] Клиент запущен, прошло {time.monotonic() - start:.2f} сек")
try:
logger.debug(f"[subscribe_account_async] Клиент Telethon запущен для сессии {session_file}")
start_entity = time.monotonic()
entity = await get_channel_entity(client, channel)
logger.info(f"[subscribe_account_async] Получена сущность за {time.monotonic() - start_entity:.2f} сек")
start_view = time.monotonic()
await client(JoinChannelRequest(entity))
logger.info(f"[subscribe_account_async] Аккаунт {session_file} успешно подписан на канал {channel}")
logger.info(f"[subscribe_account_async] Подписался на канал за {time.monotonic() - start_view:.2f} сек")
await client.disconnect()
except errors.UserAlreadyParticipantError:
logger.info(f"[subscribe_account_async] Аккаунт {session_file} уже подписан на канал {channel}")
except Exception as e:
logger.error(f"[subscribe_account_async] Ошибка подписки аккаунта {session_file} на канал {channel}: {e}", exc_info=True)
raise
finally:
await client.disconnect()
logger.debug(f"[subscribe_account_async] Клиент Telethon отключен для сессии {session_file}")
@dramatiq.actor(max_retries=3, time_limit=15000)
def subscribe_account(session_file, proxy_line, channel_id):
logger.info(f"[subscribe_account actor] Получен запрос на подписку. Аккаунт: {session_file}, прокси: {proxy_line}, канал: {channel_id}")
try:
asyncio.run(subscribe_account_async(session_file, proxy_line, channel_id))
logger.info(f"[subscribe_account actor] Задача выполнена: аккаунт {session_file}")
except Exception as e:
logger.error(f"[subscribe_account actor] Ошибка в подписке аккаунта {session_file}: {e}", exc_info=True)
raise # триггерим retry
async def safe_increment_views(client, entity, post_id, max_retries=3):
"""
Безопасно отправляет запрос увеличения просмотров поста.
Вставляет рандомную задержку, обрабатывает FloodError с паузой и повтором.
:param client: instance TelegramClient
:param entity: канал / чат для просмотра поста
:param post_id: id поста
:param max_retries: максимальное число попыток
"""
for attempt in range(1, max_retries + 1):
try:
# Рандомная задержка перед запросом (иначе телеграм пугается одинаковых частот)
delay_sec = random.uniform(20, 45)
logger.info(f"[safe_increment_views] Подождём {delay_sec:.1f} секунд перед запросом просмотров (попытка #{attempt})")
await asyncio.sleep(delay_sec)
views = await client(GetMessagesViewsRequest(peer=entity, id=[post_id], increment=True))
logger.info(f"[safe_increment_views] Запрос increment views успешен. Ответ: {views}")
return views
except errors.FloodError as e:
wait_sec = 300 # 5 минут
logger.warning(f"[safe_increment_views] FloodError (бан на метод) на попытке {attempt}: {e}. Пауза {wait_sec} секунд.")
await asyncio.sleep(wait_sec)
except Exception as ex:
logger.error(f"[safe_increment_views] Ошибка при попытке {attempt}: {ex}", exc_info=True)
# Можно решать — повторять или нет, здесь пробуем повторить
await asyncio.sleep(10)
logger.error(f"[safe_increment_views] Превышено число попыток ({max_retries}), запрос не выполнен.")
raise RuntimeError(f"Не удалось безопасно увеличить просмотры поста {post_id} после {max_retries} попыток")
async def view_post_account_async(session_file, proxy_line, channel, post_id):
logger.info(f"[view_post_account_async] Старт просмотра поста, аккаунт: {session_file}, прокси: {proxy_line.split(':')[0]}:{proxy_line.split(':')[1]}, канал: {channel}, пост: {post_id}")
proxy = proxy_tuple_from_str(proxy_line)
params = load_client_params(session_file)
client = TelegramClient(session_file, api_id=28248459, api_hash="1d964bad240e82afed769b82c89292fe",
proxy=proxy, **params)
await client.start()
try:
logger.debug(f"[view_post_account_async] Клиент Telethon запущен для сессии {session_file}")
entity = await get_channel_entity(client, channel)
logger.debug(f"[view_post_account_async] Получена сущность канала для просмотра поста: {entity}")
# Используем новую безопасную функцию
await safe_increment_views(client, entity, post_id)
except FloodError as fe:
logger.error(f"[view_post_account_async] Получен FloodError (забанен аккаунт?): {fe}", exc_info=True)
raise
except Exception as e:
logger.error(f"[view_post_account_async] Ошибка просмотра поста аккаунтом {session_file} на канале {channel} пост {post_id}: {e}", exc_info=True)
raise
finally:
await client.disconnect()
logger.debug(f"[view_post_account_async] Клиент Telethon отключен для сессии {session_file}")
@dramatiq.actor(max_retries=1, time_limit=60000)
def view_post_account(session_file, proxy_line, channel, post_id):
logger.info(
f"[view_post_account actor] Получен запрос на просмотр поста. Аккаунт: {session_file}, прокси: {proxy_line}, канал: {channel}, пост: {post_id}")
try:
asyncio.run(view_post_account_async(session_file, proxy_line, channel, post_id))
logger.info(f"[view_post_account actor] Задача выполнена: аккаунт {session_file}, пост {post_id}")
except Exception as e:
logger.error(f"[view_post_account actor] Ошибка в просмотре поста аккаунтом {session_file}: {e}", exc_info=True)
raise # триггерим retry
supervisor.py:
import os
import asyncio
import re
from telethon import TelegramClient, events
from datetime import datetime
from logger import logger
import dramatiq
from tasks import subscribe_account, view_post_account
SESSIONS_DIR = os.path.abspath(os.path.join(os.path.dirname(file), "sessions"))
PROXIES_FILE = os.path.abspath(os.path.join(os.path.dirname(file), "proxies.txt"))
SUPERVISOR_SESSION = os.path.abspath(os.path.join(os.path.dirname(file), "sessions/supervisor/supervisor.session"))
API_ID = 28248459
API_HASH = "1d964bad240e82afed769b82c89292fe"
def load_sessions():
sessions = [os.path.join(SESSIONS_DIR, f) for f in os.listdir(SESSIONS_DIR) if f.endswith(".session")]
logger.info(f"[load_sessions] Загружено сессий: {len(sessions)}")
for s in sessions:
logger.debug(f"[load_sessions] Сессия: {s}")
return sessions
def load_proxies():
proxies = []
logger.info(f"[load_proxies] Загрузка прокси из файла: {PROXIES_FILE}")
if not os.path.exists(PROXIES_FILE):
logger.error(f"[load_proxies] Файл прокси не найден: {PROXIES_FILE}")
return proxies
with open(PROXIES_FILE, "r") as f:
for line in f:
line = line.strip()
if line:
logger.debug(f"[load_proxies] Прокси: {line}")
proxies.append(line)
logger.info(f"[load_proxies] Загружено прокси: {len(proxies)}")
return proxies
async def main():
logger.info("[main] Запуск супервизора...")
client = TelegramClient(SUPERVISOR_SESSION, API_ID, API_HASH)
await client.start()
me = await client.get_me()
logger.info(f"[main] Supervisor started as {me.first_name} ({me.username})")
@client.on(events.NewMessage(pattern=r'^/subscribe (\S+) (\d+) (\d+)$'))
async def subscribe_handler(event):
try:
channel = event.pattern_match.group(1) # username, ссылка или id
count = int(event.pattern_match.group(2))
hours = int(event.pattern_match.group(3))
if hours > 48:
logger.warning(f"[subscribe_handler] Ограничение в 48 часов превышено, установлено {hours} -> 48")
hours = 48
logger.info(f"[subscribe_handler] Команда /subscribe от user_id={event.sender_id}: канал='{channel}', ботов={count}, время={hours}ч")
await event.reply(f"Планируем подписку {count} ботов на канал {channel} в течение {hours} часов.")
sessions = load_sessions()
proxies = load_proxies()
if not sessions:
logger.error("[subscribe_handler] Нет доступных сессий для подписки.")
await event.reply("Нет доступных сессий для подписки.")
return
if not proxies:
logger.error("[subscribe_handler] Нет доступных прокси.")
await event.reply("Нет доступных прокси.")
return
sessions = sessions[:count]
logger.info(f"[subscribe_handler] Используем сессии: {sessions}")
logger.info(f"[subscribe_handler] Используем прокси: {proxies}")
total_seconds = hours * 3600
step = 0
if count > 1 and total_seconds > 0:
step = total_seconds / count
logger.info(f"[subscribe_handler] Расчет задержки (step): {step:.2f} сек")
for idx, session_file in enumerate(sessions):
proxy_line = proxies[idx % len(proxies)]
delay_ms = int(step * 1000 * idx)
logger.info(f"[subscribe_handler] Планирование: акк={os.path.basename(session_file)}, proxy={proxy_line.split(':')[0]}:{proxy_line.split(':')[1]}, delay={delay_ms/1000:.2f}s")
subscribe_account.send_with_options(args=(session_file, proxy_line, channel), delay=delay_ms)
logger.info(f"[subscribe_handler] Задачи на подписку поставлены: {len(sessions)}")
except Exception as e:
logger.error(f"[subscribe_handler] Ошибка обработки команды /subscribe: {e}", exc_info=True)
await event.reply(f"Ошибка при обработке команды: {e}")
@client.on(events.NewMessage(pattern=r'^/view_post\s+(\S+)\s+(\d+)\s+(\d+)$'))
async def view_post_handler(event):
try:
link_or_channel = event.pattern_match.group(1)
count = int(event.pattern_match.group(2))
hours = int(event.pattern_match.group(3))
if hours > 48:
logger.warning(f"[view_post_handler] Ограничение в 48 часов превышено, установлено {hours} -> 48")
hours = 48
# Попытка распарсить ссылку поста
match = re.match(r"(?:https?://)?t\.me/([^/]+)/(\d+)", link_or_channel)
if match:
channel = match.group(1)
post_id = int(match.group(2))
logger.info(f"[view_post_handler] Распарсена ссылка: канал={channel}, пост_id={post_id}")
else:
# Если не ссылка, предполагаем, что это либо username, либо id в channel, а пост_id передан в параметрах
# В этом случае post_id ожидается как второй параметр (count в вашем формате), но поскольку count — количество ботов,
# а пост_id нет в этой записи, значит надо изменить немного формат команды
# Но в вашем примере пост_id выделяется из ссылки, поэтому здесь только логируем ошибку
logger.error(f"[view_post_handler] Не удалось распарсить ссылку/канал: {link_or_channel}")
await event.reply(
"Неверный формат ссылки на пост. Используйте формат: https://t.me/channel_username/post_id")
return
logger.info(
f"[view_post_handler] Команда /view_post от user_id={event.sender_id}: канал='{channel}', пост {post_id}, ботов={count}, время={hours}ч")
await event.reply(
f"Планируем просмотр {count} ботов поста {post_id} на канале {channel} в течение {hours} часов.")
sessions = load_sessions()
proxies = load_proxies()
if not sessions:
logger.error("[view_post_handler] Нет доступных сессий для просмотра поста.")
await event.reply("Нет доступных сессий для просмотра поста.")
return
if not proxies:
logger.error("[view_post_handler] Нет доступных прокси.")
await event.reply("Нет доступных прокси.")
return
sessions = sessions[:count]
logger.info(f"[view_post_handler] Используем сессии: {sessions}")
logger.info(f"[view_post_handler] Используем прокси: {proxies}")
total_seconds = hours * 3600
step = 0
if count > 1 and total_seconds > 0:
step = total_seconds / count
logger.info(f"[view_post_handler] Расчет задержки (step): {step:.2f} сек")
for idx, session_file in enumerate(sessions):
proxy_line = proxies[idx % len(proxies)]
delay_ms = int(step * 1000 * idx)
logger.info(
f"[view_post_handler] Планирование: акк={os.path.basename(session_file)}, proxy={proxy_line.split(':')[0]}:{proxy_line.split(':')[1]}, delay={delay_ms / 1000:.2f}s")
view_post_account.send_with_options(args=(session_file, proxy_line, channel, post_id), delay=delay_ms)
logger.info(f"[view_post_handler] Задачи на просмотр поста поставлены: {len(sessions)}")
except Exception as e:
logger.error(f"[view_post_handler] Ошибка обработки команды /view_post: {e}", exc_info=True)
await event.reply(f"Ошибка при обработке команды: {e}")
logger.info("[main] Supervisor слушает команды...")
await client.run_until_disconnected()
if name == "main":
logger.info("[main] Запуск супервизора через asyncio.run(main())")
asyncio.run(main())
Мне нужно добавить новый обработчик выхода новых постов, если сессия супервизора (event) обнаруживает новый пост в канале, на которые он подписан, то вывести в логгер "вышел новый пост в канале и т.п"