1
0
Fork 0
matrix-appservice-minecraft/wrapper.py

130 lines
4.0 KiB
Python
Raw Normal View History

2020-04-02 08:33:34 +02:00
import argparse
import logging
2020-04-03 08:27:05 +02:00
import json
2020-04-02 08:33:34 +02:00
import re
import subprocess
import threading
from typing import List
import message_queue
LOG = logging.getLogger(__name__)
class ProcessWrapper:
"""Iterator that spawns a process and yields lines from its stdout."""
def __init__(self, command: List[str]):
2020-04-02 08:33:34 +02:00
self.proc = subprocess.Popen(
" ".join(command),
shell=True,
stdout=subprocess.PIPE,
stdin=subprocess.PIPE,
universal_newlines=True,
)
def __iter__(self):
return iter(self.proc.stdout.readline, "")
def send(self, msg):
self.proc.stdin.write(msg)
2020-04-03 05:53:24 +02:00
self.proc.stdin.flush()
2020-04-02 08:33:34 +02:00
def wait(self):
return self.proc.wait()
2020-04-03 06:52:36 +02:00
@property
def closed(self) -> bool:
return self.proc.returncode is not None
2020-04-02 08:33:34 +02:00
def send_process_output(
process: ProcessWrapper, msg_queue: message_queue.MessageQueue
):
2020-04-03 06:52:36 +02:00
log = LOG.getChild("process_output")
2020-04-03 08:20:38 +02:00
# "[07:36:28] [Server thread/INFO] [minecraft/DedicatedServer]: <khr_> test"
chat_pattern = re.compile(r"(\[.*\] )?\[(.*)\] \[(.*)\]: <(.*)> (.*)")
# "[05:09:54] [Server thread/INFO] [minecraft/DedicatedServer]: khr_ joined the game"
2020-04-03 08:39:22 +02:00
login_pattern = re.compile(r"\[.*\] \[(.*)\] \[(.*)\]: (\S*) joined the game")
2020-04-03 08:20:38 +02:00
# "[05:12:24] [Server thread/INFO] [minecraft/DedicatedServer]: khr_ left the game"
2020-04-03 08:39:22 +02:00
logout_pattern = re.compile(r"\[.*\] \[(.*)\] \[(.*)\]: (\S*) left the game")
2020-04-02 08:33:34 +02:00
for line in process:
2020-04-03 06:52:36 +02:00
log.info(line.rstrip("\n"))
2020-04-03 08:20:38 +02:00
chat_result = chat_pattern.search(line)
login_result = login_pattern.search(line)
logout_result = logout_pattern.search(line)
if chat_result:
2020-04-02 08:33:34 +02:00
msg_queue.add(
2020-04-03 08:23:25 +02:00
{
"user": chat_result.group(4),
"action": "chat",
"msg": chat_result.group(5).rstrip("\n"),
},
2020-04-02 08:33:34 +02:00
)
2020-04-03 08:20:38 +02:00
elif login_result:
2020-04-03 08:23:25 +02:00
msg_queue.add({"user": login_result.group(3), "action": "joined"})
2020-04-03 08:20:38 +02:00
elif logout_result:
2020-04-03 08:23:25 +02:00
msg_queue.add({"user": logout_result.group(3), "action": "left"})
2020-04-02 08:33:34 +02:00
def relay_queue_input(
process: ProcessWrapper, msg_queue: message_queue.MessageQueue
):
2020-04-03 05:53:24 +02:00
log = LOG.getChild("relay_input")
2020-04-03 06:52:36 +02:00
while not process.closed:
try:
for message in msg_queue:
log.debug(message)
2020-04-03 08:20:38 +02:00
if "msg" in message:
tellraw_params = {
"text": "<{}> {}".format(
message["user"], message["msg"]
),
"insertion": "/tellraw @p %s",
}
2020-04-03 08:27:05 +02:00
command = "/tellraw @a {}\n".format(
json.dumps(tellraw_params)
)
2020-04-03 06:52:36 +02:00
log.debug("forwarding to process: {!r}".format(command))
process.send(command)
else:
log.debug(message)
except Exception as e:
log.exception(e)
2020-04-02 08:33:34 +02:00
def main():
logging.basicConfig(level=logging.DEBUG)
parser = argparse.ArgumentParser()
parser.add_argument("--matrix_server", required=True)
2020-04-02 08:33:34 +02:00
parser.add_argument("--matrix_server_port", type=int, default=5001)
parser.add_argument("command", nargs=argparse.REMAINDER)
args = parser.parse_args()
LOG.info("Running Minecraft Server Wrapper")
wrapper = ProcessWrapper(args.command)
queue = message_queue.MessageQueue(
host=args.matrix_server,
port=args.matrix_server_port,
side=message_queue.Side.CLIENT,
)
send_worker = threading.Thread(
2020-04-02 08:33:49 +02:00
target=send_process_output, args=(wrapper, queue), daemon=True,
2020-04-02 08:33:34 +02:00
)
receive_worker = threading.Thread(
2020-04-02 08:33:49 +02:00
target=relay_queue_input, args=(wrapper, queue), daemon=True,
2020-04-02 08:33:34 +02:00
)
send_worker.start()
receive_worker.start()
LOG.info("All threads created")
send_worker.join()
receive_worker.join()
queue.close()
LOG.info("All threads terminated")
return wrapper.wait()
if __name__ == "__main__":
main()