python Pyrogram:如何在FastAPI路由器中运行异步方法

lstz6jyr  于 2022-10-30  发布在  Python
关注(0)|答案(1)|浏览(231)

如何在FastApi路线中运行热解图方法?

我使用Pyrogram,我有一些处理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)

            logging.INFO()
            return messages

        except Exception as e:
            return e

为了运行这些方法,我使用了pyrogram客户端中的内置run函数

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

Run方法示例:

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

我想在fastapi路由器中运行我的pyrogram方法,我怎么能做到这一点呢?我正在尝试这一点,但没有消息被打印到终端:

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

如何在fastapi中从pyrogram方法中获取输出?

h79rfbju

h79rfbju1#

尝试tris代码

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")

相关问题