Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor asyncio #126

Open
wants to merge 3 commits into
base: dev
Choose a base branch
from
Open

Conversation

Danstiv
Copy link

@Danstiv Danstiv commented Jan 4, 2025

The logic for checking and executing asynchronous/synchronous functions is moved to the Client.acall method.
I manually tested the following:

  1. calling synchronous and asynchronous handlers in the dispatcher works.
  2. calling synchronous and asynchronous progress-callbacks in Client.get_file and Client.save_file works.
  3. synchronous and asynchronous filters works.

Also, where possible, explicit use of event loop is replaced by function calls in the asyncio module, which is the recommended way and avoids some problems.

@Danstiv Danstiv marked this pull request as draft January 4, 2025 15:31
@Danstiv
Copy link
Author

Danstiv commented Jan 4, 2025

It looks like it's all working.
Unfortunately, I haven’t found a way to make async to sync work correctly in all cases, namely:

app = pyrogram.Client(...)
@app.message(...)
def sync_handler(client, message):
    message.reply()  # works very poorly / incorrectly / does not work

async def main():
    await app.start()
    await some_blocking_call()
if __name__ == '__main__':
    asyncio.run(main())

A workaround is to add the following calls to the main function:

async def main():
    pyrogram.sync.unwrap()
    pyrogram.sync.wrap()
    await app.start()
    await some_blocking_call()

@Danstiv Danstiv marked this pull request as ready for review January 4, 2025 18:24
@Danstiv
Copy link
Author

Danstiv commented Jan 7, 2025

@KurimuzonAkuma

Avoid direct asyncio loop interaction where possible to increase the flexibility of the initialization code.

For example, this code now works:
```
import asyncio
import pyrogram
from pyrogram import filters

app = pyrogram.Client(
    "telegram_account",
    api_id=...,
    api_hash=...,
    bot_token=...,
)

@app.on_message(filters.command("start"))
async def on_start(client, message):
    await message.reply("Working")

async def main():
    await app.start()
    print((await app.get_me()).username)
    await asyncio.Event().wait()

if __name__ == "__main__":
    asyncio.run(main())
```
@Danstiv
Copy link
Author

Danstiv commented Feb 16, 2025

I have rebased and manually reread resulting diff. Looks fine.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants