コード例 #1
0
def setup_connection(address, port, version, auth_token, state, username=None):
    connection = Connection(
        address,
        port,
        auth_token=auth_token,
        initial_version=version,
        username=username,
        handle_exception=partial(handle_exception, state=state),
    )
    print_timestamped(f"Connecting to {address}:{port}")

    # Cast rod on join
    connection.register_packet_listener(partial(handle_join_game, state=state),
                                        clientbound.play.JoinGamePacket)

    # Reel in and recast rod on bobber splash
    connection.register_packet_listener(
        partial(handle_sound_play, state=state),
        clientbound.play.SoundEffectPacket)

    if state["sleep_helper"]:
        # Disconnect for a while when people need to sleep
        connection.register_packet_listener(partial(handle_chat, state=state),
                                            clientbound.play.ChatMessagePacket)

    # Handle disconnects
    connection.register_packet_listener(partial(handle_dc, state=state),
                                        clientbound.play.DisconnectPacket)
    connection.register_packet_listener(partial(handle_dc, state=state),
                                        clientbound.login.DisconnectPacket)

    return connection
コード例 #2
0
ファイル: start.py プロジェクト: AsGreyWolf/pyCraft
def main():
    options = get_options()

    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)
    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:
            text = input()
            packet = ChatPacket()
            packet.message = text
            connection.write_packet(packet)
        except KeyboardInterrupt:
            print("Bye!")
            sys.exit()
コード例 #3
0
def startChat(update, context):
    usr = "******" + str(update.message.from_user.first_name)
    connection = Connection("ioya.de", username=usr)
    context.user_data["connection"] = connection

    id = update.effective_chat.id

    def handle_join_game(join_game_packet):
        print("handle_join_Game")
        context.bot.send_message(chat_id=id, text='Connected to Corona Land.')

    connection.register_packet_listener(handle_join_game,
                                        clientbound.play.JoinGamePacket)

    def print_chat(chat_packet):
        msg = json.loads(chat_packet.json_data)
        translate = msg["translate"]

        if translate == "chat.type.text":
            name = msg["with"][0]["text"]
            content = msg["with"][1]["text"]
            if name != usr:
                context.bot.send_message(chat_id=update.effective_chat.id,
                                         text="%s: %s" % (name, content))

    connection.register_packet_listener(print_chat,
                                        clientbound.play.ChatMessagePacket)

    connection.connect()
    return SENDMESSAGE
コード例 #4
0
def main():
    options = get_options()

    auth_token = authentication.AuthenticationToken()
    try:
        auth_token.authenticate(options.username, options.password)
    except YggdrasilError as e:
        print(e)
        sys.exit()
    connection = Connection(options.address, options.port, auth_token)
    connection.connect()

    print("Logged in as " + auth_token.username)

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind(("", 9001))
    s.listen(5)

    connection.register_packet_listener(print_chat,
                                        ChatMessageClientboundPacket)

    #send_message("GET http://www.google.com/ HTTP/1.1\r\nhost: www.google.com\r\n\r\n", "address", connection)  #GET http://www.uga.edu/ HTTP/1.1\r\nHost: www.uga.edu\r\n

    #time.sleep(100)

    #sys.exit()
    while True:
        try:
            (conn, addr) = s.accept()
            print("got packet")
            data = conn.recv(8192)
            send_message(data, addr, connection)
        except KeyboardInterrupt:
            sys.exit()
    s.close()
コード例 #5
0
ファイル: start.py プロジェクト: bridgar/Pickaxe
def main():
    options = get_options()

    auth_token = authentication.AuthenticationToken()
    try:
        auth_token.authenticate(options.username, options.password)
    except YggdrasilError as e:
        print(e)
        sys.exit()
    connection = Connection(options.address, options.port, auth_token)
    connection.connect()

    print("Logged in as " + auth_token.username)

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.bind(("", 9001))
    s.listen(5)

    connection.register_packet_listener(print_chat, ChatMessageClientboundPacket)

    #send_message("GET http://www.google.com/ HTTP/1.1\r\nhost: www.google.com\r\n\r\n", "address", connection)  #GET http://www.uga.edu/ HTTP/1.1\r\nHost: www.uga.edu\r\n

    #time.sleep(100)

    #sys.exit()
    while True:
        try:
            (conn, addr) = s.accept()
            print("got packet")
            data = conn.recv(8192)
            send_message(data, addr, connection)
        except KeyboardInterrupt:
            sys.exit()
    s.close()
コード例 #6
0
ファイル: start.py プロジェクト: virustotalop/pyCraft
def main():
    options = get_options()

    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)
    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:
            text = input()
            packet = ChatPacket()
            packet.message = text
            connection.write_packet(packet)
        except KeyboardInterrupt:
            print("Bye!")
            sys.exit()
コード例 #7
0
class MinecraftBot():
	def __init__(self, username, server, port, commands):
		self.username = username
		self.server = server
		self.port = port
		self.commands = commands
		self.bot = Connection(server, port, username=username, allowed_versions=[47])
		self.bot.register_packet_listener(self.handle_join_game, clientbound.play.JoinGamePacket)

		log("INFO", "Trying to connect {0} to {1}:{2}.".format(username, server, port))
		self.bot.connect()
		threading.Thread(target=self.execute_go, args=["/go"], daemon=True).start()

	def execute_go(self, command):
		time.sleep(15)
		self.execute_command(command)

	def handle_join_game(self, join_game_packet):
		log("INFO", "{0} is connected to {1}:{2}.".format(self.username, self.server, self.port))
		time.sleep(3)
		self.execute_command(self.commands[0])

	def execute_command(self, command):
		log("INFO", "{0} is doing command {1}".format(self.username, command))
		packet = serverbound.play.ChatPacket()
		packet.message = command
		self.bot.write_packet(packet)

	def disconnect(self):
		log("INFO", "Disconnecting {0} from {1}:{2}.".format(self.username, self.server, self.port))
		self.bot.disconnect()
		log("INFO", "{0} is disconnected of {1}:{2}.".format(self.username, self.server, self.port))
コード例 #8
0
def main():
    config = read_config()

    # split port and host
    match = re.match(
        r"((?P<host>[^\[\]:]+)|\[(?P<addr>[^\[\]]+)\])"
        r"(:(?P<port>\d+))?$", config["server"])
    if match is None:
        raise ValueError(f"Invalid server address: '{config['server']}'")
    address = match.group("host") or match.group("addr")
    port = int(match.group("port") or 25565)

    auth_token = authentication.AuthenticationToken()
    try:
        auth_token.authenticate(config["username"], config["password"])
    except YggdrasilError as e:
        print(e)
        sys.exit()
    print(f"Authenticated successfully as {auth_token.username}")
    connection = Connection(address, port, auth_token=auth_token)

    def handle_goodbye(signum, frame):
        print("Signing out!")
        payload = {
            'username': config["username"],
            'password': config["password"]
        }
        try:
            authentication._make_request(authentication.AUTH_SERVER, "signout",
                                         payload)
        except:
            print("Failed to sign out with Yggdrasil")
        finally:
            sys.exit()

    def handle_disconnect():
        print("Disconnected from server")
        if config["reconnect"] == True:
            connection.connect()
        else:
            sys.exit()

    connection.register_packet_listener(
        lambda packet: print(f"Connected to {address}!"),
        clientbound.play.JoinGamePacket)

    connection.register_packet_listener(handle_disconnect,
                                        clientbound.login.DisconnectPacket)

    try:
        connection.connect()
    except Exception as err:
        print(err)
        print("Failed to connect to specified server")
        sys.exit()

    signal.signal(signal.SIGINT, handle_goodbye)
    while True:
        time.sleep(1)
コード例 #9
0
ファイル: start.py プロジェクト: muddyfish/pyCraft
class Main(object):
    def __init__(self, options):
        self.auth_token = authentication.AuthenticationToken()
        try:
            self.auth_token.authenticate(options.username, options.password)
        except YggdrasilError as e:
            print(e)
            sys.exit()
        print("Logged in as " + self.auth_token.username)
        self.network = Connection(options.address, options.port, self.auth_token)
        self.network.connect()
        self.register_listeners()
        #sys.stdout = Speaker(self)
        while not self.network.playing: pass
        self.respawn()
        while True:
            try: self.tick()
            except KeyboardInterrupt:
                print("Bye!")
                sys.exit()

    def register_listeners(self):
        self.network.register_packet_listener(self.print_chat, ChatMessagePacket)
        self.network.register_packet_listener(self.set_pos, PlayerPositionAndLookPacket)
        self.network.register_packet_listener(self.recieve_plugin_message, PluginMessage)
        self.network.register_packet_listener(self.set_health, UpdateHealth)

    def tick(self):
        text = input()
        self.speak(text)
        
    def speak(self, message):
        packet = ChatPacket()
        packet.message = message
        self.network.write_packet(packet)
    
    def set_health(self, health_packet):
        if health_packet.health == 0.0:
            print "RESPAWN"
            self.respawn()
            
    def respawn(self):
        packet = ClientStatus()
        packet.action_id = 0
        self.network.write_packet(packet)
        #print packet
            
    def print_chat(self, chat_packet):
        print type(chat_packet)
        print("Position: " + str(chat_packet.position))
        print("Data: " + chat_packet.json_data)

    def recieve_plugin_message(self, plugin_message):
        data = plugin_message.data.split("|")
        if len(data) == 2 and data[0] == "MC":
            if data[1] == "Brand": print "Brand:", plugin_message.channel
            else:
                print "PLUGIN MESSAGE:", data[1], plugin_message.channel
