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} nn<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.
2
Answers
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.
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.
Thank you very much, I researched a lot and only found your solution…
For me, I only made small changes to the Telegram message code.
My code runs every 15 seconds, without sending duplicate messages.
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 enviar_mensagem(msg):
bot_token = ”
chat_id = ”
url = f’https://api.telegram.org/bot{bot_token}/sendMessage?chat_id={chat_id}&text={msg}’
requests.post(url)
sent_messages.append(msg)
with open(sent_messages_file, "wb") as f:
pickle.dump(sent_messages, f)