TypeError: «Менеджер контекста драматурга» Как реализовать слаженную работу Пирограммы и Драматурга в одном потоке?Python

Программы на Python
Ответить Пред. темаСлед. тема
Гость
 TypeError: «Менеджер контекста драматурга» Как реализовать слаженную работу Пирограммы и Драматурга в одном потоке?

Сообщение Гость »


The title may not reflect the essence of the question. I am writing a small script. I use Pyrogram to troll messages from the Telegram channel. Next, I extract the necessary data, which I use Playwright to enter into a form on some site.

Here is an example of the code:

Код: Выделить всё

import re import logging from datetime import datetime from typing import AsyncGenerator from pyrogram import filters, Client from pyrogram.types import Message from playwright.async_api import async_playwright from keys import API_ID, API_HASH, CANAL_ID_IMEX, LOGIN, PASSWORD, URL client = Client("my_session", api_id=API_ID, api_hash=API_HASH) async def get_codes(message: Message) -> AsyncGenerator[str, None]:     """Example of the message text:     'ZM_GDB4SRHQNK Activate in bonuses.'     """     promo = [c              for codes in re.findall(                  r"(^[a-zA-Z]{2}_[a-zA-Z0-9]{10})",                  message.text, flags=re.MULTILINE                  )              for c in codes if c]     for code in promo:         yield code @client.on_message(filters.chat(CANAL_ID_IMEX)) async def message_handler(client: Client, message: Message) -> None:     async for code in get_codes(message):         with async_playwright() as playwright:             browser = await playwright.chromium.launch()             context = await browser.new_context()             page = await context.new_page()             await page.goto(URL) if __name__ == '__main__':     client.run() 
This line

Код: Выделить всё

with async_playwright() as playwright:
leads to the following error:

Код: Выделить всё

2024-03-08 21:16:02,915 - INFO - 256 | 2024-03-08 21:16:03 | ZM_Z263A89F4R | 0:00:00.000022  2024-03-08 21:16:02,915 - ERROR - 'function' object does not support the context manager protocol Traceback (most recent call last):   File "/home/svbazuev/Zooma/.venv/lib/python3.11/site-packages/pyrogram/dispatcher.py", line 240, in handler_worker     await handler.callback(self.client, *args)   File "/home/svbazuev/Zooma/main.py", line 99, in message_handler     with async_playwright() as playwright: TypeError: 'function' object does not support the context manager protocol 
When I made the changes suggested by ggorlen:

Код: Выделить всё

@client.on_message(filters.chat(CANAL_ID_IMEX)) async def message_handler(client: Client, message: Message) -> None:     async for code in get_codes(message):         if code:             async with async_playwright as p:                 browser = await p.chromium.launch() 
I got this error:

Код: Выделить всё

2024-03-09 13:02:59,842 - INFO - 274 | 2024-03-09 13:02:59 | ZM_726HBNYRA2 | 0:00:00.000029  2024-03-09 13:02:59,843 - ERROR - 'function' object does not support the asynchronous context manager protocol Traceback (most recent call last):   File "/home/svbazuev/Zooma/.venv/lib/python3.11/site-packages/pyrogram/dispatcher.py", line 240, in handler_worker     await handler.callback(self.client, *args)   File "/home/svbazuev/Zooma/main.py", line 100, in message_handler     async with async_playwright as p: TypeError: 'function' object does not support the asynchronous context manager protocol 
If I first save the necessary data and upload it separately to the form, I succeed. But I want to execute immediately without saving intermediate results.

I didn't find any explicit instructions in the documentation. I must be missing something. How to solve it?

At first, I used the synchronous implementation of Playwright (Windows OS). I think the problem is related to this. The asynchronous version of Playwright (OS Linux) is already being used in the code example. But I could be wrong...


Источник: https://stackoverflow.com/questions/781 ... ed-work-of
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение
  • Менеджер асинхронного контекста, который выполняет действие при переключении контекста.
    Anonymous » » в форуме Python
    0 Ответы
    27 Просмотры
    Последнее сообщение Anonymous
  • Как правильно реализовать менеджер контекста в psycopg2?
    Anonymous » » в форуме Python
    0 Ответы
    12 Просмотры
    Последнее сообщение Anonymous
  • Медиа-менеджер не отображает файловый менеджер в меню администратора
    Anonymous » » в форуме Php
    0 Ответы
    41 Просмотры
    Последнее сообщение Anonymous
  • Как использовать файл сеанса телемарафона для входа в систему с помощью пирограммы
    Anonymous » » в форуме Python
    0 Ответы
    9 Просмотры
    Последнее сообщение Anonymous
  • Как я могу получить папки чата с помощью пирограммы в Python?
    Anonymous » » в форуме Python
    0 Ответы
    6 Просмотры
    Последнее сообщение Anonymous

Вернуться в «Python»