コード例 #10
0
ファイル: ServerLogin.py プロジェクト: 0ll0wain/MCBot
def ServerWakeUp():
    connection = Connection("ioya.de", username="******")

    def handle_join_game(join_game_packet):
        print('Connected.')

    connection.register_packet_listener(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)

    connection.connect()

    sleep(2)
コード例 #11
0
ファイル: test.py プロジェクト: kisate/Interactions-Bot
def main():
    username = '******'
    # connection = Connection(address, port, username='******'.format(random.randint(0, 1000)))
    connection = Connection(address, port, username=username)
    bot = Bot(connection, username)
    
    def print_outgoing(packet):
        if type(packet) is not my_svbnd_play.DiggingPacket:
            print('<-- %s' % packet, file=sys.stderr)

    connection.register_packet_listener(
        bot.process_packet, Packet)
    connection.register_packet_listener(
        print_outgoing, Packet, outgoing=True)

    def handle_join_game(join_game_packet, early=True):
        print('Connected.')

    connection.register_packet_listener(
        handle_join_game, clientbound.play.JoinGamePacket)

    connection.connect()    

    while True:  # making a loop
        try:  # used try so that if user pressed other than the given key error will not be shown
            a = input()
        except Exception as e:
            # print(e)
            pass  #
コード例 #12
0
def main():
    authenticate(MINECRAFT_USERNAME, MINECRAFT_PASSWORD)
    connection = Connection(SERVER_IP, 25565, auth_token=auth_token)

    connection.register_packet_listener(packet_handler.handle_join_game,
                                        packets.JoinGamePacket)

    # Lambda function is used to inject the connection so the handle_chat function can also send chat packets.
    # That's important for AFK
    connection.register_packet_listener(
        lambda chat_packet: packet_handler.handle_chat(
            chat_packet, connection), packets.ChatMessagePacket)

    connection.register_packet_listener(packet_handler.handle_player_list,
                                        packets.PlayerListItemPacket)

    connection.connect()

    # Allows user to enter chat messages in the terminal and we'll send them.
    # Sometimes needed to run /l bedwars.
    while True:
        try:
            text = input()
            packet = serverbound.play.ChatPacket()
            packet.message = text
            connection.write_packet(packet)
        except KeyboardInterrupt:
            print("Exiting bedwars bot.")
            sys.exit()
コード例 #13
0
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:
            text = input()
            if text == "/respawn":
                print("respawning...")
                packet = ClientStatusPacket()
                packet.action_id = ClientStatusPacket.RESPAWN
                connection.write_packet(packet)
            else:
                packet = ChatPacket()
                packet.message = text
                connection.write_packet(packet)
        except KeyboardInterrupt:
            print("Bye!")
            sys.exit()
コード例 #14
0
def main():
    options = get_options()

    def handle_exception(*args):
        print('handle exception')
        os.kill(os.getpid(), signal.SIGINT)

    if options.offline:
        print("Connecting in offline mode...")
        connection = Connection(options.address,
                                options.port,
                                username=options.username,
                                handle_exception=handle_exception,
                                handle_exit=handle_exception)
    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 %s..." % auth_token.username)
        connection = Connection(options.address,
                                options.port,
                                auth_token=auth_token)

    if options.dump_packets:

        def print_incoming(packet):
            if type(packet) is Packet:
                # This is a direct instance of the base Packet type, meaning
                # that it is a packet of unknown type, so we do not print it.
                return
            print('--> %s' % packet, file=sys.stderr)

        def print_outgoing(packet):
            print('<-- %s' % packet, file=sys.stderr)

        connection.register_packet_listener(print_incoming, Packet, early=True)
        connection.register_packet_listener(print_outgoing,
                                            Packet,
                                            outgoing=True)

    def handle_join_game(join_game_packet):
        print('Connected.')

    connection.register_packet_listener(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)

    connection.connect()

    def send(text):
        print("sending", text)
        packet = serverbound.play.ChatPacket()
        packet.message = text
        connection.write_packet(packet)

    time.sleep(10)
    send("/server main")
    # time.sleep(3)
    # send("Hello world! I'm online!")

    while connection.connected:
        try:
            time.sleep(10)
            send("/server main")
            # text = input()
            # if text == "/respawn":
            #     print("respawning...")
            #     packet = serverbound.play.ClientStatusPacket()
            #     packet.action_id = serverbound.play.ClientStatusPacket.RESPAWN
            #     connection.write_packet(packet)
            # else:
            #     send(text)
        except KeyboardInterrupt:
            send("Bye!")
            print("Bye!")
            time.sleep(5)
            sys.exit()
コード例 #15
0
ファイル: start.py プロジェクト: Merkie/Echo
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 %s..." % auth_token.username)
        connection = Connection(
            options.address, options.port, auth_token=auth_token)

    if options.dump_packets:
        def print_incoming(packet):
            if type(packet) is Packet:
                # This is a direct instance of the base Packet type, meaning
                # that it is a packet of unknown type, so we do not print it.
                return
            print('--> %s' % packet, file=sys.stderr)

        def print_outgoing(packet):
            print('<-- %s' % packet, file=sys.stderr)

        connection.register_packet_listener(
            print_incoming, Packet, early=True)
        connection.register_packet_listener(
            print_outgoing, Packet, outgoing=True)

    once = False

    def handle_join_game(join_game_packet):
        message_queue.append(("CONNECTION", "**Connected**"))
        once = True
        print('Connected.')

    connection.register_packet_listener(
        handle_join_game, clientbound.play.JoinGamePacket)

    def print_chat(chat_packet):
        print("[%s]: %s" % (
            chat_packet.field_string('position'), parse_chat_item(json.loads(chat_packet.json_data))))

    connection.register_packet_listener(
        print_chat, clientbound.play.ChatMessagePacket)

    # Add a deque for chat messages and register a method to get them
    message_queue = deque()

    def forward_chat(chat_packet):
        msg = parse_chat_item(json.loads(chat_packet.json_data))
        if msg.startswith("<"):
            author, message = parse_message(msg)
            if (author != auth_token.username and message != ""): # Don't put in queue your own messages!
                message_queue.append((author, message))

    connection.register_packet_listener(
        forward_chat, clientbound.play.ChatMessagePacket)

    # More maybe? Add here shit for a chatbot

    # Auto respawn because we can't send chat while dead
    def auto_respawn(update_health_packet):
        if update_health_packet.health <= 0:
            print("Respawning")
            packet = serverbound.play.ClientStatusPacket()
            packet.action_id = serverbound.play.ClientStatusPacket.RESPAWN
            connection.write_packet(packet)

    connection.register_packet_listener(
        auto_respawn, clientbound.play.UpdateHealthPacket)

    # Start the discord thread and provide the message deque

    botThread = DiscordBotThread(message_queue, connection)
    botThread.daemon = True
    botThread.start()

    connection.connect()

    while True:
        try:
            text = input()
            if text == "/respawn":
                print("respawning...")
                packet = serverbound.play.ClientStatusPacket()
                packet.action_id = serverbound.play.ClientStatusPacket.RESPAWN
                connection.write_packet(packet)
            else:
                packet = serverbound.play.ChatPacket()
                packet.message = text
                connection.write_packet(packet)
        except KeyboardInterrupt:
            print("Bye!")
            sys.exit()
コード例 #16
0
ファイル: client.py プロジェクト: ConfusedSky/MinecraftFlask
        print(e)
        sys.exit()

with open('minecraft.auth', 'w') as fout:
    fout.write(auth_token.client_token + '\n')
    fout.write(auth_token.access_token)

print("Logged in as %s..." % auth_token.username)
connection = Connection("localhost", 25565, auth_token=auth_token)


def handle_join_game(join_game_packet):
    print('Connected.')


connection.register_packet_listener(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)

# global connected
# connected = True

# def disconnect(disconnect_packet):
# print("You were disconnected: %s" % disconnect_packet.json_data)
# global connected
# connected = False
コード例 #17
0
ファイル: MCFish.py プロジェクト: ENTNEAZ/MCFishBot
packet = minecraft.networking.packets.serverbound.play.UseItemPacket()
packet.hand = 0

if options.dump_packets:
    def print_incoming(packet):
        if type(packet) is Packet:
            # This is a direct instance of the base Packet type, meaning
            # that it is a packet of unknown type, so we do not print it.
            return
        print('--> %s' % packet, file=sys.stderr)

    def print_outgoing(packet):
        print('<-- %s' % packet, file=sys.stderr)

    connection.register_packet_listener(
        print_incoming, Packet, early=True)
    connection.register_packet_listener(
        print_outgoing, Packet, outgoing=True)


def handle_join_game(join_game_packet):
    print('Connected.')

def print_chat(chat_packet):
    # TODO 聊天信息正常化


    #print(chat_packet.json_data)
    decode = json.loads(chat_packet.json_data)
        
        
