Skip to content

bug can't send message #4692

@xvovabluex

Description

@xvovabluex

Code that causes the issue

import os
import random
import asyncio
from telethon import TelegramClient
from telethon.errors import SessionPasswordNeededError, FloodWaitError
from telethon.types import InputPeerChat
import logging

logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    datefmt='%Y-%m-%d %H:%M:%S'
)
logger = logging.getLogger(__name__)

class TelegramMassSender:
    def __init__(self):
        self.folder_path = 'sessions'
        self.chat_list = [
            "https://t.me/vzjacki",
            #"https://t.me/piary_chatik", 
            "https://t.me/fludov_chat1",
            "https://t.me/vzaimki_piarr",
            "https://t.me/meow_piar_chat",
            "https://t.me/PR_CHAT1K",
            "https://t.me/VZAIMNYE_PODPISKI_PIAR_CHAT",
            "https://t.me/kypuprodautrafuk"
        ]
        self.message_text = """test"""
        self.clients = []
        self.entities = []
        
    async def load_sessions(self):
        if not os.path.exists(self.folder_path):
            logger.error(f"Папка '{self.folder_path}' не найдена")
            return False
            
        session_files = [
            os.path.join(self.folder_path, f) 
            for f in os.listdir(self.folder_path) 
            if f.endswith('.session') and os.path.isfile(os.path.join(self.folder_path, f))
        ]
        
        if not session_files:
            logger.error("Сессионные файлы не найдены")
            return False
            
        logger.info(f"Найдено {len(session_files)} сессионных файлов")
        
        for session_file in session_files:
            try:
                client = TelegramClient(
                    session=session_file,
                    api_id=,
                    api_hash=,
                    connection_retries=None,
                    device_model="Universus Sapientia Zephyrus",
                    system_version="Samsung Galaxy S24 Ultra",
                    app_version="11.14.1",
                    lang_code="en",
                    system_lang_code="en-US"
                )
                await client.connect()
                
                if await client.is_user_authorized():
                    self.clients.append(client)
                    logger.info(f"Сессия {os.path.basename(session_file)} успешно загружена")
                else:
                    logger.warning(f"Сессия {os.path.basename(session_file)} не авторизована")
                    await client.disconnect()
                    
            except Exception as e:
                logger.error(f"Ошибка при загрузке сессии {session_file}: {e}")
        
        return len(self.clients) > 0
    
    async def load_entities(self):
        if not self.clients:
            logger.error("Нет доступных клиентов для загрузки чатов")
            return False
            
        for i in self.clients:
            toappend = []
            for chat_url in self.chat_list:
                try:
                    entity = await i.get_entity(chat_url)
                    toappend.append({
                        'entity': entity,
                        'url': chat_url
                    })
                    logger.info(f"Загружен чат: {chat_url}")
                except Exception as e:
                    logger.error(f"Ошибка при загрузке чата {chat_url}: {e}")
            self.entities.append(toappend)
            #print(self.entities)
        return len(self.entities) > 0
    
    async def send_messages(self):
        if not self.entities:
            logger.error("Нет доступных чатов для отправки")
            return
            
        logger.info(f"Начинаем рассылку сообщений с {len(self.clients)} аккаунтов в {len(self.entities)} чатов...")
        
        while True:
            successful_sends = 0
            failed_sends = 0
            
            ide = 0
            for i in self.clients:
                for chat_info in self.entities[ide]:
                    print(chat_info['entity'])
                    try:
                        client = i
                        telegramgovnoebanoe = await client.get_entity(chat_info['url'])
                        await client.send_message(telegramgovnoebanoe, self.message_text)
                        successful_sends += 1
                        
                        chat_name = getattr(chat_info['entity'], 'title', getattr(chat_info['entity'], 'username', chat_info['url']))
                        logger.info(f"Сообщение отправлено в {chat_name} через {client.session.filename}")
                        
                        await asyncio.sleep(random.uniform(2, 5))
                        
                    except FloodWaitError as e:
                        logger.warning(f"Flood wait: ожидание {e.seconds} секунд")
                        await asyncio.sleep(e.seconds)
                        
                    except Exception as e:
                        failed_sends += 1
                        logger.error(f"Ошибка при отправке сообщения в {chat_info['url']}: {e}")
                        await asyncio.sleep(10)  # Пауза при ошибке
                ide += 1
            
            logger.info(f"Цикл завершен: успешно {successful_sends}, ошибок {failed_sends}")
            
            if successful_sends > 0:
                wait_time = random.uniform(30, 60)
                logger.info(f"Ожидание {wait_time:.1f} секунд до следующего цикла...")
                await asyncio.sleep(wait_time)
            else:
                logger.warning("Все отправки завершились ошибкой. Ожидание 60 секунд...")
                await asyncio.sleep(60)
    
    async def run(self):
        logger.info("Запуск Telegram Sender")
        
        if not await self.load_sessions():
            logger.error("Не удалось загрузить сессии. Завершение работы.")
            return
            
        if not await self.load_entities():
            logger.error("Не удалось загрузить чаты. Завершение работы.")
            await self.cleanup()
            return
            
        try:
            await self.send_messages()
        except KeyboardInterrupt:
            logger.info("Работа прервана пользователем")
        except Exception as e:
            logger.error(f"Критическая ошибка: {e}")
        finally:
            await self.cleanup()
    
    async def cleanup(self):
        logger.info("Отключение клиентов...")
        for client in self.clients:
            try:
                await client.disconnect()
                logger.info(f"Клиент {client.session.filename} отключен")
            except Exception as e:
                logger.error(f"Ошибка при отключении клиента: {e}")

async def main():
    sender = TelegramMassSender()
    await sender.run()

if __name__ == "__main__":
    try:
        asyncio.run(main())
    except KeyboardInterrupt:
        print("\nПрограмма завершена")

Expected behavior

always getting
An invalid Peer was used. Make sure to pass the right peer type and that the value is valid (for instance, bots cannot start conversations) (caused by SendMessageRequest)

Actual behavior

An invalid Peer was used. Make sure to pass the right peer type and that the value is valid (for instance, bots cannot start conversations) (caused by SendMessageRequest)

Traceback

An invalid Peer was used. Make sure to pass the right peer type and that the value is valid (for instance, bots cannot start conversations) (caused by SendMessageRequest)

Telethon version

1.35.0

Python version

3.12

Operating system (including distribution name and version)

Windows 10

Other details

No response

Checklist

  • The error is in the library's code, and not in my own.
  • I have searched for this issue before posting it and there isn't an open duplicate.
  • I ran pip install -U https://github.com/LonamiWebs/Telethon/archive/v1.zip and triggered the bug in the latest version.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions