From ab60931620066f6704be3010903f779b3cb9c71a Mon Sep 17 00:00:00 2001 From: Will Thompson Date: Sun, 9 Apr 2017 10:21:56 +0100 Subject: Initial implementation of streaming API This is missing any error handling and rate-limiting around the stream itself, but once the stream is established, the full range of events are supported. Fixes issue #14. --- mastodon/Mastodon.py | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) (limited to 'mastodon/Mastodon.py') diff --git a/mastodon/Mastodon.py b/mastodon/Mastodon.py index 9967bdb..493fb40 100644 --- a/mastodon/Mastodon.py +++ b/mastodon/Mastodon.py @@ -12,6 +12,9 @@ import datetime import dateutil import dateutil.parser +from contextlib import closing + + class Mastodon: """ Super basic but thorough and easy to use mastodon.social @@ -578,6 +581,37 @@ class Mastodon: media_file_description = (file_name, media_file, mime_type) return self.__api_request('POST', '/api/v1/media', files = {'file': media_file_description}) + def user_stream(self, listener): + """ + Streams events that are relevant to the authorized user, i.e. home + timeline and notifications. 'listener' should be a subclass of + StreamListener. + + This method blocks forever, calling callbacks on 'listener' for + incoming events. + """ + return self.__stream('/api/v1/streaming/user', listener) + + def public_stream(self, listener): + """ + Streams public events. 'listener' should be a subclass of + StreamListener. + + This method blocks forever, calling callbacks on 'listener' for + incoming events. + """ + return self.__stream('/api/v1/streaming/public', listener) + + def hashtag_stream(self, tag, listener): + """ + Returns all public statuses for the hashtag 'tag'. 'listener' should be + a subclass of StreamListener. + + This method blocks forever, calling callbacks on 'listener' for + incoming events. + """ + return self.__stream('/api/v1/streaming/hashtag', listener, params={'tag': tag}) + ### # Internal helpers, dragons probably ### @@ -710,6 +744,20 @@ class Mastodon: return response + def __stream(self, endpoint, listener, params = {}): + """ + Internal streaming API helper. + """ + + headers = {} + if self.access_token != None: + headers = {'Authorization': 'Bearer ' + self.access_token} + + url = self.api_base_url + endpoint + with closing(requests.get(url, headers = headers, data = params, stream = True)) as r: + listener.handle_stream(r.iter_lines()) + + def __generate_params(self, params, exclude = []): """ Internal named-parameters-to-dict helper. -- cgit v1.2.3