コード例 #18
0
def main() -> int:

    # Handle program arguments
    ap = argparse.ArgumentParser(
        prog="mchat",
        description="A console chat client for most Minecraft server versions")
    ap.add_argument("server_address", help="IP address of a Minecraft server")
    ap.add_argument("-p",
                    "--port",
                    help="Minecraft server port (default: %(default)s)",
                    type=int,
                    default=25565)
    ap.add_argument("-u", "--username", help="Minecraft username or email")
    ap.add_argument(
        "-v",
        "--version",
        help="Client -> Server protocol version to use (default: %(default)s)",
        default="1.16.4")
    args = ap.parse_args()

    # Verify server version to keep the terminal looking clean
    if args.version not in SUPPORTED_MINECRAFT_VERSIONS.keys():
        console.print(
            f"[bold yellow]{args.version} is not a valid Minecraft version. Versions from {list(SUPPORTED_MINECRAFT_VERSIONS.keys())[0]} to {list(SUPPORTED_MINECRAFT_VERSIONS.keys())[-1]} are allowed."
        )
        return 1

    # Do authentication
    if not args.username:
        username = Prompt.ask("Username or email")
    else:
        username = args.username

    password = getpass.getpass("Password: "******"[bright_black]Loaded authentication information")

    # Determine the actual protocol version number
    protocol_version_num = SUPPORTED_MINECRAFT_VERSIONS[args.version]
    console.print(
        f"[bright_black]Selecting protocol version {protocol_version_num}")

    # Authenticate with Mojang
    auth_token = AuthenticationToken()
    console.print(f"[bright_black]Contacting Yggdrasil...")

    try:
        auth_token.authenticate(username, password)
    except YggdrasilError as e:
        console.print(f"[bold red]Failed to authenticate Minecraft session")
        return 1

    # Open a connection
    server_connection = Connection(args.server_address,
                                   args.port,
                                   auth_token,
                                   allowed_versions=[protocol_version_num])

    try:
        server_connection.connect()
    except:
        console.print(f"[bold red]Could not connect to server")
        return 1

    # Set up an incoming chat handler
    server_connection.register_packet_listener(incomingChatHandler,
                                               ChatMessagePacket)
    console.print(f"[bright_black]Listen to incoming chat packets")

    # Set up input loop
    console.print(
        "All further inputs will be sent to server chat. Press CTRL+C to stop")
    try:
        while True:

            # Get a line from the user
            chat_message = console.input()

            # Send the chat message
            packet = serverbound.play.ChatPacket()
            packet.message = chat_message
            server_connection.write_packet(packet)

    except KeyboardInterrupt as e:
        print("\rGoodbye")

    return 0
コード例 #19
0
class Minecraft():
    def __init__(self,
                 username,
                 password=None,
                 server=None,
                 versions=("1.12.2", "1.12.2"),
                 auto_connect=False):
        self.username = username
        self.password = password
        self.server = server
        self.versions = versions

        self.event = lambda x: print(x)

        self.auth_token = authentication.AuthenticationToken(
            username=self.username, access_token=self.password)
        print("authenticated: %s" % self.auth_token.authenticate(
            self.username, self.password, invalidate_previous=False))
        self.connection = Connection(self.server,
                                     auth_token=self.auth_token,
                                     allowed_versions=self.versions)

        self.connection.register_packet_listener(lambda x: self.print_chat(x),
                                                 ChatMessagePacket)

        print(self.auth_token)
        print(self.connection)

        if auto_connect:
            self._loop_reconect()

    def _loop_reconect(self):
        Timer(30.0, self._loop_reconect).start()
        try:
            self.connect()
        except:
            pass

    def add_chat_event(self, event):
        self.event = event

    def connect(self):
        self.connection.connect()

    def disconnect(self, immediate=False):
        self.connection.disconnect(immediate=immediate)

    def send_message(self, message):
        if message.strip() == "" or message == None:
            return False
        packet = ChatPacket()
        packet.message = message
        self.connection.write_packet(packet)

    def print_chat(self, chat_packet):
        try:
            a = json.loads(chat_packet.json_data)
        except Exception as e:
            pass
        else:
            self.event(self.parse_chat(a))

    def parse_chat(self, chat_data):
        try:
            chat_data["extra"][0]["extra"]
            try:
                return (True, self.parse_chat(chat_data["extra"][0])[1])
            except Exception as e:
                print(e)
        except:
            try:
                return (False, "".join([x["text"]
                                        for x in chat_data["extra"]]))
            except:
                pass
            return
コード例 #20
0
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 %s..." % auth_token.username)
        connection = Connection(options.address,
                                options.port,
                                auth_token=auth_token)

    if options.dump_packets:

        def print_incoming(packet):
            if type(packet) is Packet:
                # This is a direct instance of the base Packet type, meaning
                # that it is a packet of unknown type, so we do not print it.
                return
            print('--> %s' % packet, file=sys.stderr)

        def print_outgoing(packet):
            print('<-- %s' % packet, file=sys.stderr)

        connection.register_packet_listener(print_incoming, Packet, early=True)
        connection.register_packet_listener(print_outgoing,
                                            Packet,
                                            outgoing=True)

    def handle_join_game(join_game_packet):
        print('Connected.')

    connection.register_packet_listener(handle_join_game,
                                        clientbound.play.JoinGamePacket)

    def print_raw_json(chat_packet):
        print("Message (%s): %s" %
              (chat_packet.field_string('position'), chat_packet.json_data))

    def print_raw_text(chat_packet):
        print("Message (%s): " % chat_packet.field_string('position'), end="")
        printRawText(json.loads(chat_packet.json_data))
        print("")

    def print_color_text(chat_packet):
        print("Message (%s): " % chat_packet.field_string('position'), end="")
        printColorText(json.loads(chat_packet.json_data))
        print("")

    def keep_alive(packet):
        print("keep_alive[%d] packet receive." % packet.keep_alive_id)
        from random import randint
        ret = serverbound.play.KeepAlivePacket()
        ret.keep_alive_id = randint(0, 10000)
        connection.write_packet(ret)
        print("Write packet ok.")

    connection.register_packet_listener(print_color_text,
                                        clientbound.play.ChatMessagePacket)
    connection.register_packet_listener(keep_alive,
                                        clientbound.play.KeepAlivePacket)

    connection.connect()

    while True:
        try:
            text = input()
            if text == "/respawn":
                print("respawning...")
                packet = serverbound.play.ClientStatusPacket()
                packet.action_id = serverbound.play.ClientStatusPacket.RESPAWN
                connection.write_packet(packet)
            else:
                packet = serverbound.play.ChatPacket()
                packet.message = text
                connection.write_packet(packet)
        except KeyboardInterrupt:
            print("Bye!")
            sys.exit()
コード例 #21
0
def new_connection():
	m=authentication.AuthenticationToken()
	auth=False
	while not auth: #Retry authentication until we get it
		try:
			auth=m.authenticate(user,pw)
		except YggdrasilError as e: #If authentication fails
			print(e)
			time.sleep(5)
			print("Retrying...")
	c=Connection(server_ip,auth_token=m,initial_version=server_version)
	c.allowed_proto_versions={SUPPORTED_MINECRAFT_VERSIONS[server_version]}
	c.register_packet_listener(keep_alive,KeepAlivePacketClientbound)
	c.register_packet_listener(process_chat,ChatMessagePacket,early=True)
	c.register_packet_listener(respawn,UpdateHealthPacket)
	c.register_packet_listener(set_slot,SetSlotPacket)
	if debug:
		c.register_packet_listener(in_out,Packet,outgoing=True)
		c.register_packet_listener(lambda x:in_out(x,"IN"),Packet)
	return c
コード例 #22
0
ファイル: start.py プロジェクト: Skelmis/pyCraft
def main():
    """Our main function for running the simple pyCraft implementation.

    This function handles and maintains:
     - Gaining authentication tokens & 'logging in'
     - Connecting to the provided server, online or offline
     - Prints the chat packet data to standard out on Clientbound Packet
     - Writes Serverbound chat Packets when required
     - Dumping all packets to standard out

    Notes
    -----
    This is a blocking function.

    """
    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 %s..." % auth_token.username)
        connection = Connection(options.address,
                                options.port,
                                auth_token=auth_token)

    if options.dump_packets:

        def print_incoming(packet):
            if type(packet) is Packet:
                # This is a direct instance of the base Packet type, meaning
                # that it is a packet of unknown type, so we do not print it
                # unless explicitly requested by the user.
                if options.dump_unknown:
                    print("--> [unknown packet] %s" % packet, file=sys.stderr)
            else:
                print("--> %s" % packet, file=sys.stderr)

        def print_outgoing(packet):
            print("<-- %s" % packet, file=sys.stderr)

        connection.register_packet_listener(print_incoming, Packet, early=True)
        connection.register_packet_listener(print_outgoing,
                                            Packet,
                                            outgoing=True)

    def handle_join_game(join_game_packet):
        print("Connected.")

    connection.register_packet_listener(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)

    connection.connect()

    while True:
        try:
            text = input()
            if text == "/respawn":
                print("respawning...")
                packet = serverbound.play.ClientStatusPacket()
                packet.action_id = serverbound.play.ClientStatusPacket.RESPAWN
                connection.write_packet(packet)
            else:
                packet = serverbound.play.ChatPacket()
                packet.message = text
                connection.write_packet(packet)
        except KeyboardInterrupt:
            print("Bye!")
            sys.exit()
