pyCraft/start.py

88 lines
2.6 KiB
Python
Raw Normal View History

2012-04-05 04:56:21 +02:00
import getpass
import sys
from optparse import OptionParser
2014-10-08 19:12:37 +02:00
from minecraft import authentication
from minecraft.exceptions import YggdrasilError
2015-04-01 17:19:12 +02:00
from minecraft.networking.connection import Connection
from minecraft.networking.packets import ChatMessagePacket, ChatPacket
2015-04-06 02:11:26 +02:00
from minecraft.compat import input
2012-04-30 19:05:06 +02:00
2014-10-08 19:12:37 +02:00
def get_options():
parser = OptionParser()
2012-12-25 21:38:02 +01:00
parser.add_option("-u", "--username", dest="username", default=None,
2014-10-08 19:12:37 +02:00
help="username to log in with")
2012-12-25 21:38:02 +01:00
parser.add_option("-p", "--password", dest="password", default=None,
2014-10-08 19:12:37 +02:00
help="password to log in with")
2012-12-25 21:38:02 +01:00
parser.add_option("-s", "--server", dest="server", default=None,
2014-10-08 19:12:37 +02:00
help="server to connect to")
2012-12-25 21:38:02 +01:00
parser.add_option("-o", "--offline", dest="offline", action="store_true",
help="connect to a server in offline mode")
(options, args) = parser.parse_args()
2012-12-25 21:38:02 +01:00
if not options.username:
2015-04-06 02:11:26 +02:00
options.username = input("Enter your username: ")
if not options.password and not options.offline:
options.password = getpass.getpass("Enter your password: ")
2012-12-25 21:38:02 +01:00
if not options.server:
2015-04-06 02:11:26 +02:00
options.server = input("Please enter server address"
" (including port): ")
# Try to split out port and address
if ':' in options.server:
server = options.server.split(":")
options.address = server[0]
options.port = int(server[1])
else:
options.address = options.server
options.port = 25565
return options
def main():
options = get_options()
if options.offline:
print("Connecting in offline mode")
connection = Connection(
options.address, options.port, username=options.username)
else:
auth_token = authentication.AuthenticationToken()
try:
auth_token.authenticate(options.username, options.password)
except YggdrasilError as e:
print(e)
sys.exit()
print("Logged in as " + auth_token.username)
connection = Connection(
options.address, options.port, auth_token=auth_token)
connection.connect()
def print_chat(chat_packet):
print("Position: " + str(chat_packet.position))
print("Data: " + chat_packet.json_data)
connection.register_packet_listener(print_chat, ChatMessagePacket)
while True:
try:
2015-04-06 02:11:26 +02:00
text = input()
packet = ChatPacket()
packet.message = text
connection.write_packet(packet)
except KeyboardInterrupt:
print("Bye!")
sys.exit()
if __name__ == "__main__":
2015-04-06 02:11:26 +02:00
main()