Search code examples
pythontelebot

I don't want the Telegram bot send repeated messages


i'm learning Python!

I'm building a Bot that searches for products in an e-commerce, the bot will always send a message with a price predefined by me!

The bot does a new search every 5 minutes, but I don't want send the same product again in the next message, i did some research but found nothing that fits what i need.

Sorry for my bad english! I hope you understand what I meant.

Code:

def send_to_telegram(message):

    apiToken = 'xxxxx'
    chatID = '-xxxx'
    bot = telebot.TeleBot(apiToken)

    if placa and fabricante_1 in marca:
        bot.send_message(
            chat_id=chatID, text=f"<b>Modelo:</b> {marca} \n<b>Fabricante:</b> {fabricante_1}\n<b>Preço a vista:</b> R$ {valor_preco_avista} \n<b>Preço a prazo:</b> R$ {valor_preco_prazo} \n<b>Loja:</b> {loja} \n\n<b>Link Produto:</b> {url_completa}", parse_mode='HTML')

I tried some modules like: schedule, time But in the end the bot sends the duplicate message anyway.


Solution

  • I managed to solve my problem, I'll leave the solution for anyone who has a similar doubt in the future!

    To avoid sending repeated messages with a Telegram bot with Python, you can store a record of the messages that have already been sent and check against this record before sending a new message.

    import os
    import pickle
    
    sent_messages_file = "sent_messages.pickle"
    
    if os.path.exists(sent_messages_file):
        with open(sent_messages_file, "rb") as f:
            sent_messages = pickle.load(f)
    else:
        sent_messages = []
    
    
    def send_message(mensagem):
    
        apiToken = 'XXXXXXXXXX'
        chatID = 'XXXXXXXX'
        bot = telebot.TeleBot(apiToken)
        bot.send_message(
            chat_id=chatID, text=message, parse_mode='HTML')
        sent_messages.append(message)
        with open(sent_messages_file, "wb") as f:
            pickle.dump(sent_messages, f)
    

    In this code, the sent_messages list is saved to a file using the pickle module. Before sending a new message, the code checks if the sent_messages_file exists. If it exists, the code loads the sent_messages list from the file. If it does not exist, the code creates an empty sent_messages list. After sending a message, the code saves the updated sent_messages list to the file.

    This way, when you run the code again, it will load the sent_messages list from the file, and only send new messages that have not been sent before.