コード例 #23
0
def main():
    options = get_options()

    assets = AssetsManager(options.assets)
    mcdata = DataManager("./mcdata")

    if options.offline:
        print("Connecting in offline mode...")
        connection = Connection(options.address,
                                options.port,
                                username=options.username,
                                allowed_versions=[options.mcversion])
    else:
        auth_token = authentication.AuthenticationToken()
        try:
            auth_token.authenticate(options.username, options.password)
        except YggdrasilError as e:
            print(e)
            return
        print("Logged in as %s..." % auth_token.username)
        connection = Connection(options.address,
                                options.port,
                                auth_token=auth_token,
                                allowed_versions=[options.mcversion])

    if options.dump_packets:

        def print_incoming(packet):
            if type(packet) is Packet:
                # This is a direct instance of the base Packet type, meaning
                # that it is a packet of unknown type, so we do not print it.
                return
            if type(packet) in [
                    clientbound.play.EntityVelocityPacket,
                    clientbound.play.EntityLookPacket
            ]:
                # Prevents useless console spam
                return
            print('--> %s' % packet, file=sys.stderr)

        def print_outgoing(packet):
            print('<-- %s' % packet, file=sys.stderr)

        connection.register_packet_listener(print_incoming, Packet, early=True)
        connection.register_packet_listener(print_outgoing,
                                            Packet,
                                            outgoing=True)

    chat = ChatManager(assets)
    chat.register(connection)

    chunks = ChunksManager(mcdata)
    chunks.register(connection)

    def handle_join_game(join_game_packet):
        print('Connected.')

    connection.register_packet_listener(handle_join_game,
                                        clientbound.play.JoinGamePacket)

    connection.connect()

    while True:
        try:
            text = input()
            if text.startswith("!"):
                if text == "!respawn":
                    print("respawning...")
                    packet = serverbound.play.ClientStatusPacket()
                    packet.action_id = serverbound.play.ClientStatusPacket.RESPAWN
                    connection.write_packet(packet)
                elif text.startswith("!print "):
                    p = text.split(" ")
                    chunks.print_chunk(
                        chunks.get_chunk(int(p[1]), int(p[2]), int(p[3])),
                        int(p[4]))
                elif text == "!chunks":
                    area = chunks.get_loaded_area()
                    y_count = area[1][1] - area[0][1]
                    print("Bounds: %s" % (area, ))
                    for y in range(area[0][1], area[1][1]):
                        print("Slice %d:" % (y))
                        for z in range(area[0][2], area[1][2]):
                            for x in range(area[0][0], area[1][0]):
                                if (x, y, z) in chunks.chunks:
                                    c = 'X'
                                else:
                                    c = '.'
                                print(c, end="")
                            print()
                elif text == "!export":
                    area = chunks.get_loaded_area(True)
                    export_area(area[0][0] * 16, area[0][1] * 16,
                                area[0][2] * 16, area[1][0] * 16,
                                area[1][1] * 16, area[1][2] * 16, chunks,
                                assets, mcdata)
                else:
                    print("Unknow test command: %s" % (text))
            else:
                chat.send(connection, text)

        except KeyboardInterrupt:
            print("Bye!")
            sys.exit()

        except Exception as ex:
            print("Exception: %s" % (ex))
            traceback.print_exc()
コード例 #24
0
ファイル: bot.py プロジェクト: xLeon-python/MCBot
    custom_answers = config["custom"]
auth_token = authentication.AuthenticationToken()
#auth_token.authenticate(ACCOUNT[0], ACCOUNT[1])
while 1:
    try:
        auth_token.authenticate(ACCOUNT[0], ACCOUNT[1])
        break
    except:
        print("waiting for mojang cooldown")
        time.sleep(10)

print("Logged in as %s..." % auth_token.username)
connection = Connection("gommehd.net", auth_token=auth_token)

#connection = Connection("localhost", 62139, username="******")
'''
def print_incoming(packet):
    if type(packet) is Packet:
        # This is a direct instance of the base Packet type, meaning
        # that it is a packet of unknown type, so we do not print it.
        return
    print('--&gt; %s' % packet, file=sys.stderr)


def print_outgoing(packet):
    print('&lt;-- %s' % packet, file=sys.stderr)


connection.register_packet_listener(print_incoming, Packet, early=True)
connection.register_packet_listener(print_outgoing, Packet, outgoing=True)
'''
コード例 #25
0
    def onMessage(self, payload, isBinary):
        if not isBinary:
            message = json.loads(payload.decode('utf8'))

            if message["type"] == "login":
                try:
                    if message["username"] in connections and message[
                            "password"] == connections[
                                message["username"]]["password"]:
                        connections[message["username"]][
                            "connection"].register_packet_listener(
                                self.sendPacket, Packet, early=True)

                        self.username = message["username"]

                        print("Resuming session as " + connections[
                            message["username"]]["auth_token"].username +
                              " on " + message["host"])
                        return

                    print("Trying to log in as " + message["username"] +
                          " on " + message["host"] + ":" + message["port"])

                    auth_token = authentication.AuthenticationToken()
                    auth_token.authenticate(message["username"],
                                            message["password"])

                    connection = Connection(message["host"],
                                            int(message["port"]),
                                            auth_token=auth_token)
                    connection.register_packet_listener(self.sendPacket,
                                                        Packet,
                                                        early=True)
                    connection.register_packet_listener(self.onGameJoin,
                                                        JoinGamePacket,
                                                        early=True)
                    connection.register_packet_listener(
                        self.onDisconnection, DisconnectPacket)
                    connection.connect()

                    @connection.exception_handler(LoginDisconnect, early=True)
                    def onFailedLogin(exc, exc_info):
                        data = {"type": "LoginDisconnect", "packet": str(exc)}

                        self.sendMessage(json.dumps(
                            data, ensure_ascii=False).encode('utf8'),
                                         isBinary=False)
                        connections[self.username]["connection"].disconnect()
                        connections.pop(self.username)
                        self._closeConnection()

                    connections[message["username"]] = {
                        "password": message["password"],
                        "host": message["host"],
                        "port": message["port"],
                        "auth_token": auth_token,
                        "connection": connection
                    }

                    self.username = message["username"]

                    print("Started new session as " + auth_token.username +
                          " on " + message["host"])

                except Exception as e:
                    print("Error while logging in: " + repr(e))
                    self.sendMessage(
                        ("Error while logging in: " + repr(e)).encode('utf8'),
                        False)
                    self._closeConnection()

            elif message["type"] == "respawn":
                packet = serverbound.play.ClientStatusPacket()
                packet.action_id = serverbound.play.ClientStatusPacket.RESPAWN
                connections[self.username]["connection"].write_packet(packet)

            elif message["type"] == "chat":
                packet = serverbound.play.ChatPacket()
                packet.message = message["message"]
                connections[self.username]["connection"].write_packet(packet)

            elif message["type"] == "disconnect":
                connections[self.username]["connection"].disconnect()
                connections.pop(self.username)
                self._closeConnection()

            elif message["type"] == "connect":
                connections[self.username]["connection"].connect()
コード例 #26
0
def main():

    auth_token = authentication.AuthenticationToken()
    try:
        with open('minecraft.auth', 'r') as f:
            auth_token.client_token, auth_token.access_token = f.read().splitlines()

        # Library has issues need to do some hackey stuff to make sure it works.
        # I would use validate, but that would require some rewriting as well.
        auth_token.username = "******"
        auth_token.refresh()
    except (IOError, YggdrasilError):
        # IF there is no authentication file authenticate using username and password
        try:
            options = get_options()
            auth_token.authenticate(options["username"], options["password"])
        except YggdrasilError as e:
            print(e)
            sys.exit()

    with open('minecraft.auth', 'w') as fout:
        fout.write(auth_token.client_token + '\n')
        fout.write(auth_token.access_token)

    print("Logged in as %s..." % auth_token.username)
    connection = Connection(
        "localhost", 25565, auth_token=auth_token)

    def handle_join_game(join_game_packet):
        print('Connected.')

    connection.register_packet_listener(
        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)

    global connected
    connected = True

    def disconnect(disconnect_packet):
        print("You were disconnected: %s" % disconnect_packet.json_data)
        global connected
        connected = False

    connection.register_packet_listener(disconnect, 
            clientbound.play.DisconnectPacket)
    connection.connect()

    while connected:
        try:
            text = input()
            if text == "/respawn":
                print("respawning...")
                packet = serverbound.play.ClientStatusPacket()
                packet.action_id = serverbound.play.ClientStatusPacket.RESPAWN
                connection.write_packet(packet)
            else:
                packet = serverbound.play.ChatPacket()
                packet.message = text
                connection.write_packet(packet)
        except KeyboardInterrupt:
            print("Bye!")
            sys.exit()
