我正在开发一个机器人,该机器人可以流式传输来自Steem区块链的帖子(使用同步beem库),并将满足某些条件的帖子发送到Discord通道(使用异步Discord.py库)。这是我的(简化)代码:
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_post(post)
,它就可以正常工作,但是现在通过异步实现,帖子的处理速度不够快,并且流的延迟迅速增加。如果我将scan_post(post)
设为同步函数,则处理时间很好,但是Discord网络套接字关闭(甚至没有打开),并且该机器人已脱机。我如何以简单的方式解决此问题(无需重写beem库)?