X
X
XWR2021-06-12 21:48:29
Python
XWR, 2021-06-12 21:48:29

How to edit a telegram message by timer using aiogram?

How to edit a telegram message using aiogram?
Hello, I want to edit the command / start

@dp.message_handler(commands=['start'])
async def process_start_command(message: types.Message):
    user_name = message.from_user.first_name
    await message.answer('Привет')


I want to make it edited for while by timer (5 seconds)
How can I do this?
I will be glad if you help

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
progeroffline, 2021-06-13
@XWR

I won't call my solution correct, but it works.
And so, in order to be able to edit messages after a certain timing, and the bot itself does not go into hibernation, you need to do these actions in a separate thread. The essence of this method is to send the waiting process to a separate thread, and within this thread we wait for the time you specified, and then send a request to the telegram server to edit the message.
We need libraries: threading, requests. The first is for multithreading, and the second is for sending requests to telegram servers.

# Импорт библиотек
import time

from threading import Thread

# Это функция отправляет запрос на редактирования сообщения напрямую через сервера телеграмма
# message - обьект сообщения
# delay - задержкка
# text - новый текст
def edit_message(message, delay, text):
  time.sleep(delay)
  api_url = "https://api.telegram.org/bot" + TOKEN
  method = "/editMessageText"
  chat_id = message.chat.id
  message_id = message.message_id

  r = requests.post(api_url + method, data={'chat_id': chat_id, 'message_id': message_id, 'text': text})

. . .
. . .
. . .

@dp.message_handler(content_types=['text'])
async def process_text(message: types.Message):
  # Добавляем функцию в отдельный поток 
  # args - аргументы функции
  th = Thread(target=edit_message, args=(message, 5, "Cообщение изменено", ))
  th.start()

I hope I explained everything clearly, if you have any questions, write.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question