コード例 #27
0
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 %s..." % auth_token.username)
        connection = Connection(options.address,
                                options.port,
                                auth_token=auth_token)

    if options.dump_packets:

        def print_incoming(packet):
            if type(packet) is Packet:
                # This is a direct instance of the base Packet type, meaning
                # that it is a packet of unknown type, so we do not print it.
                return
            print('--> %s' % packet, file=sys.stderr)

        def print_outgoing(packet):
            print('<-- %s' % packet, file=sys.stderr)

        connection.register_packet_listener(print_incoming, Packet, early=True)
        connection.register_packet_listener(print_outgoing,
                                            Packet,
                                            outgoing=True)

    def handle_join_game(join_game_packet):
        print('Connected.')

    connection.register_packet_listener(handle_join_game,
                                        clientbound.play.JoinGamePacket)

    def print_chat(chat_packet, output="default"):

        if output == "raw":
            print(
                "Message (%s): %s" %
                (chat_packet.field_string('position'), chat_packet.json_data))

        chat_json = json.loads(chat_packet.json_data)

        if output == "pretty":
            print(
                json.dumps(chat_json,
                           sort_keys=True,
                           indent=4,
                           separators=(',', ': ')))

        if output == "default":
            message = Message(chat_json)
            ts = datetime.datetime.fromtimestamp(
                time.time()).strftime('%Y-%m-%d %H:%M:%S')
            print("[{}] {}".format(colored(ts, "grey"), message.formatted_str))

    connection.register_packet_listener(print_chat,
                                        clientbound.play.ChatMessagePacket)

    connection.connect()

    def requeue(realm):
        message = "/joinqueue " + realm
        packet = serverbound.play.ChatPacket()
        packet.message = message
        print(message)
        connection.write_packet(packet)

    # Re-join realm every 60 seconds
    rt = RepeatedTimer(60, requeue, options.realm)

    while True:
        try:
            text = input()
            if text == "/respawn":
                print("respawning...")
                packet = serverbound.play.ClientStatusPacket()
                packet.action_id = serverbound.play.ClientStatusPacket.RESPAWN
                connection.write_packet(packet)
            else:
                packet = serverbound.play.ChatPacket()
                packet.message = text
                connection.write_packet(packet)
        except KeyboardInterrupt:
            rt.stop()
            print("Bye!")
            sys.exit()
コード例 #28
0
            #playSong("thetop")

        if kb.is_pressed("ctrl+shift"):
            #MultiDimPrint("https://cdn.discordapp.com/attachments/255681374025941003/677868965674090526/wall.schematic", (219, 231, -155))
            while kb.is_pressed("ctrl+shift"):
                pass

        if kb.is_pressed("f4"):
            exit()

        updatePosition()


if __name__ == '__main__':
    # connect and register listeners
    dj = Connection("127.0.0.1", username="******")
    dj.connect()
    dj.register_packet_listener(
        _setPosition, clientbound.play.player_position_and_look_packet.
        PlayerPositionAndLookPacket)
    dj.register_packet_listener(_onChatMessage,
                                clientbound.play.ChatMessagePacket)

    print("Connecting...")
    while pos is None:
        # wait for server to update dj's position
        pass
    print("Connected")
    sendChat("<3")
    main()
