def run(self): self.logger.debug( "Checking if the server {} is online before connecting.") if not self.config.mc_online: self.logger.info("Connecting in offline mode...") while not self.is_server_online(): self.logger.info( 'Not connecting to server because it appears to be offline.' ) time.sleep(15) self.bot_username = self.config.mc_username self.connection = Connection( self.config.mc_server, self.config.mc_port, username=self.config.mc_username, handle_exception=self.minecraft_handle_exception) else: self.auth_token = authentication.AuthenticationToken() try: self.auth_token.authenticate(self.config.mc_username, self.config.mc_password) except YggdrasilError as ex: self.logger.info(ex) sys.exit(os.EX_TEMPFAIL) self.bot_username = self.auth_token.profile.name self.logger.info("Logged in as %s...", self.auth_token.profile.name) while not self.is_server_online(): self.logger.info( 'Not connecting to server because it appears to be offline.' ) time.sleep(15) self.connection = Connection( self.config.mc_server, self.config.mc_port, auth_token=self.auth_token, handle_exception=self.minecraft_handle_exception) self.register_handlers(self.connection) self.connection_retries += 1 self.reactor_thread.start() self.connection.connect() try: self.aioloop.run_until_complete( self.discord_bot.start(self.config.discord_token)) except (KeyboardInterrupt, SystemExit): # log out of discord self.aioloop.run_until_complete(self.discord_bot.logout()) # log out of minecraft self.connection.disconnect() # shut down auth server from twisted.internet import reactor reactor.callFromThread(reactor.stop) # clean up auth server thread self.reactor_thread.join() finally: # close the asyncio event loop discord uses self.aioloop.close() return self.return_code
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()
def connect(self): global viewing if viewing is None: viewing = self.email Connect.connections[str(self.authtoken.username)] = Connection(self.ip, self.port, auth_token=self.authtoken) connection = Connect.connections[str(self.authtoken.username)] def onjoin(packet): print(f"{Colors.colors['green']}[+] Connected as {self.authtoken.username}") time.sleep(Config.onjoin_wait_time) p = serverbound.play.ChatPacket() p.message = Config.onjoin_command connection.write_packet(p) connection.register_packet_listener(onjoin, clientbound.play.JoinGamePacket) c = Chat(self.email) connection.register_packet_listener(c.handleChatMessage, clientbound.play.ChatMessagePacket) if Config.autoreconnect_on: d = Disconnect(self.email, self.passw) connection.register_packet_listener(d.handleDisconnect, clientbound.play.DisconnectPacket) connection.connect()
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 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()
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
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 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()
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
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 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 #
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)
def create_conn(address, port, version, token): mc_conn = Connection( address=address, port=port, auth_token=token, initial_version=version, allowed_versions=[version], ) mc_conn.connect() return mc_conn
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 __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 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()
def __init__(self, terminal: Terminal, options: object): """ Parameters ---------- terminal : Terminal class representing and managing the terminal and it's subwindows options : object options parsed by the argument parser """ self._terminal = terminal auth_token = authentication.AuthenticationToken() if options.auth_type == 'Mojang': try: auth_token.authenticate(options.username, options.password) except YggdrasilError as e: print(e) sys.exit() # TODO Use correct status and not default to 0 as it's a failure self._client = Client(auth_token.profile.name, auth_token.profile.id_) self._terminal.info.update(self._client.name, util.format_uuid(self._client.uuid)) self._terminal.console.log('Successfully authenticated') self._address = options.address self._port = options.port self._connection = Connection(self._address, self._port, auth_token=auth_token) if hasattr(options, 'Bot'): self._bot = options.Bot(self._terminal, self._connection, self._client) else: self._bot = None self._register_listeners() self._connection.connect() while (True): key = self._terminal.stdscr.getkey() if (key == 'q'): sys.exit(0) if (key == 'KEY_UP'): self._terminal.console.scroll_up() elif (key == 'KEY_DOWN'): self._terminal.console.scroll_down() else: if hasattr(self._bot, 'keys') and key in self._bot.keys and inspect.ismethod(self._bot.keys[key]): self._bot.keys[key]()
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)
def __init__(self, account: str, password: str, server_address: str, port: int, version: int, auto_reconnect: bool, auto_respawn: bool, lang: Lang): self.__email = account self.__password = base64.b64encode(password.encode()) self.__lang = lang self.__logger = logging.getLogger("Auth") logging.basicConfig(level=logging.INFO) tokens = self.__get_tokens() self.__auth = authentication.AuthenticationToken( username=self.__email, access_token=tokens["access"], client_token=tokens["client"]) self.auth() self.__auto_reconnect = auto_reconnect self.__auto_respawn = auto_respawn self.__connection = Connection(address=server_address, port=port, initial_version=version, auth_token=self.__auth) if not self.__auth.authenticated: return self.username = self.__auth.profile.name self.__logger = logging.getLogger(self.username) self.__connection.register_packet_listener( self.handle_join_game, clientbound.play.JoinGamePacket) self.__connection.register_packet_listener( self.print_chat, clientbound.play.ChatMessagePacket) self.__connection.register_packet_listener( self.handle_disconnect, clientbound.play.DisconnectPacket) self.__connection.register_packet_listener( self.handle_health_change, clientbound.play.UpdateHealthPacket) self.__connection.register_exception_handler(self.handle_exception) try: self.__connection.connect() except Exception as e: self.__logger.error(str(e)) self.__retry()
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
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 make_connection(*args, **kwds): kwds['initial_version'] = self.earliest_version return Connection(*args, **kwds)
webhook_url = config['webhook'] ACCOUNT = config["mcAcc"].split(":") #ACCOUNT = 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('--> %s' % packet, file=sys.stderr) def print_outgoing(packet): print('<-- %s' % packet, file=sys.stderr)
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()
#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()
def make_connection(*args, **kwds): kwds["initial_version"] = self.lowest_version return Connection(*args, **kwds)
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()
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()
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)
raise ValueError("Invalid server address: '%s'." % options.server) options.address = match.group("host") or match.group("addr") options.port = int(match.group("port") or 25565) return options def useitem(): global connection global packet connection.write_packet(packet) 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) packet = minecraft.networking.packets.serverbound.play.UseItemPacket() packet.hand = 0 if options.dump_packets: