【发布时间】:2021-05-17 20:36:05
【问题描述】:
我想使用 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(...),但我不知道如何结合这两个库,如何启动两个循环。 你能帮帮我吗?
【问题讨论】:
-
我认为您正在寻找
asyncio.create_task()、here,您可以找到有关其工作原理的更多详细信息。 -
@TheKill-996 谢谢,是的。我找到了这样的例子: loop.create_task(client.get_messages('telegram', 10)) loop.create_task(client.send_message('me', 'Using asyncio!')) loop.create_task(client.download_profile_photo('telegram ')) 但这些只是“命令”,我不知道,我怎样才能接收到这样的事件:@client.on(events.NewMessage) async def my_event_handler(event): if 'hello' in event.raw_text: await event.reply('hi!') 对不起,我不完全理解整个异步的东西。
-
像
client.on(events.NewMessage)这样的装饰器只是调用add_event_handler的一种便捷方式。你可以在你的设置代码中直接调用它。 -
请注意,
client.start()和client.run_until_disconnected()都可以是await-ed,如果您在async def中。您已经在使用asyncio.gather,因此您还可以在一些asyncio def中设置客户端并将所有代码收集在一起。 Asyncio 文档值得一读。
标签: python python-asyncio telethon aiopg