コード例 #29
0
ファイル: bwstatscore.py プロジェクト: Vyprath/Bedwars-Stats
class bot:
    def __init__(self,
                 username,
                 password,
                 bot_ign,
                 reply_rate=20,
                 whitelist=False):
        self.username = username
        self.password = password
        self.bot_ign = bot_ign
        self.debug = False
        self.whitelist = whitelist

        self.reply_rate = int(reply_rate)

        self.auth_token = authentication.AuthenticationToken()
        try:
            self.auth_token.authenticate(self.username, self.password)
        except YggdrasilError as error:
            print(error)
            exit()
        print("Logged in as %s." % self.auth_token.username)
        self.connection = Connection("mc.hypixel.net",
                                     25565,
                                     auth_token=self.auth_token)

        self.command_delay = 0
        self.msgQueue = []
        self.partyQueue = []
        self.commandQueue = []
        self.msgCurrentChannel = ""
        self.party = {"inP": False, "from": "", "timestamp": 0}
        self.partyConfig = {}
        self.playercooldown = {}
        self.cooldownTimer = time.time()
        self.heartbeat = time.time() + 120
        self.heartbeatCooldown = time.time() + 120
        self.msgformat = msgformat.formats(self.bot_ign, 24)
        self.bots = {x: 0 for x in msgformat.bots if x != self.bot_ign}
        self.current_load = 0
        self.inQueue = False
        self.inQueueTime = 0
        self.muted = False
        self.muteDuration = 3600
        self.unmutetime = 0
        self.muteheartbeat = 0
        self.leaderBuffer = []
        self.mods = []
        self.whitelisted = []
        try:
            with open("whitelisted.txt", "r") as file:
                self.whitelisted = [x for x in file.read().split("\n")]
        except Exception:
            self.whitelisted = []
        print("whitelisted loaded", len(self.whitelisted))

    def initialize(self):
        self.connection.register_packet_listener(
            self.handle_join_game, clientbound.play.JoinGamePacket)
        self.connection.register_packet_listener(
            self.handle_chat, clientbound.play.ChatMessagePacket)
        self.connection.connect()

    def disconnect(self):
        self.msgQueue = []
        self.partyQueue = []
        self.friendQueue = []
        self.connection.disconnect(True)
        exit()

    def send_chat(self, text, delay=0.6, bypass=False):
        if not self.inQueue or bypass:
            text = text[:255]  # limit to 255 characters
            packet = serverbound.play.ChatPacket()
            packet.message = text
            self.connection.write_packet(packet)
            if self.debug:
                debugtext = "".join(x for x in text if x not in "-⛬⛫⛭⛮⛶_")
                print(debugtext)
        self.command_delay = time.time()
        time.sleep(delay * 1.05)

    def handle_join_game(self, packet):
        print(packet)
        self.heartbeat = time.time() - 50
        self.heartbeatCooldown = time.time() - 50
        time.sleep(0.5)
        self.send_chat("/p leave")
        print('Connected.')

    def handle_chat(self, chat_packet):
        try:
            chat_raw = str(chat_packet.json_data)
            chat_json = json.loads(chat_raw)
            msg = util.raw_to_msg(chat_json)
            if not (self.muted):
                if ("red" in chat_raw and len(msg) < 75
                        and "+]" not in msg) or self.debug:
                    debugtext = "".join(x for x in msg if x not in "-⛬⛫⛭⛮⛶_")
                    print(debugtext)

                if ("red" in chat_raw and len(msg) < 75 and "+]" not in msg):
                    mutedetect = "".join(x for x in msg if x not in "-⛬⛫⛭⛮⛶_")
                    if "Your mute will expire in" in mutedetect:
                        muted = True
                        duration = mutedetect[
                            mutedetect.index("Your mute will expire in") + 25:]
                        duration = duration.split(' Find')
                        del duration[1]
                        duration = duration.pop(0)
                        print(f'You are muted for {duration}.')

                if "extra" in chat_json:
                    # On party request
                    if chat_raw.count("/party accept") >= 2:
                        for data in chat_json["extra"]:
                            if "/party accept" in str(data):
                                user = data["clickEvent"]["value"].split()[-1]
                                if (user not in self.whitelisted
                                    ) and self.whitelist:
                                    return  # whitelist
                                if self.cooldowncheck(user, 5):
                                    return  # cooldown
                                self.partyQueue.append({
                                    "mode": "queue",
                                    "user": user
                                })
                                return
                        return

                    # On heartbeat
                    elif "HeartBeat-KeepAlive" in chat_raw and "from" not in chat_raw.lower(
                    ) and self.bot_ign in chat_raw:
                        if time.time() - self.heartbeat > 70 and self.debug:
                            self.debug = False
                        self.heartbeat = time.time()
                        onlinehb = ['bwstatsv2']
                        onlinehb.append([
                            int(time.time()), self.bot_ign,
                            min(
                                int(
                                    max(self.current_load, 1) /
                                    max(self.reply_rate, 0.1) * 100), 100)
                        ])
                        onlinehb = [
                            x for x in onlinehb if time.time() - x[0] < 130
                        ]
                        msgformat.bots = list(
                            set([
                                x[1] for x in onlinehb
                                if time.time() - x[0] < 130
                            ]))
                        self.bots = {}
                        for bot in onlinehb:
                            if bot[1] in self.bots:
                                self.bots[bot[1]] = max(
                                    bot[2], self.bots[bot[1]])
                            else:
                                self.bots[bot[1]] = bot[2]
                        if self.debug:
                            for bot in self.bots:
                                print(bot, self.bots[bot], "%")
                            # print(msgformat.bots)
                        return

                    elif "Party Leader" in chat_raw and "●" in chat_raw:
                        leader = [
                            leader
                            for leader in msg[msg.index(":") + 1:].split("●")
                            if len(leader) > 1
                        ]
                        leader = [leader.split()[-1] for leader in leader]
                        leader = leader.pop(0)
                        self.leaderBuffer.append(leader)

                    elif "Party Moderators" in chat_raw and "●" in chat_raw:
                        mods = [
                            mods
                            for mods in msg[msg.index(":") + 1:].split("●")
                            if len(mods) > 1
                        ]
                        mods = [mods.split()[-1] for mods in mods]
                        self.mods.append(self.leaderBuffer[0])

                    # On party list return
                    elif "Party Members" in chat_raw and "●" in chat_raw:
                        # Party members (2): [VIP] MinuteBrain ● [MVP+] Its_Me_Me ●
                        users = [
                            user
                            for user in msg[msg.index(":") + 1:].split("●")
                            if len(user) > 1
                        ]
                        users = [user.split()[-1]
                                 for user in users]  # remove ranks
                        users.append(self.leaderBuffer[0])
                        users.extend(self.mods)
                        self.leaderBuffer = []
                        self.mods = []
                        users.remove(self.bot_ign)  # remove bot from the list
                        self.partyQueue = [{
                            "mode": "list",
                            "user": users
                        }] + self.partyQueue  # put on top of the queue
                        return

                    # On msg request
                    elif ("From "
                          in chat_raw) and ("light_purple"
                                            in chat_raw) and (self.bot_ign
                                                              not in chat_raw):
                        self.chat_msg(msg)
                        return

                    # On open PM channel
                    elif {
                            "text": " for the next 5 minutes. Use ",
                            "color": "green"
                    } in chat_json["extra"]:
                        user = msg[msg.index("with") +
                                   4:msg.index("for")].split()[-1]
                        #print(user)
                        self.msgCurrentChannel = user
                        return

                    # On friend request
                    elif ("Click to" in chat_raw) and ("/f accept "
                                                       in chat_raw):
                        for data in chat_json["extra"]:
                            if "/f accept " in str(data).lower():
                                user = data["clickEvent"]["value"].split()[-1]
                                if self.cooldowncheck(user, 2):
                                    return  # cooldown
                                self.commandQueue.append({
                                    "command": "friend_request",
                                    "user": user
                                })
                                return
                        return

                    # On queue
                    elif ("The game starts in" in chat_raw) or (
                            "has joined" in msg and "/" in msg
                    ) or ("has quit" in msg
                          and "/" in msg) or ("The party leader, " in chat_raw
                                              and "yellow" in chat_raw):
                        if not (self.inQueue
                                ) and time.time() - self.inQueueTime > 5:
                            self.inQueue = True
                            self.inQueueTime = time.time()
                            print("Blocked - " + self.party["from"])
                            self.cooldowncheck(self.party["from"], 60)
                            self.party["inP"] = True
                            self.party["timestamp"] = time.time() + 99999
                            time.sleep(1)
                            self.party["inP"] = True
                            self.send_chat("/pchat :( hey! don't warp me!",
                                           0.07, True)
                            self.send_chat("/p leave", 1, True)
                            self.send_chat("/hub bw", 0.7, True)
                            for _ in range(15):
                                self.send_chat("/golimbo", 0.07, True)
                            self.party["inP"] = True
                            self.party["timestamp"] = time.time() + 5
                            self.inQueue = False
                            self.inQueueTime = time.time()
                        return

                    # On whereami respond
                    elif "You are currently connected to server" in msg and "aqua" in chat_raw.lower(
                    ):
                        if "lobby" in msg:
                            self.commandQueue.append({"command": "in_lobby"})
                        else:
                            self.commandQueue.append({"command": "in_game"})
                        return
            else:  # while muted
                print('idk ur muted or smth')

        except Exception as error_code:
            print("chat handle error!!", error_code)

    def chat_msg(self, msg):
        # >>> msg = 'From [MVP+] FatDubs: FatDubs gamerboy80 5'
        if "+send" not in msg.lower():
            msg = "".join([
                char for char in msg if char.lower() in
                "[]:abcdefghijklmnopqrstuvwxyz0123456789_ +/"
            ])
        msg = " ".join(msg.split())  # remove double space
        msg = msg.replace("+ ", "+").replace("++", "+").replace("+]", "]")
        user = msg[:msg.index(":")].split()[-1]
        if (user not in self.whitelisted) and self.whitelist:
            return  # whitelist
        agus = msg[msg.index(":") + 1:].split()
        # user = '******'
        # agus = ['FatDubs', 'gamerboy80', '5']

        mode = 0  # stats mode
        if len(agus) > 1 and "+send" not in "".join(agus).lower():
            mode = agus[-1]
            if mode in [str(x) for x in range(6)]:
                mode = int(mode)
                agus.pop(-1)
            else:
                mode = 0

        # user = '******'
        # agus = ['FatDubs', 'gamerboy80']
        # mode = 5

        if self.cooldowncheck(user, 1) and user.lower() not in ["fatdubs"]:
            return  # player cooldown

        # commands
        if "+" in msg:
            command = agus[0]

            if command.lower() == "+send" and user.lower() in [
                    "fatdubs"
            ] and len(agus) >= 2:
                self.commandQueue.append({
                    "command": "send_command",
                    "send": " ".join(agus[1:])
                })

            elif command.lower() == "+limbo" and user.lower() in ["fatdubs"]:
                print("Warp to Limbo")
                for _ in range(15):
                    self.send_chat("/golimbo", 0.07, True)
                self.send_chat("/whereami")

            elif command.lower() == "+whitelist" and user.lower() in [
                    "fatdubs"
            ] and len(agus) >= 2:
                self.whitelistChange = ("".join(agus[1:]))
                print('whitelist queue - ' + self.whitelistChange)

            elif command.lower() == "+stop" and user.lower() in ["fatdubs"]:
                print('disconnecting..')
                self.disconnect()

            elif command.lower() in ["+pmode", "+setpartymode"]:
                self.partyConfig[user] = mode
                self.msgQueue = [{
                    "msgMode": "party_mode",
                    "user": user,
                    "mode": mode
                }] + self.msgQueue

            elif command.lower() == "+resetcooldown" and user.lower() in [
                    "fatdubs"
            ]:
                self.playercooldown = {}
                print('reset cooldown')

            elif command.lower() in ["+reload", "+reloadall"] and user.lower(
            ) in ["fatdubs"] + [x.lower() for x in list(self.bots)]:
                print("Reloading...")
                try:
                    reload(msgformat)
                    self.msgformat = msgformat.formats(self.bot_ign, 24)
                    self.bots = {
                        x: 0
                        for x in msgformat.bots if x != self.bot_ign
                    }
                except Exception:
                    print("Fail to reload msgformat")
                try:
                    reload(hypixelapi)
                except Exception:
                    print("Fail to reload hypixelapi")

            elif command.lower() == "+debug" and user.lower() in ["fatdubs"]:
                self.debug = not (self.debug)
                print(f"Debug : {self.debug}")
            else:
                self.msgQueue = [{
                    "msgMode": "wrong_syntax",
                    "user": user
                }] + self.msgQueue

            return

        # stats request
        if self.current_load <= self.reply_rate:
            if len(agus) > 0:
                if len(agus[0]) <= 16:
                    if len(agus) == 1:
                        self.msgQueue = [{
                            "msgMode": "stats",
                            "replyto": user,
                            "username": agus[0],
                            "mode": mode
                        }] + self.msgQueue
                    elif len(agus) > 1 and len(agus) <= 4:
                        self.msgQueue = [{
                            "msgMode": "stats_multiple",
                            "replyto": user,
                            "username": agus,
                            "mode": mode
                        }] + self.msgQueue
                    else:
                        self.msgQueue = [{
                            "msgMode": "wrong_syntax",
                            "user": user
                        }] + self.msgQueue
                else:
                    self.msgQueue = [{
                        "msgMode": "wrong_syntax",
                        "user": user
                    }] + self.msgQueue
            else:
                self.msgQueue = [{
                    "msgMode": "wrong_syntax",
                    "user": user
                }] + self.msgQueue

    def cooldowncheck(self, user, n=1):
        if user not in self.playercooldown:
            self.playercooldown[user] = n
        else:
            if self.playercooldown[user] > 6:
                self.playercooldown[user] += 3
            else:
                self.playercooldown[user] += n

        if self.playercooldown[user] > 100 and user.lower() not in ["fatdubs"]:
            self.commandQueue.append({"command": "ignore", "user": user})
            print("Ignored", user, self.playercooldown[user])
            return True
        elif self.playercooldown[user] > 6 and user.lower() not in ["fatdubs"]:
            print("Reject spam from", user, self.playercooldown[user])
            return True
        else:
            self.current_load += 1
            return False

    def cooldown_tick(self):
        if time.time() - self.cooldownTimer >= 6:
            self.cooldownTimer = time.time()
            for user in list(self.playercooldown):
                self.playercooldown[user] -= 1
            self.playercooldown = {
                x: self.playercooldown[x]
                for x in list(self.playercooldown)
                if self.playercooldown[x] > 0
            }

    def msg_tick(self):
        if len(self.msgQueue) > 0:
            currentQueue = self.msgQueue.pop(0)
            if currentQueue["msgMode"] == "stats":
                replyTo = currentQueue["replyto"]
                username = currentQueue["username"]
                if currentQueue["username"].lower() == "me":
                    username = currentQueue["replyto"]
                mode = currentQueue["mode"]
                if self.msgCurrentChannel != replyTo:
                    while time.time() - self.command_delay < 0.5:
                        time.sleep(0.05)
                    self.send_chat("/r", 0)
                data = hypixelapi.getPlayer(username, hypixelapi.nextKey())
                raw = hypixelapi.convert(data, mode, "msg")
                msg = self.msgformat.msg(raw,
                                         replyTo.lower() == username.lower())
                while time.time() - self.command_delay < 0.7:
                    time.sleep(0.05)
                if replyTo.lower() == self.msgCurrentChannel.lower():
                    print(f"(R) {replyTo} --> {username}")
                    self.send_chat(msg, 0.4)
                else:
                    if hypixelapi.getPlayer(
                            replyTo, hypixelapi.nextKey())["msgsetting"]:
                        print(f"(MSG) {replyTo} --> {username}")
                        self.send_chat(f"/msg {replyTo} " + msg, 0.4)
                    else:
                        print(f"(MSG) Couldn't reply to {replyTo}")
                self.msgCurrentChannel = ""

            if currentQueue["msgMode"] == "stats_multiple":
                replyTo = currentQueue["replyto"]
                usernames = currentQueue["username"]
                mode = currentQueue["mode"]
                #util.dict_increment(self.quotaChange,replyTo,len(usernames))
                if self.msgCurrentChannel != replyTo:
                    while time.time() - self.command_delay < 0.6:
                        time.sleep(0.05)
                    self.send_chat("/r", 0)
                handle = util.multithreading(usernames, mode)
                handle.start()
                raws = [handle.output[x] for x in list(handle.output)]
                msg = list(self.msgformat.party(raws, mode))[0]
                msg = msgformat.insertInvis(msg, 20)
                while time.time() - self.command_delay < 0.7:
                    time.sleep(0.05)
                if replyTo.lower() == self.msgCurrentChannel.lower():
                    print(f"(R) {replyTo} --> {usernames}")
                    self.send_chat(msg, 0.4)
                else:
                    if hypixelapi.getPlayer(
                            replyTo, hypixelapi.nextKey())["msgsetting"]:
                        print(f"(MSG) {replyTo} --> {username}")
                        self.send_chat(f"/msg {replyTo} " + msg, 0.4)
                    else:
                        print(f"(MSG) Can't send msg {replyTo}")
                self.msgCurrentChannel = ""

            elif currentQueue["msgMode"] == "wrong_syntax":
                print(f"Wrong_syntax: {currentQueue['user']}")
                while time.time() - self.command_delay < 0.5:
                    time.sleep(0.05)
                self.send_chat("/r " + self.msgformat.wrong_syntax(), 0.5)

            elif currentQueue["msgMode"] == "party_mode":
                print(
                    f"Party Mode: {currentQueue['user']} --> {currentQueue['mode']}"
                )
                while time.time() - self.command_delay < 0.5:
                    time.sleep(0.05)
                self.send_chat(
                    "/r " + self.msgformat.party_mode(currentQueue["mode"]),
                    0.5)

    def party_chat_transit(self, msg, delay=0.5):
        while len(self.msgQueue) > 0:
            self.msg_tick()
            time.sleep(0.05)
        while time.time() - self.command_delay < delay:
            time.sleep(0.05)
        self.send_chat(msg, delay)
        self.party["timestamp"] = time.time()

    def party_tick(self):
        if len(self.partyQueue) > 0 and len(self.msgQueue) == 0:
            currentQueue = self.partyQueue.pop(0)
            if currentQueue["mode"] == "queue" and self.party[
                    "inP"]:  # requeue if in party
                #print("Party Requeued !!")
                self.partyQueue.append(currentQueue)
            else:
                if currentQueue["mode"] == "queue":
                    self.party = {"inP": True, "from": currentQueue["user"]}
                    #util.dict_increment(self.quotaChange,self.party["from"],1)
                    while time.time() - self.command_delay < 0.5:
                        time.sleep(0.05)  # prevent sending command too fast
                    self.party_chat_transit(f"/p accept {self.party['from']}",
                                            0.4)
                    self.party_chat_transit(f"/pl", 0.3)
                elif currentQueue["mode"] == "list":
                    users = currentQueue['user']
                    print("Party list -", " ".join(users))
                    for user in users:
                        if user.lower() != self.bot_ign and user in list(
                                self.bots):
                            print("multiple bots in party!!!!!")
                            self.cooldowncheck(self.party["from"], 20)
                            while time.time() - self.command_delay < 2:
                                self.msg_tick()
                                time.sleep(0.05)
                            self.send_chat("/p leave")
                            self.party["inP"] = False
                            return
                    if len(users) <= self.msgformat.party_max:
                        if self.party["from"] in self.partyConfig:
                            mode = self.partyConfig[self.party["from"]]
                        else:
                            mode = 0
                        handle = util.multithreading(users, mode)
                        handle.start()
                        raws = [handle.output[x] for x in list(handle.output)]
                        msgs = self.msgformat.party(raws, mode)
                        while time.time() - self.command_delay < 0.3:
                            time.sleep(0.05)
                        for msg in msgs:
                            self.party_chat_transit(f"/pchat {msg}", 0.3)
                    else:
                        while time.time() - self.command_delay < 0.3:
                            time.sleep(0.05)
                        self.party_chat_transit(
                            "/pchat " + self.msgformat.party_too_large(), 0.3)
                    while time.time() - self.command_delay < 1:
                        self.msg_tick()
                        time.sleep(0.05)
                    self.send_chat("/p leave")
                    self.party["inP"] = False
        if self.party["inP"] and time.time() - self.party["timestamp"] > 2:
            print("Party timeout", self.party["from"])
            while time.time() - self.command_delay < 0.8:
                time.sleep(0.05)
            self.send_chat("/p leave", 0.3)
            self.party["inP"] = False

    def command_tick(self):
        if len(self.commandQueue) > 0:
            currentQueue = self.commandQueue.pop(0)

            if currentQueue["command"] == "friend_request":
                print(f"Friend accepted - {currentQueue['user']}")
                while time.time() - self.command_delay < 0.7:
                    time.sleep(0.05)
                self.send_chat(f"/f accept {currentQueue['user']}", 0.3)

            elif currentQueue["command"] == "send_command":
                print(f"Command sent - {currentQueue['send']}")
                while time.time() - self.command_delay < 0.7:
                    time.sleep(0.05)
                self.send_chat(currentQueue["send"], 0.3, True)

            elif currentQueue["command"] == "in_game":
                print("Warp to Lobby")
                while time.time() - self.command_delay < 0.5:
                    time.sleep(0.05)
                self.send_chat("/hub bw", 0.3, True)

            elif currentQueue["command"] == "in_lobby":
                print("Warp to Limbo")
                for _ in range(15):
                    self.send_chat("/golimbo", 0.07, True)
                self.send_chat("/whereami")

            elif currentQueue["command"] == "ignore":
                print(f"Ignored - {currentQueue['user']}")
                while time.time() - self.command_delay < 0.7:
                    time.sleep(0.05)
                self.send_chat(f"/ignore add {currentQueue['user']}")

    def heartbeat_tick(self):
        if time.time() - self.heartbeat > 610:
            self.connection.disconnect(True)
            raise Exception("No heartbeat detect! Reconnecting")
            return

        if time.time() - self.heartbeat > 120 and not (self.debug):
            #self.debug = True
            self.connection.connect()
            #print("Debug : True")
            print("Reconnecting")

        if time.time() - self.heartbeat > 60 and time.time(
        ) - self.heartbeatCooldown > 30:
            heartbeat_length = time.time() - self.heartbeat
            random_msg = "".join(
                [chr(random.randint(64, 125)) for _ in range(30)])
            while time.time() - self.command_delay < 0.5:
                time.sleep(0.7)
            self.send_chat(
                f"/msg {self.bot_ign} HeartBeat-KeepAlive {random_msg}",
                0.3)  #comment this to test heartbeat restart system.
            self.heartbeatCooldown = time.time()
            self.send_chat("/whereami", 0.2)

            if self.current_load > self.reply_rate:
                print("Overloaded!! <-----")
            self.current_load = 0

            if time.time() - self.heartbeat > 300:
                self.connection.connect()
                print("Reconnecting")

            print(f"Heartbeat ({int(heartbeat_length)}sec)")
            return

    def tick(self):
        self.heartbeat_tick()
        try:
            self.party_tick()
            self.msg_tick()
            self.command_tick()
            self.cooldown_tick()
        except Exception as error_code:
            print("Tick error! (skiped) -", error_code)
