I created a command to do math using Sympy. The problem is that if I put something that needs a lot of calculation (Like for example 9999999**999999) the bot freezes completely until the message with the result is sent.
This is my code:
@client.command(name="math")
async def math_command(ctx, calc = None):
if calc == None:
return
try:
result = sympy.sympify(calc)
await ctx.reply(f"Result: {result}")
except:
await ctx.reply("Invalid")
CodePudding user response:
As Lukas Thaler said, sympy is a synchronous library and it's not meant to be used within asynchronous code, you can however use the loop.run_in_executor method to run it in a non-blocking way:
import asyncio
from functools import partial
loop = asyncio.get_event_loop() # in py 3.10 use `asyncio.get_running_loop()`
async def run_blocking(func, *args, **kwargs):
"""Run any blocking, synchronous function in a non-blocking way"""
callback = partial(func, *args, **kwargs)
return await loop.run_in_executor(None, callback)
# inside the command
result = await run_blocking(sympy.sympify, calc)
