-
Notifications
You must be signed in to change notification settings - Fork 0
/
mcchat.py
executable file
·224 lines (189 loc) · 7.21 KB
/
mcchat.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
#!/usr/bin/env python2.7
# coding=utf8
from __future__ import print_function
import re
import sys
import time
import os.path
import threading
import traceback
import socket
import argparse
from McClient.networking.NetworkHelper import NetworkHelper
from McClient.networking.Connection import Connection
from McClient.networking.Receiver import BaseReceiver
from McClient.networking.Receiver import Receiver
from McClient.networking.Sender import Sender
from McClient.networking.Exceptions import HandlerError
from McClient.Events import EventManager
from McClient import Utils
from McClient.networking.Session import OfflineSession
from McClient.networking.Session import Session
from MC2Session import MC2Session
from minecraft_query import MinecraftQuery
import JSONChat
#==============================================================================#
DEFAULT_PORT = 25565
#==============================================================================#
def with_global_lock(func):
def decorated(*args, **kwds):
with global_lock: func(*args, **kwds)
return decorated
NetworkHelper.respondFD = with_global_lock(NetworkHelper.respondFD)
NetworkHelper.respondFC = with_global_lock(NetworkHelper.respondFC)
NetworkHelper.respond00 = with_global_lock(NetworkHelper.respond00)
def fprint(*args, **kwds):
print(*args, **kwds)
kwds.get('file', sys.stdout).flush()
def eprint(*args, **kwds):
fprint(*args, file=sys.stderr, **kwds)
def run_command(cmd):
try: exec cmd
except Exception: traceback.print_exc()
for f in sys.stdout, sys.stderr: f.flush()
#==============================================================================#
arg_parser = argparse.ArgumentParser()
arg_parser.add_argument(
'address', metavar='HOST[:PORT]',
help='The Minecraft server to connect to.')
arg_parser.add_argument(
'username', metavar='USERNAME',
help='Username to connect as.')
arg_parser.add_argument(
'password', metavar='PASSWORD', nargs='?',
help='Password to authenticate with, if any.')
arg_parser.add_argument(
'auth_server', metavar='AUTH_SERVER|offline', nargs='?',
help='A custom (Mineshafter Squared) authentication server.')
arg_parser.add_argument(
'--protocol', metavar='VERSION', type=int,
help='The protocol version to report to the Minecraft server.')
args = arg_parser.parse_args()
#==============================================================================#
address = args.address.rsplit(':', 1)
if len(address) == 2:
host, port = address[0], int(address[1])
else:
host, port = address[0], DEFAULT_PORT
global_lock = threading.Lock()
global_cond = threading.Condition(global_lock)
position_and_look = None
connection = None
players = set()
connected = False
protocol = Sender.protocol_version = args.protocol or Sender.protocol_version
#==============================================================================#
class Client(object):
@staticmethod
def recv_login_request(*args, **kwds):
global connected
with global_lock:
connected = True
fprint('Connected to server.')
@staticmethod
def recv_chat_message(message):
if protocol >= 72:
message = JSONChat.decode_string(message)
# Support Bukkit's xAuth plugin.
if args.password and message.startswith(u'§c'):
for cmd in u'/register', u'/login':
if cmd not in message: continue
with global_lock: connection.sender.send_chat_message(
'%s %s' % (cmd, args.password))
message = re.sub(ur'^§[ac]', '! ', message)
message = re.sub(ur'§.', '', message)
with global_lock: fprint(message)
@staticmethod
def recv_player_position_and_look(**kwds):
global position_and_look
with global_lock: position_and_look = kwds
@staticmethod
def recv_client_disconnect(reason):
global connected
with global_lock:
fprint('Disconnected from server: %s' % reason,
file=sys.stdout if connected else sys.stderr)
connected = False
sys.exit()
@staticmethod
def recv_player_list_item(player_name, online, ping):
with global_lock:
if online: players.add(player_name)
else: players.remove(player_name)
#==============================================================================#
def run_send_position():
while True:
time.sleep(0.05)
with global_lock:
if position_and_look is None: continue
connection.sender.send_player_position_and_look(**position_and_look)
send_position = threading.Thread(target=run_send_position, name='send_position')
send_position.daemon = True
send_position.start()
#==============================================================================#
query_pending = set()
def query(key):
if key == 'players' and connected:
fprint('!query success players %s' % ' '.join(players))
else:
query_pending.add(str(key))
global_cond.notifyAll()
@with_global_lock
def run_query():
while True:
while not query_pending: global_cond.wait()
pending = query_pending.copy()
query_pending.clear()
for key in pending: fprint('!query pending %s' % key)
global_lock.release()
try:
status = MinecraftQuery(host, port, timeout=1, retries=5).get_rules()
global_lock.acquire()
for key in pending:
if key in status:
val = status[key]
if type(val) is list: val = ' '.join(val)
fprint('!query success %s %s' % (key, val))
else:
fprint('!query failure %s no such key' % key)
except socket.timeout as e:
global_lock.acquire()
for key in pending: fprint('!query failure %s %s' % (key, str(e)))
query_server = threading.Thread(target=run_query, name='query_server')
query_server.daemon = True
query_server.start()
if args.auth_server == 'offline' or args.password is None:
session = OfflineSession()
elif args.auth_server is None:
session = Session()
else:
session = MC2Session(args.auth_server)
session.connect(args.username, args.password)
connection = Connection(session, EventManager, Receiver, Sender)
connection.name = 'connection'
connection.eventmanager.apply(Client)
connection.connect(host, port)
#==============================================================================#
def run_read_stdin():
while True:
msg = raw_input().decode('utf8')
with global_lock:
if msg.startswith('?'):
run_command(msg[1:])
continue
while len(msg) > 100:
connection.sender.send_chat_message(msg[:97] + '...')
msg = '...' + msg[97:]
if msg: connection.sender.send_chat_message(msg)
read_stdin = threading.Thread(target=run_read_stdin, name='read_stdin')
read_stdin.daemon = True
read_stdin.start()
#==============================================================================#
try:
while connection.is_alive():
connection.join(0.1)
except KeyboardInterrupt:
connection.disconnect()
with global_lock:
if connected:
fprint('Disconnected from server.')