diff --git a/discord/client.py b/discord/client.py index 714fd0455..076c8c367 100644 --- a/discord/client.py +++ b/discord/client.py @@ -110,7 +110,6 @@ class Client(object): self.ws.opened = self._opened self.ws.closed = self._closed self.ws.received_message = self._received_message - self.ws.connect() # the actual headers for the request... # we only override 'authorization' since the rest could use the defaults. @@ -236,6 +235,7 @@ class Client(object): def _closed(self, code, reason=None): print('Closed with {} ("{}") at {}'.format(code, reason, int(time.time()))) + self._invoke_event('on_disconnect') def run(self): """Runs the client and allows it to receive messages and events.""" @@ -369,7 +369,8 @@ class Client(object): def login(self, email, password): - """Logs in the user with the following credentials. + """Logs in the user with the following credentials and initialises + the connection to Discord. After this function is called, :attr:`is_logged_in` returns True if no errors occur. @@ -378,6 +379,8 @@ class Client(object): :param str password: The password used to login. """ + self.ws.connect() + payload = { 'email': email, 'password': password @@ -407,6 +410,14 @@ class Client(object): self.ws.send(json.dumps(second_payload)) self._is_logged_in = True + def logout(self): + """Logs out of Discord and closes all connections.""" + response = requests.post(endpoints.LOGOUT) + self.ws.close() + self._is_logged_in = False + self.keep_alive.cancel() + + def logs_from(self, channel, limit=500): """A generator that obtains logs from a specified channel. diff --git a/docs/api.rst b/docs/api.rst index 9909bcd17..1b3648a6c 100644 --- a/docs/api.rst +++ b/docs/api.rst @@ -26,6 +26,10 @@ All events are 'sandboxed', in that if an exception is thrown while the event is Called when the client is done preparing the data received from Discord. Usually after login is successful and the :attr:`Client.servers` and co. are filled up. +.. function:: on_disconnect() + + Called when the client disconnects for whatever reason. Be it error or manually. + .. function:: on_message(message) Called when a message is created and sent to a server.