0

I want to make a Discord bot to manage my Minecraft server for me and my friends, and I have a command to startup the server via subprocess, and to print the "server.jar" file's output into the python console. However, when attempting to send it to a specific channel within my Discord server, it fails to do so, but returns no error. If I stop the subprocess running the Minecraft server, the bot goes back online, but until then no command works, and it eventually goes offine. The command in question looks like the following:

@client.command()
async def start(ctx):
    await client.change_presence(status=discord.Status.idle)
    process = subprocess.Popen(["java", "-Xmx1024M", "-Xms1024M", "-jar", "server.jar", "nogui"], stdout=subprocess.PIPE, universal_newlines=True)
    while True:
        output = process.stdout.readline()
        print(output.strip())
        return_code = process.poll()
        if return_code is not None:
            for output in process.stdout.readlines():
                print(output.strip())
                tchannel = client.get_channel(967379407431925821)
                await tchannel.send(output.strip())
                if "Done" in output.strip():
                    ip = get('https://api.ipify.org')
                    await ctx.send("Done! Server Live on: "+ str(ip))
            break

Any help is greatly appreciated, thanks!

  • 1
    This is not a good idea to spawn a large process like a server and tie it to the discord bot. Instead, try opening its log file (in logs/latest.log) and doing `readline` on that. – Eric Jin Apr 26 '22 at 17:42
  • Thanks for the response! This is actually a good idea, but I still want to communicate with the server console, so I can stop it correctly. – user17004077 Apr 27 '22 at 14:18
  • You can redirect stdin with it, or, as I would suggest, run it in a multiplexer like `tmux` and send input through there. This also lets you manually control it. (Also, why is there no error? What happens if you control c? Does `Popen` block asyncio?) – Eric Jin Apr 27 '22 at 14:31
  • Stopping the code prematurely, stops the python program with no errors but leaves the server running. Although, If I would know why that happens I would not really be asking this question... Is it possible that running the server and the bot in different threads would fix the issue? – user17004077 Apr 27 '22 at 18:47
  • `process.stdout.readline()` is probably permanently blocking. You will need to find asyncio version of this, or use multiprocessing/threads as you said. [This answer](https://stackoverflow.com/questions/47184177/how-do-i-use-asyncio-and-gui-to-read-a-file) might help. – Eric Jin Apr 27 '22 at 20:15
  • Thank you very much, I think I solved the issue with threads, it seems to be working just fine now. – user17004077 Apr 28 '22 at 18:18

0 Answers0