Issue
I am writing a bot in aiogram and I want to use a function from a third-party library. The function fun()
works for a very long time, and blocks the execution of the entire code (while it is being executed, the bot cannot respond to other users). It is impossible to rewrite this library into asynchronous code. How do I make that the function does not block all the code?
import ...
import example_library
bot = Bot(token=TOKEN)
dp = Dispatcher(bot, storage=storage)
async def on_startup(_):
print("bot is online")
@dp.message_handler(commands=['start'])
async def process_start_command(message: types.Message):
await bot.send_message(msg.from_user.id, msg.text)
await example_library.fun(*args, **kwargs) ### block function, works for a long time
if __name__ == '__main__':
executor.start_polling(dp, skip_updates=True, on_startup=on_startup)
Solution
as I expected, everything is done in one line:
@dp.message_handler(commands=['start'])
async def process_start_command(message: types.Message):
await bot.send_message(msg.from_user.id, msg.text)
await asyncio.get_running_loop().run_in_executor(None, example_library.fun, *args, **kwargs)
Answered By - vsudarik
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.