Error while trying to implement a periodic message on a Telegram Bot with Python

72 views Asked by At

I'm trying to implement a Telegram Bot function that allows my account to periodically receive an update message, but I receive this error when I execute the function:

telebot.apihelper.ApiTelegramException: A request to the Telegram API was unsuccessful. Error code: 409. Description: Conflict: terminated by other getUpdates request; make sure that only one bot instance is running

This is my code.

import threading

import telebot
import Consts

from mypackage.ProcessManager import ProcessManager


bot = telebot.TeleBot(Consts.bot_token, threaded=True)
process_manager = ProcessManager()


@bot.message_handler(commands=['subscribe'])
def subscribe(message):
    chat_id = message.from_user.id
    if not process_manager.has_running_elements(chat_id):
        process_manager.start_process(chat_id=chat_id,
                                  target=send_message,
                                  arg2=chat_id, arg3="Prova")
        bot.reply_to(message, "Perfetto. Da ora riceverai aggiornamenti sulla tua assicurazione")
    else:
        bot.reply_to(message, "Sei giĆ  iscritto")


def send_message(chat_id, message: str):
    bot.send_message(chat_id=chat_id, text=message)


bot.infinity_polling()

ProcessManager is just a wrapper class that handles multiprocessing.Process objects. I'm also sharing that start_process function:

    def start_process(self, chat_id, target, **args):
        new_process = multiprocessing.Process(target=target,
                                          daemon=True,
                                          args=args)
        self.processes_dict[chat_id] = new_process
        new_process.start()

What am I doing wrong?

1

There are 1 answers

0
Fabrizio Gabriele On BEST ANSWER

I solved it using multithreading.Thread instead of multiprocessing.Process.