O
O
Onervi2021-08-29 01:33:47
Python
Onervi, 2021-08-29 01:33:47

How to delete bot messages in telegram after a while?

How to make it so that after a while after the bot sends a message, it is deleted (time.sleep is not suitable because it stops all code)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
O
Old_TyT, 2021-08-29
@Onervi

If the usual sleep does not fit, then use the asynchronous one
https://realpython.com/lessons/asynciosleep-and-wr...

L
LXSTVAYNE, 2021-08-29
@lxstvayne

You can use this solution:

from threading import Thread
from collections import namedtuple
import time
import typing
import random


Message = namedtuple('Message', ['delete_time', 'message_id'])

messages_to_delete: typing.List[Message] = []


def delete_message(message: Message):
    print(f'Сообщение {message.message_id=} удалено')
    messages_to_delete.remove(message)


def messages_deleter():
    while True:
        for message in messages_to_delete:
            if message.delete_time - time.time() <= 0:
                delete_message(message)
        time.sleep(1)


if __name__ == '__main__':
    thread = Thread(target=messages_deleter)
    thread.start()
    while True:
        delete_time = time.time() + random.randint(1, 5)
        messages_to_delete.append(
            Message(delete_time=delete_time, message_id=random.randint(1, 1000))
        )

        time.sleep(1)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question