Python 使用带有异步Discord.py的同步库

Python 使用带有异步Discord.py的同步库,python,python-asyncio,discord.py,steemit,Python,Python Asyncio,Discord.py,Steemit,我正在开发一个机器人,它使用同步beem库从Steem区块链流式传输帖子,并使用asynchronous Discord.py库将满足某些标准的帖子发送到Discord通道。这是我的简化代码: bot = commands.Bot(command_prefix="!") async def send_discord(msg): await bot.wait_until_ready() await bot.send_message(bot.get_channel("mychann

我正在开发一个机器人,它使用同步beem库从Steem区块链流式传输帖子,并使用asynchronous Discord.py库将满足某些标准的帖子发送到Discord通道。这是我的简化代码:

bot = commands.Bot(command_prefix="!")

async def send_discord(msg):
    await bot.wait_until_ready()
    await bot.send_message(bot.get_channel("mychannelid"), msg)

async def scan_post(post):
    """Scan queued Comment objects for defined patterns"""
    post.refresh()
    if post["author"] == "myusername":
        await loop.create_task(send_discord("New post found"))

async def start_blockchain():
    stream = map(blockchain.stream(opNames=["comment"]))
    for post in stream:
        await loop.create_task(scan_post(post))

if __name__ == '__main__':
    while True:
        loop.create_task(start_blockchain())
        try:
            loop.run_until_complete(bot.start(TOKEN))
        except Exception as error:
            bot.logout()
            logger.warning("Bot restarting "+repr(error))

在实现discord.py之前,我只需要调用同步函数scan_postpost,它工作得很好,但是现在使用异步实现时,POST的处理速度不够快,流的延迟迅速增加。如果我使scan_post成为一个同步函数,处理时间就可以了,但是Discord websocket会关闭,甚至不会打开,bot会离线。如何在不重写beem库的情况下以简单的方式解决这个问题?

我解决了这个问题:我在自己的线程中运行beem流,在第二个线程中运行异步函数。使用该库,我可以将beam线程中的对象添加到由异步线程处理的队列中。

blockchain.stream调用也是阻塞的,还是仅仅是post.refresh?还有,mapblockchain.stream。。。看起来不正确-映射至少包含两个参数。对于异步代码中的阻塞操作,您可以使用run_in_executor so,这样它们就不会阻塞整个线程。文档中也有有用的示例。