1

How i can run pyrogram method in FastApi routes?

I use Pyrogram and i have some methods for working with Telegram.

class UserBot: 
     def __init__(self, username: str, debug: Optional[bool] = False) -> None:
        self.username = username
        self.app = Client(f"sessions/{username}")

# For example get chat history (https://docs.pyrogram.org/api/methods/get_chat_history)
    async def get_chat_history(self, chat_id: str) -> "List of chat messages":
        try:
            messages = list()
            async with self.app as app:
                async for message in app.get_chat_history(chat_id):
                    print(message)
                    messages.append(message)

            logging.INFO()
            return messages

        except Exception as e:
            return e

To run the methods, I use the built-in run function in the pyrogram Client

    async def loop_methods(self, fn):
        try:
            self.app.run(fn)
            logging.INFO()
        except Exception as e:
            return e

Run method example:

ubot = UserBot(username="donqhomo", debug=False)
ubot.loop_methods(ubot.get_chat_history(chat_id="@CryptoVedma"))

I want to run my pyrogram method in fastapi router, how i can do this? I'm try this, but no messages were printed to the terminal:

from fastapi import FastAPI, HTTPException
import asyncio

app = FastAPI()

@app.get("/test/")
async def test():
    ubot = UserBot(username="donqhomo", debug=False)

    loop = asyncio.get_running_loop()
    task1 = loop.create_task(ubot.get_chat_history(chat_id="@CryptoVedma"))
    await task1

    return task1

And how i can take output from pyrogram method in fastapi?

Иван
  • 158
  • 2
  • 12
  • Instead of running the bot inside FastAPI, it's usually a better approach to run the bot in a separate process and then exchange messages through a database/queuesystem (sqlite, redis, or similar). But first; does this give you expected messages back if you run it _outside_ of the FastAPI context with the exact same arguments? – MatsLindh Oct 29 '22 at 10:46

1 Answers1

0

try tris code

from fastapi import FastAPI, HTTPException
import asyncio

app = FastAPI()

@app.get("/test/")
async def test():
    ubot = UserBot(username="donqhomo", debug=False)
    return await bot.get_chat_history(chat_id="@CryptoVedma")
Ryabchenko Alexander
  • 10,057
  • 7
  • 56
  • 88