Search code examples
telegramtelethontelegram-api

Telethon regular repetition of the action when a certain number of rows in the list is reached (counting rows)


Please help me with the execution of an action that depends on the number of lines. So, the task of the program is to track how many messages were in the group, and then when the value of these messages reaches a certain number, perform an action to send a message to the same group.

from telethon import TelegramClient, sync
from telethon.events import NewMessage

api_id = '____'
api_hash = '______'

client = TelegramClient('session_name', api_id, api_hash)

@client.on(event=NewMessage(chats=('https://t.me/some_group')))
async def normal_handler(event):
    value = event.message.to_dict()['message']
    lines = 0
    for line in value:
        lines += 1
    print(lines)
    if lines % 2:           #the task is to send messages every 2 income messages
        await client.send_message('https://t.me/some_group', message='something')

client.start()
client.run_until_disconnected()

Currently, the program shows me each message separately and counts the number of characters in this particular message, and then proceeds to the next message.

I am grateful for your patience :)

Thank you very much in advance


Solution

  • from telethon import TelegramClient, sync
    from telethon.events import NewMessage
    
    api_id = '______'
    api_hash = '______'
    
    client = TelegramClient('session_name', api_id, api_hash)
    
    @client.on(event=NewMessage(chats=('https://t.me/_____')))
    async def normal_handler(event):
        value = event.message.to_dict()['message']
    
        file = open('text.txt', 'r+')
        read = file.read()
        file.write(value + '\n')
    
        read_str = ''.join(read)
        splited = read_str.split('\n')
    
        number = len(splited)
        if number >= 15:
            file.truncate(0)
            print('Sending the message')
            await client.send_message('_____', message='Строк больше 15')
            
        print(number)
    
    
        file.close()
    client.start()
    client.run_until_disconnected()