|
|
|
@ -3,34 +3,40 @@ import json |
|
|
|
|
from minecraft.networking.packets import clientbound, serverbound |
|
|
|
|
|
|
|
|
|
class ChatManager: |
|
|
|
|
def __init__(self, global_state): |
|
|
|
|
self.g = global_state |
|
|
|
|
self.handler = None |
|
|
|
|
|
|
|
|
|
def __init__(self): |
|
|
|
|
return |
|
|
|
|
self.g.connection.register_packet_listener(self.print_chat, clientbound.play.ChatMessagePacket) |
|
|
|
|
|
|
|
|
|
def translate_chat(self, data): |
|
|
|
|
if isinstance(data, str): |
|
|
|
|
return data |
|
|
|
|
elif 'extra' in data: |
|
|
|
|
return "".join([self.translate_chat(x) for x in data['extra']]) |
|
|
|
|
return ''.join([self.translate_chat(x) for x in data['extra']]) |
|
|
|
|
elif 'text' in data: |
|
|
|
|
return data['text'] |
|
|
|
|
else: |
|
|
|
|
return "?" |
|
|
|
|
return '?' |
|
|
|
|
|
|
|
|
|
def print_chat(self, chat_packet): |
|
|
|
|
# TODO: Replace with handler |
|
|
|
|
try: |
|
|
|
|
print("[%s] %s"%(chat_packet.field_string('position'), self.translate_chat(json.loads(chat_packet.json_data)))) |
|
|
|
|
source = chat_packet.field_string('position') |
|
|
|
|
text = self.translate_chat(json.loads(chat_packet.json_data)) |
|
|
|
|
print('[%s] %s'%(source, text)) |
|
|
|
|
if self.handler: |
|
|
|
|
self.handler((source, text)) |
|
|
|
|
except Exception as ex: |
|
|
|
|
print("Exception %r on message (%s): %s" % (ex, chat_packet.field_string('position'), chat_packet.json_data)) |
|
|
|
|
|
|
|
|
|
def register(self, connection): |
|
|
|
|
connection.register_packet_listener(self.print_chat, clientbound.play.ChatMessagePacket) |
|
|
|
|
|
|
|
|
|
def send(self, connection, text): |
|
|
|
|
print('Exception %r on message (%s): %s' % (ex, chat_packet.field_string('position'), chat_packet.json_data)) |
|
|
|
|
|
|
|
|
|
def set_handler(self, func): |
|
|
|
|
self.handler = func |
|
|
|
|
|
|
|
|
|
def send(self, text): |
|
|
|
|
if not text: |
|
|
|
|
# Prevents connection bug when sending empty chat message |
|
|
|
|
return |
|
|
|
|
packet = serverbound.play.ChatPacket() |
|
|
|
|
packet.message = text |
|
|
|
|
connection.write_packet(packet) |
|
|
|
|
self.g.connection.write_packet(packet) |
|
|
|
|