コード例 #30
0
ファイル: start.py プロジェクト: MissingNoShiny/pyCraft
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 %s..." % auth_token.username)
        connection = Connection(
            options.address, options.port, auth_token=auth_token)

    if options.dump_packets:
        def print_incoming(packet):
            if type(packet) is Packet:
                # This is a direct instance of the base Packet type, meaning
                # that it is a packet of unknown type, so we do not print it
                # unless explicitly requested by the user.
                if options.dump_unknown:
                    print('--> [unknown packet] %s' % packet, file=sys.stderr)
            else:
                print('--> %s' % packet, file=sys.stderr)

        def print_outgoing(packet):
            print('<-- %s' % packet, file=sys.stderr)

        connection.register_packet_listener(
            print_incoming, Packet, early=True)
        connection.register_packet_listener(
            print_outgoing, Packet, outgoing=True)

    def handle_join_game(join_game_packet):
        print('Connected.')

    connection.register_packet_listener(
        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)

    def handle_zzz(chat_packet):
        if json.loads(chat_packet.json_data).get("with", " ")[-1] == "zzz":
            connection.disconnect()
            time.sleep(5)
            connection.connect()
            
    connection.register_packet_listener(
        handle_zzz, clientbound.play.ChatMessagePacket)        

    connection.connect()

    while True:
        try:
            text = input()
            if text == "/respawn":
                print("respawning...")
                packet = serverbound.play.ClientStatusPacket()
                packet.action_id = serverbound.play.ClientStatusPacket.RESPAWN
                connection.write_packet(packet)
            else:
                packet = serverbound.play.ChatPacket()
                packet.message = text
                connection.write_packet(packet)
        except KeyboardInterrupt:
            print("Bye!")
            sys.exit()
