Search code examples
pythontelegramtelebot

How can i delete message that channel name was changed using telebot?


I wrote a bot that change name of the telegram channel every N minutes But, when name of the channel is changed telegram automaticly send message, that channel name has been changed

i tried bot.delete_message command, but could't figure out how to delete that exact message


Solution

  • To delete the message that Telegram sends automatically when the channel name is changed, you can use the channel_post_handler decorator provided by the Telebot library to intercept and delete these messages.

    Example: bot.py

    import telebot
    
    bot = telebot.TeleBot('BOT_TOKEN')
    
    
    @bot.channel_post_handler(content_types=['new_chat_title'])
    def channel_name_changed(message):
        try:
            bot.delete_message(message.chat.id, message.message_id)
        except Exception as e:
            print("Error deleting message:", e)
    
    
    if __name__ == '__main__':
        bot.polling()
    

    changer.py

    import random
    from time import sleep
    
    import telebot
    
    bot = telebot.TeleBot('BOT_TOKEN')
    
    
    def change_channel_name():
        new_name = random.choice(["Channel 1", "Channel 2", "Channel 3", "Channel 4", "Channel 5"])
        try:
            bot.set_chat_title(
                "@CHAT",
                new_name
            )
        except Exception as e:
            print("Error changing channel name:", e)
    
    
    def main():
        while True:
            change_channel_name()
            sleep(10)
    
    
    if __name__ == '__main__':
        main()