I created a Telegram bot using the Python-Telegram-Bot library. The bot is in a group as an admin. It’s supposed to check messages and remove ones containing certain words from a list. But it’s not working and doesn’t show any errors.
Here’s my code:
import re
from telegram.ext import Updater, MessageHandler, Filters
def remove_bad_words(bot, update):
if not update.message.text:
print('No text in message')
return
bad_words = ['hello', 'goodbye']
for word in bad_words:
if re.search(word, update.message.text):
bot.delete_message(chat_id=update.message.chat_id,
message_id=update.message.message_id)
def start_bot():
updater = Updater(token='YOUR_BOT_TOKEN')
dp = updater.dispatcher
dp.add_handler(MessageHandler(Filters.all, remove_bad_words))
updater.start_polling()
updater.idle()
if __name__ == '__main__':
start_bot()
The bot should delete messages with words from the bad_words list, but it’s not doing anything. What could be wrong?
I’ve encountered similar issues with Telegram bots before. One thing to check is whether your bot has the necessary permissions in the group. Even if it’s an admin, it might not have the specific permission to delete messages.
Also, make sure your bot token is correct and the bot is actually running. Sometimes, the script might execute without errors, but the bot isn’t properly connected to Telegram’s servers.
Another potential issue could be with the regex. Try using word boundaries in your search pattern, like this:
if re.search(r'\b' + re.escape(word) + r'\b', update.message.text, re.IGNORECASE):
This ensures you’re matching whole words and not parts of words. The re.IGNORECASE flag makes it case-insensitive.
Lastly, add some logging to your script to see if the function is being called and if it’s detecting the bad words. This can help pinpoint where the issue might be occurring.
hey grace, i had similar probs. try adding some print statements to see if ur bot’s actually catching messages. also, double-check ur bot token - sometimes that’s the culprit. oh, and make sure ur bot has delete perms in the group. good luck!
Have you considered using the on_message event handler instead of MessageHandler? This approach might be more reliable for catching all messages. Also, ensure your bot’s privacy mode is disabled in BotFather settings, as it can interfere with message processing in groups.
Another potential issue could be rate limiting. Telegram has strict limits on bot actions. Try implementing a delay between message deletions using time.sleep().
Lastly, double-check that your bot is actually receiving messages. You can add a simple print statement in your handler function to confirm this. If you’re not seeing any output, it might indicate a connectivity issue or incorrect bot token.