首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在python脚本(telethon,aiopg)中运行两个异步循环

在python脚本(telethon,aiopg)中运行两个异步循环
EN

Stack Overflow用户
提问于 2021-02-15 04:36:50
回答 1查看 440关注 0票数 0

我想使用Telethon (Telegram bot)和aiopg (PostgreSQL)库。

Telethon示例:

代码语言:javascript
复制
from telethon import TelegramClient
api_id = 12345
api_hash = '0123456789abcdef0123456789abcdef'
client = TelegramClient('anon', api_id, api_hash)
async def main():
    # Getting information about yourself
    me = await client.get_me()
    print(me.stringify())

@client.on(events.NewMessage)
async def my_event_handler(event):
    if 'hello' in event.raw_text:
        await event.reply('hi!')

client.start()
client.run_until_disconnected()

aiopg示例:

代码语言:javascript
复制
import aiopg

dsn = 'dbname=aiopg user=aiopg password=passwd host=127.0.0.1'


async def notify(conn):
    async with conn.cursor() as cur:
        for i in range(5):
            msg = "message {}".format(i)
            print('Send ->', msg)
            await cur.execute("NOTIFY channel, %s", (msg,))

        await cur.execute("NOTIFY channel, 'finish'")


async def listen(conn):
    async with conn.cursor() as cur:
        await cur.execute("LISTEN channel")
        while True:
            msg = await conn.notifies.get()
            if msg.payload == 'finish':
                return
            else:
                print('Receive <-', msg.payload)


async def main():
    async with aiopg.create_pool(dsn) as pool:
        async with pool.acquire() as conn1:
            listener = listen(conn1)
            async with pool.acquire() as conn2:
                notifier = notify(conn2)
                await asyncio.gather(listener, notifier)
    print("ALL DONE")


loop = asyncio.get_event_loop()
loop.run_until_complete(main())

我想在同一个python脚本中使用这两个脚本。我试图找到解决方案,可能是asyncio.gather(...),但我不知道如何将这两个库结合起来,如何启动这两个循环。你能帮帮我吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-04-23 18:31:38

创建一个新的异步函数,该函数创建一个新的客户端实例,并添加您需要的所有处理程序,在此示例中,我展示了我的一些示例处理程序。

代码语言:javascript
复制
async def init_bot() -> TelegramClient:
    client = TelegramClient(
                 session="trade-bot",
                 api_hash=Config.API_HASH,
                 api_id=Config.API_ID,
             )
    await client.start(bot_token=Config.BOT_TOKEN)

    client.add_event_handler(
        register_handler,
        events.NewMessage(incoming=True, pattern=r"^[\/?!]register$"),
    )
    client.add_event_handler(
        get_webhook_handler,
        events.NewMessage(incoming=True, pattern=r"^[\/?!]webhook$"),
    )
    client.add_event_handler(
        status_handler,
        events.NewMessage(incoming=True, pattern=r"^[\/?!]status$"),
    )
    _LOG.info("Bot client started")
    return client

然后在后面的main函数中

代码语言:javascript
复制
client = await init_bot()
await client.connect()
# the below code is non-blocking
asyncio.create_task(client.run_until_disconnected())
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66199874

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档