Ask coding questions

← Back to all posts
Newline discord.py bot problem
dacoconutnut (1)

In this bot I`m making something like a python shell and when I enter this code:

the output is this:

No newlines are displayed, there sould be. I tried, no newlines are displayed in any cases in the "console"
The code for this command is at about line 484

Comments
hotnewtop
ChezCoder (1588)

You are piping stdout, which means the newline character (\n) is replaced with an actual newline whitespace. Now imagine how this would print in discord. Reading

llol
ygvbh

turns into

llol  ygvbh

One way to solve this would be to write the code the user sent into a file, and then pipe the bash console.

import os

# replace this with the username
username = "dacoconutnut"

# replace this with the code msg
msg = ["print('lol1\nlol2')", "print('this is line 2')", "print('last line!')"]

for i, line in enumerate(msg):
    # replace all newlines with escapped newline
    # then add a newline to end of the line

    msg[i] = line.replace("\n", "\\n") + "\n"

# write it to the py file
open(username + ".py", "w").writelines(msg)

# read the result of bash "python filename.py"
res = os.popen("python " + username + ".py").read()

# print the result
print("Result: \n" + str(res))
print("Raw Result String: \n" + repr(res))
dacoconutnut (1)

@ChezCoder newline whitespace is 2 spaces? Then I can just replace them with \n`s