Answer the question
In order to leave comments, you need to log in
How to set up multithreading in a telegram bot?
There is a telegram bot that works with files. When writing it, I made a mistake and forgot about multithreading, which causes errors in work due to the fact that different users have different directories and file processing processes take a lot of time, etc. When writing, the pyTelegramBotAPI library was used. Does it have methods that are responsible for multithreading? I know about the threading library, the bot code is quite large and I really don’t want to redo it.
ADDITION
Here is one small piece of code:
@bot.message_handler(commands=['start'])
def start(message):
# keyboard
markup1 = types.ReplyKeyboardMarkup(resize_keyboard=True)
item1 = types.KeyboardButton("Видео")
item2 = types.KeyboardButton("Аудио")
item3 = types.KeyboardButton("Завершить")
item4 = types.KeyboardButton("/start")
item5 = types.KeyboardButton("Добавить файлы")
markup1.add(item1, item2).add(item3, item5).add(item4)
start_dir = os.getcwd()
bot.send_message(message.chat.id, "текст")
bot.send_message(message.chat.id, "текст")
bot.send_message(message.chat.id, "текст", reply_markup=markup1)
database.registration_user(message.from_user.id, message.from_user.first_name, message.from_user.last_name)
derect_function.creat_vid_dir(message.from_user.id)
derect_function.creat_aud_dir(message.from_user.id)
derect_function.creat_com_dir(message.from_user.id)
derect_function.creat_img_dir(message.from_user.id)
derect_function.creat_res_dir(message.from_user.id)
if database.select_status_of_usages(message.from_user.id) == 0:
derect_function.delete_file_in_vid_dir(message.from_user.id)
derect_function.delete_file_in_aud_dir(message.from_user.id)
derect_function.delete_file_in_img_dir(message.from_user.id)
derect_function.delete_file_in_res_dir(message.from_user.id)
derect_function.creat_command_file(message.from_user.id)
if user_id not in database_for_google.select_user_id():
google_program.start_upload_file(message.from_user.id)
Answer the question
In order to leave comments, you need to log in
In short: let the bot run on the main thread. FZ, synchronous or asynchronous, depends on the library used. Judging by the above code, synchronously.
But run all long-running operations in separate threads or even processes.
Organize two queues for communication between the bot thread and worker threads/processes. From one data processing threads will accept jobs. In another, they will add messages to send (text + user id, for example). Then the main bot, when the request is ready, should put the object with the task description in the first place, and also periodically check for messages in the second. If available, extract and send to destination.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question