python - 在 python 脚本中运行两个 asynco 循环(telethon,aiopg)
问题描述
我想使用 Telethon (Telegram bot) 和 aiopg (PostgreSQL) 库。
马拉松示例:
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 示例:
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(...),但我不知道如何结合这两个库,如何启动两个循环。你能帮我么?
解决方案
创建一个新的异步函数,它创建一个新的客户端实例并添加您需要的所有处理程序,为了这个示例,我展示了我的一些示例处理程序。
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
然后是你的主要功能
client = await init_bot()
await client.connect()
# the below code is non-blocking
asyncio.create_task(client.run_until_disconnected())
推荐阅读
- permissions - 清空项目的“浏览权限”后,如何设置项目的“浏览权限”?
- modelica - 在 Modelica 中创建一个包
- php - 使用 PHP 或浏览器访问 NodeJS 模块创建的文件
- apache - 找不到页面 Shibboleth.sso/SAML2/POST
- android - Room 在使用 Live Data 时返回 Null 值,但在未使用 Livedata 包装时返回 Proper 值
- html - 从网站获取正确的音频流元数据(专辑、艺术家、歌曲)以通过蓝牙显示
- javascript - 将中间件添加到事件
- php - Symfony 分析器的执行时间不正确?
- javascript - 如何通过 Javascript 按 3 列对数组进行排序?
- python - Pickle 说它不能腌制 pygame.surface,但我的对象不是 pygame.surface