rlms
rlms

Reputation: 11060

Using Python to communicate with a minecraft server

This question was deleted when I was just about to answer it with some relevant information. I thought that, although it was phrased in a way which made people dislike it, and no code was posted, it was a useful question. As such, I decided to post it here, along with my partial answer. The current code I have has a problem with it, if anyone knows a solution I would be glad to hear it. Also, if anyone knows a cleaner solution (e.g. using the communicate method of Popen objects), that would be good too.

As I remember it, the relevant part of the question was this:

How can I use Python to communicate with a Minecraft server? I have a user interface set up, but I am unsure how I can connect to the server and send commands through to it.

Upvotes: 2

Views: 5879

Answers (3)

qreodium
qreodium

Reputation: 63

https://github.com/Fallen-Breath/MCDReforged

MCDReforged (abbreviated as MCDR) is a tool which provides the management ability of the Minecraft server using custom plugin system. It doesn't need to modify or mod the original Minecraft server at all

Upvotes: 1

Samuelzila
Samuelzila

Reputation: 162

Here is the code I'm using, I edited rlms' code a little bit to fix the readline problem:

import os, sys, time
import subprocess

server = subprocess.Popen('./start.sh',stdin=subprocess.PIPE,shell=True)
content = ''
previousContent = ''
while True:
#you can add a time.sleep() to reduce lag   
f = open('logs/latest.log')
    content = f.read()
    if previousContent in content:
        content.replace(previousContent,'')
        if content != '':
            print(content)

    command = input('')
    if command:
        server.stdin.write(bytes(command + '\r\n', 'ascii'))
        server.stdin.flush()
   previousContent = f.read()

Upvotes: 1

rlms
rlms

Reputation: 11060

Here is my current solution to this problem. It allows communication with the server easily, but has the problem of hanging on calls to readline when there are no more lines to read. If anyone knows how to solve this, I would be grateful for them telling me.:

from subprocess import Popen, PIPE, STDOUT
server = Popen("java -jar minecraft_server.1.7.4.jar nogui", stdin=PIPE, stdout=PIPE, stderr=STDOUT)
while True:
    print(server.stdout.readline())
    server.stdout.flush()
    command = input("> ")
    if command:
        server.stdin.write(bytes(command + "\r\n", "ascii"))
        server.stdin.flush()

Please note that for this code to work as is, the script must be in the same directory as the server.

Upvotes: 0

Related Questions