I am trying to add a feature to delete n number of chat messages for my telegram bot

39 Views Asked by At

Here is the code itself that doesn't quite work(the problem is not with 'ALLOWED_USER')

@bot.message_handler(commands=['delete'])
def delete_messages(message):
    user_id = message.from_user.id
    chat_id = message.chat.id
    bot.delete_message(chat_id=chat_id, message_id=message.message_id)

    if user_id == ALLOWED_USER:
        try:
            command_parts = message.text.split(' ')
            if len(command_parts) == 3:
                username = command_parts[1]
                count = int(command_parts[2])

                messages = bot.get_chat_history(chat_id, limit=100)
                deleted_count = 0

                for msg in messages:
                    if msg.from_user.username == username:
                        bot.delete_message(chat_id=chat_id, message_id=msg.message_id)
                        deleted_count += 1

                        if deleted_count == count:
                            break

        except Exception as e:
            bot.send_message(chat_id, f"Error {e}")

    else:
        bot.send_message(chat_id, "No")

I tried to find this in the telebot documentation, but I didn't find anything.

1

There are 1 best solutions below

0
On

I suggest you to add print statements, you can better understand the flow of your program and identify where the problem might be occurring.

print("Command Parts:", command_parts)
print("Username:", username)
print("Count:", count)
print("Error:", e)