在 python-telegram-bot 中使用 asyncio 和线程

问题描述 投票:0回答:1
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()

当我运行此代码并同时从 2 个电报帐户发送消息时,为一个用户启动进程,当进程结束时为另一个用户启动,但我想为用户同时启动,并且不要让任何人等待另一个用户结束时。

python multithreading bots python-asyncio python-telegram-bot
1个回答
0
投票

PTB针对此类案例提供的功能有

这些也在此维基页面上进行了详细阐述。您应该使用哪些功能以及使用到什么程度很大程度上取决于代码的整体设置和您的具体要求。因此我不会提出建议。


免责声明:我目前是

python-telegram-bot

的维护者
© www.soinside.com 2019 - 2024. All rights reserved.