'Telegram bot can't delete message

I have received the following error while trying to delete a Message:

2018-04-10 13:58:57,646 (__init__.py:292 MainThread) ERROR - TeleBot: "A request to the Telegram API was unsuccessful. The server returned HTTP 400 Bad Request. Response body:
[b'{"ok":false,"error_code":400,"description":"Bad Request: message can\'t be deleted"}']"

Why message can't be deleted?

import config
import telebot

bot = telebot.TeleBot(config.token)

@bot.message_handler(content_types=["text"])
def repeat_all_messages(message):
  bot.send_message(message.chat.id, 'Hello World')
  bot.delete_message(message.chat.id, message.message_id)


if __name__ == '__main__':
 bot.polling(none_stop=True)


Solution 1:[1]

Check your Message. There are following limitations on deleting messages by bots:

  • A message can only be deleted if it was sent less than 48 hours ago.
  • Bots can delete outgoing messages in groups and supergroups.
  • Bots granted can_post_messages permissions can delete outgoing messages in channels.
  • If the bot is an administrator of a group, it can delete any message there.
  • If the bot has can_delete_messages permission in a supergroup or a channel, it can delete any message there. Returns True on success.

Solution 2:[2]

The handler you've placed to operate your bot only processes messages that the user has sent, not the bot.

the message object inside the repeat_all_messages() function is the message that the user has sent, and in this case you are only echoing it. I would try to do the following:

Since you know that next message is sent by you, you can increment the message_id by 1, since your message's id is +1 away from the one the user has sent, i.e:

@bot.message_handler(content_types=["text"])
def repeat_all_messages(message):
    bot.send_message(message.chat.id, 'Hello World')
    bot.delete_message(message.chat.id, message.message_id + 1)

Solution 3:[3]

I'm late to answer this.

Here's a demo which shows bot sending "Hi" message to the user every 10 seconds and deleting previous sent message

@bot.message_handler(commands=['hi'])
def hi(message):
  x = -1 
  while(True):
    if(x != -1): # not to delete first time
      bot.delete_message(message.chat.id, x.message_id)
    x = bot.send_message(message.chat.id, "Hi")
    time.sleep(10) #wait for 10 seconds

bot.polling()

bot.send_message() returns the Message object. We will store the object in a variable x and delete it by using x.message_id.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ivan Vinogradov
Solution 2 Sergey Ronin
Solution 3 Dharman