コード例 #31
0
class CallbackCallable():
    def __init__(self):
        self.connection = None
        self.done = False
        self.ip = None
        self.port = None

    def __call__(self, ch, method, properties, body):
        json_body = json.loads(body)
        self.ip = json_body["ip"]
        self.port = int(json_body["port"])
        try:
            ipstr = "{}:{}".format(self.ip, self.port)
            status = MinecraftServer.lookup(ipstr).status(retries=2)
            if status.players.online > 0:
                print("server {} skipped because of {} online players".format(
                    ipstr, status.players.online))
                channel.basic_publish(
                    exchange='',
                    routing_key=os.environ['RABBIT_MOTD_QUEUE'],
                    body=json.dumps({
                        'ip': self.ip,
                        'port': int(self.port)
                    }),
                    properties=pika.BasicProperties(
                        delivery_mode=2,  # make message persistent
                    ))
        except (socket.timeout, ConnectionRefusedError, ConnectionResetError,
                OSError):
            return
        try:
            self.connect()
        except Exception as e:
            self.disconnect(ch, method)
            print(e)
            return
        if self.connection.connected:
            self.connection.disconnect(immediate=True)
        self.disconnect(ch, method)

    def exception_handler(self, exception):
        print(exception)

    def connect(self):
        self.connection = Connection(self.ip,
                                     self.port,
                                     auth_token=auth_token,
                                     handle_exception=self.exception_handler)
        print("connecting to", self.ip)
        self.connection.register_packet_listener(
            self.handle_join_game, clientbound.play.JoinGamePacket)
        self.connection.register_packet_listener(
            self.on_login_disconnect_packet,
            clientbound.play.DisconnectPacket,
            early=True)
        # self.connection.register_packet_listener(self.print_packet, Packet, early=True)
        self.connection.register_packet_listener(
            self.on_login_disconnect_packet,
            clientbound.login.DisconnectPacket,
            early=True)
        with timeout(2):
            self.connection.connect()
            start = time.time()
            while not self.done:
                time.sleep(0.01)
                now = time.time()
                diff = now - start
                if diff > 2:
                    self.done = True

    def disconnect(self, ch, method):
        self.connection = None
        self.done = False
        ch.basic_ack(method.delivery_tag)

    def print_packet(self, packet):
        if type(packet) is Packet:
            return
        print('--> %s' % packet)

    def handle_join_game(self, join_game_packet):
        print("found server without whitelist")
        conn = psycopg2.connect(database=os.environ['POSTGRES_DATABASE'],
                                user=os.environ['POSTGRES_USER'],
                                password=os.environ['POSTGRES_PASSWORD'],
                                host=os.environ['POSTGRES_HOST'],
                                port=os.environ['POSTGRES_PORT'])
        with conn.cursor() as c:
            c.execute(
                "INSERT INTO public.servers (ip, port) VALUES(%s, %s) ON CONFLICT DO NOTHING;",
                (self.ip, self.port))
        conn.commit()
        self.done = True

    def on_login_disconnect_packet(self, packet):
        #print("disconnected from game:",packet)
        self.done = True
コード例 #32
0
class Player:
    """
    A class built to handle all required actions to maintain:
     - Gaining auth tokens, and connecting to online minecraft servers.
     - Clientbound chat
     - Serverbound chat

    Warnings
    --------
    This class explicitly expects a username & password, then expects to
    be able to connect to a server in online mode.
    If you wish to add different functionality please view the example
    headless client, `start.py`, for how to implement it.
    """

    def __init__(self, username, password, *, admins=None):
        """
        Init handles the following:
         - Client Authentication
         - Setting the current connection state
         - Setting the recognized 'admins' for this instance

        Parameters
        ----------
        username : String
            Used for authentication
        password : String
            Used for authentication
        admins : list, optional
            The minecraft accounts to auto accept tpa's requests from

        Raises
        ------
        YggdrasilError
            Username or Password was incorrect

        """
        self.kickout = False
        self.admins = [] if admins is None else admins

        self.auth_token = authentication.AuthenticationToken()
        self.auth_token.authenticate(username, password)

    def Parser(self, data):
        """
        Converts the chat packet received from the server
        into human readable strings

        Parameters
        ----------
        data : JSON
            The chat data json receive from the server

        Returns
        -------
        message : String
            The text received from the server in human readable form

        """
        message = DefaultParser(data)  # This is where you would call other parsers

        if not message:
            return False

        if "teleport" in message.lower():
            self.HandleTpa(message)

        return message

    def HandleTpa(self, message):
        """
        Using the given message, figure out whether or not to accept the tpa

        Parameters
        ----------
        message : String
            The current chat, where 'tpa' was found in message.lower()

        """
        try:
            found = re.search(
                "(.+?) has requested that you teleport to them.", message
            ).group(1)
            if found in self.admins:
                self.SendChat("/tpyes")
                return
        except AttributeError:
            pass

        try:
            found = re.search("(.+?) has requested to teleport to you.", message).group(
                1
            )
            if found in self.admins:
                self.SendChat("/tpyes")
                return
        except AttributeError:
            pass

    def SendChat(self, msg):
        """
        Send a given message to the server

        Parameters
        ----------
        msg : String
            The message to send to the server

        """
        msg = str(msg)
        if len(msg) > 0:
            packet = serverbound.play.ChatPacket()
            packet.message = msg
            self.connection.write_packet(packet)

    def ReceiveChat(self, chat_packet):
        """
        The listener for ClientboundChatPackets

        Parameters
        ----------
        chat_packet : ClientboundChatPacket
            The incoming chat packet
        chat_packet.json : JSON
            The chat packet to pass of to our Parser for handling

        """
        message = self.Parser(chat_packet.json_data)
        if not message:
            # This means our Parser failed lol
            print("Parser failed")
            return

        print(message)

    def SetServer(self, ip, port=25565, handler=None):
        """
        Sets the server, ready for connection

        Parameters
        ----------
        ip : str
            The server to connect to
        port : int, optional
            The port to connect on
        handler : Function pointer, optional
            Points to the function used to handle Clientbound chat packets

        """
        handler = handler or self.ReceiveChat

        self.ip = ip
        self.port = port
        self.connection = Connection(
            ip, port, auth_token=self.auth_token, handle_exception=print
        )

        self.connection.register_packet_listener(
            handler, clientbound.play.ChatMessagePacket
        )

        self.connection.exception_handler(print)

    def Connect(self):
        """
        Actually connect to the server for this player and maintain said connection

        Notes
        -----
        This is a blocking function and will not return until `Disconnect()` is called on said instance.

        """
        self.connection.connect()

        print(f"Connected to server with: {self.auth_token.username}")

        while True:
            time.sleep(1)
            if self.kickout:
                break

    def Disconnect(self):
        """
        In order to disconnect the client, and break the blocking loop
        this method must be called

        """
        self.kickout = True
        self.connection.disconnect()
コード例 #33
0
class Main(object):
    def __init__(self, options):
        self.auth_token = authentication.AuthenticationToken()
        try:
            self.auth_token.authenticate(options.username, options.password)
        except YggdrasilError as e:
            print(e)
            sys.exit()
        print("Logged in as " + self.auth_token.username)
        self.network = Connection(options.address, options.port,
                                  self.auth_token)
        self.network.connect()
        self.register_listeners()
        #sys.stdout = Speaker(self)
        while not self.network.playing:
            pass
        self.respawn()
        while True:
            try:
                self.tick()
            except KeyboardInterrupt:
                print("Bye!")
                sys.exit()

    def register_listeners(self):
        self.network.register_packet_listener(self.print_chat,
                                              ChatMessagePacket)
        self.network.register_packet_listener(self.set_pos,
                                              PlayerPositionAndLookPacket)
        self.network.register_packet_listener(self.recieve_plugin_message,
                                              PluginMessage)
        self.network.register_packet_listener(self.set_health, UpdateHealth)

    def tick(self):
        text = input()
        self.speak(text)

    def speak(self, message):
        packet = ChatPacket()
        packet.message = message
        self.network.write_packet(packet)

    def set_health(self, health_packet):
        if health_packet.health == 0.0:
            print "RESPAWN"
            self.respawn()

    def respawn(self):
        packet = ClientStatus()
        packet.action_id = 0
        self.network.write_packet(packet)
        #print packet

    def print_chat(self, chat_packet):
        print type(chat_packet)
        print("Position: " + str(chat_packet.position))
        print("Data: " + chat_packet.json_data)

    def recieve_plugin_message(self, plugin_message):
        data = plugin_message.data.split("|")
        if len(data) == 2 and data[0] == "MC":
            if data[1] == "Brand": print "Brand:", plugin_message.channel
            else:
                print "PLUGIN MESSAGE:", data[1], plugin_message.channel