0

I'm trying to make discord bot execute python code line by line similar to python interactive shell

Everything works fine but I have some problems with loops

Instead of printing i one by one, and waiting second between them, it print 0 to 9 instantly

There is a simplified example:

if 'q' in message.content:
   redirected_output = sys.stdout = StringIO()
   exec('for i in range(10):\n   print(i)\n   time.sleep(1)')
if redirected_output.getvalue():
   await message.channel.send(f'`{redirected_output.getvalue()}`')

Video

Full code here

Issue

Attempt using asyncio.sleep inside of async exec

if 'q' in message.content:                               
   redirected_output = sys.stdout = StringIO()
   await aexec('for i in range(10):\n   print(i)\n   await asyncio.sleep(1)')
   if redirected_output.getvalue():
      await message.channel.send(f'`{redirected_output.getvalue()}`')

Result is same, it print from 0 to 9 instantly

11
  • Please don't put all the details in links. You're only executing send once, at the bottom, not each time. Is there a reason that you must eval it? There's nothing dynamic in there, just write it as normal code. Also use asyncio.sleep not time.sleep Commented Jul 20, 2022 at 21:04
  • Yes I must use eval (exec) because I'm getting code as string from Discord messages. Also I cannot call asyncio.sleep inside because it's throw SyntaxError: 'await' outside async function Commented Jul 20, 2022 at 22:06
  • Maybe I can try with async exec But it's not what I wanted, it's still doesn't work using time.sleep Commented Jul 20, 2022 at 22:20
  • Please dont. Why do you need to exec it? The same problem is there - you’re sending the message once at the end from your output buffer. (Why do you need file-like io for that anyway?) Commented Jul 21, 2022 at 2:07
  • So different approach, What u suggest? I need exec` to execute python code from string come from Discord mesage and redirect standard output to Discord. Commented Jul 21, 2022 at 4:51

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.