def perform_handshake(self, connection, resume=False): """Waits for the gateway to say hello then identifies with it and waits for its READY acknowledgment. In the process the heartbeat interval and session ID are defined. Raises: AssertionError: Unexpected behaviour from the gateway during the handshake. KeyError: Handshake messages did not contain necessary information. """ payload = connection.receive_payload() assert payload == Payload.HELLO, "First message upon connection was not HELLO." self.heartbeat_period = payload.data["heartbeat_interval"] / 1000 # Identify if resume: payload = Payload.Resume(self.token, self.session_id, connection.last_seq) else: payload = Payload.Identify(self.token, self.OS, self.NAME) connection.send_payload(payload) # Get ready payload = connection.receive_payload() if payload == Payload.DISPATCH and payload.event_name == "READY": self.session_id = payload.data["session_id"] elif payload == Payload.INVALID: raise InvalidSessionException() else: self.process_payload(payload, connection)
def receive_payload(self): """Receives a payload packet from the websocket and stores its sequence number. Returns: A Payload object. """ packet = self.ws.recv() self.logger.info("Inc. packet: %s", packet[:1000]) if packet == "": raise DisconnectionException() payload = Payload.from_packet(packet) if payload.seq_number: self.last_seq = payload.seq_number return payload
def send_heartbeat(self, connection): payload = Payload(Payload.HEARTBEAT, data=connection.last_seq) connection.send_payload(payload)