Pull chat manager file over from Elektordi/pyCraft

This commit is contained in:
Tanner Collin 2020-09-06 16:43:20 -06:00
parent 7d93888798
commit 04cd44fa72
3 changed files with 41 additions and 8 deletions

View File

@ -1,2 +1,3 @@
from .data import DataManager from .data import DataManager
from .chunks import ChunksManager from .chunks import ChunksManager
from .chat import ChatManager

36
custom/managers/chat.py Normal file
View File

@ -0,0 +1,36 @@
import json
from minecraft.networking.packets import clientbound, serverbound
class ChatManager:
def __init__(self):
return
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']])
elif 'text' in data:
return data['text']
else:
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))))
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):
if not text:
# Prevents connection bug when sending empty chat message
return
packet = serverbound.play.ChatPacket()
packet.message = text
connection.write_packet(packet)

12
main.py
View File

@ -5,7 +5,7 @@ USERNAME = ''
PASSWORD = '' PASSWORD = ''
SERVER = '' SERVER = ''
from custom.managers import DataManager, ChunksManager from custom.managers import DataManager, ChunksManager, ChatManager
from minecraft import authentication from minecraft import authentication
from minecraft.exceptions import YggdrasilError from minecraft.exceptions import YggdrasilError
@ -35,16 +35,12 @@ def main():
connection.register_packet_listener( connection.register_packet_listener(
handle_join_game, clientbound.play.JoinGamePacket) handle_join_game, clientbound.play.JoinGamePacket)
def print_chat(chat_packet):
print("Message (%s): %s" % (
chat_packet.field_string('position'), chat_packet.json_data))
connection.register_packet_listener(
print_chat, clientbound.play.ChatMessagePacket)
chunks = ChunksManager(mcdata) chunks = ChunksManager(mcdata)
chunks.register(connection) chunks.register(connection)
chat = ChatManager()
chat.register(connection)
connection.connect() connection.connect()
print('connected') print('connected')