concurrency_limit = 3
semaphore = asyncio.Semaphore(concurrency_limit)
async def send_pdf(last_update: Update, context: ContextTypes.DEFAULT_TYPE):
async with semaphore:
chat_id = last_update.effective_chat.id
msg = last_update.effective_message.text
html_path = f"{HTML_PATH}/{msg}{chat_id}.html"
pdf_path = f"{PDF_PATH}/{msg}{chat_id}{msg}.pdf"
json_path = f"{JSON_PATH}/{msg}{chat_id}{msg}.json"
await context.bot.send_message(
chat_id=chat_id, text="يتم البحث عن الوظائف قد يستغرق الوقت دقيقتين ..."
)
# Run the blocking script in a separate thread
loop = asyncio.get_running_loop()
data = await loop.run_in_executor(None, run_wuzzuf_script, msg)
await context.bot.send_message(
chat_id=chat_id, text="جاري انشاء ملف الpdf الخاص بك"
)
await asyncio.sleep(3)
# Generate the HTML page
page = f"""
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Job Details</title>
{STYLE}
</head>
<body>
<h1>Jobs For {msg}</h1><div class="container">{return_html_code(data)}</div></body></html>
"""
# Write data to JSON file
write_dict_to_json(data, json_path)
# Write the HTML page to a file
with open(html_path, "w", encoding="utf-8") as file:
file.write(page)
# Convert HTML to PDF in a separate thread
await loop.run_in_executor(None, convert_html_to_pdf, html_path, pdf_path)
await context.bot.send_message(
chat_id=chat_id, text="المسات الاخير انتظر ثواني"
)
await asyncio.sleep(5)
# Send the PDF document
with open(pdf_path, "rb") as pdf_file:
await context.bot.send_document(chat_id=chat_id, document=pdf_file)
await context.bot.send_message(
chat_id=chat_id, text="شكرا لاستخدامك هذا البوت"
)
if __name__ == "__main__":
application = ApplicationBuilder().token(BOT_TOKEN).build()
# Command Handler
start_command = CommandHandler("start", start_cmd)
send_handler = MessageHandler(filters.TEXT, send_pdf)
# Register Command
application.add_handler(start_command)
application.add_handler(send_handler)
application.run_polling()
When I run this code and send message from 2 telegram accounts in the same time, start process for one user and when it end start for another but I want to start in the same time for users and don't let any one wait another while end.
The features that PTB provides for such cases are
blockof all handlersApplicationBuilder.concurrent_updatesApplication.crate_taskThese are also elaborated on this wiki page. Which of those features you should use and to what extend depends highly on the overall setup of your code and your specific requirements. I will therefore not make a recommendation.
Disclaimer: I'm currently the maintainer of
python-telegram-bot