Search code examples
arraystelethon

Telethon reply to the last channel post only


I have coded a small script which replies to channel posts. It works, but I want it to post only to the last channel post if multiple posts have been made in a short time (for example 3 posts in 5-10 seconds). I want it to post only to the last post of the 3.

This is my code so far:

@client.on(events.NewMessage(CHANNEL))
async def main(event):
    if -100123456789 == event.chat_id:
        await client.send_message(event.chat_id, 'my_message', comment_to=event.id)

I tried out some stuff like with append() but it still replies to all posts. Thanks in advance!


Solution

  • The easiest way is probably to start a new task when the first message arrives, and not do so when subsequent ones arrive.

    import asyncio
    
    reply_task = None
    reply_to = None
    
    COOLDOWN = 20  # seconds
    
    async def do_reply():
        global reply_task, reply_to
        await asyncio.sleep(COOLDOWN)
        await client.send_message(reply_to.chat_id, 'my_message', comment_to=reply_to.id)
        reply_task = None
    
    @client.on(events.NewMessage(CHANNEL))
    async def main(event):
        global reply_task, reply_to
    
        if reply_task is None:
            reply_task = asyncio.create_task(do_reply())
        
        reply_to = event
    

    When a message arrives, if there's no task, a new one will be made. The last event will be saved in a variable.

    When the spawned task completes the sleep, it will send the message to whichever event was last, and set the current task to None so a new one can be started.

    This does not handle multiple groups correctly. It also does not correctly handle exceptions. It also does not worry with proper cancellation of the task. This is only the skeleton of an idea.