Skip to content

Instantly share code, notes, and snippets.

@GNQG
Last active April 23, 2017 12:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save GNQG/16678035f7ce8e440251e8bfe1370990 to your computer and use it in GitHub Desktop.
Save GNQG/16678035f7ce8e440251e8bfe1370990 to your computer and use it in GitHub Desktop.
Mastodon.pyでmstdn.jpのstreamを使いたいときの面倒をなくすあれ
#coding: utf-8
'''
mstdnjp.py - subclass of mastodon.Mastodon for mstdn.jp
original: Mastodon.py (MIT license)
https://github.com/halcy/Mastodon.py
license of this code: MIT license
http://opensource.org/licenses/mit-license.php
'''
from contextlib import closing
import requests
from mastodon import Mastodon, StreamListener
class MstdnJP(Mastodon):
"""
subclass of mastodon.Mastodon for mstdn.jp avoiding Streaming API problem
"""
__DEFAULT_BASE_URL = 'https://mstdn.jp'
__DEFAULT_BASE_URL_STREAMING = 'https://streaming.mstdn.jp'
__DEFAULT_TIMEOUT = 300
def __init__(self, client_id, client_secret = None, access_token = None,
api_base_url = __DEFAULT_BASE_URL, debug_requests = False,
ratelimit_method = "wait", ratelimit_pacefactor = 1.1, request_timeout = __DEFAULT_TIMEOUT):
Mastodon.__init__(self, client_id, client_secret, access_token,
api_base_url, debug_requests,
ratelimit_method, ratelimit_pacefactor, request_timeout)
self.api_base_url = self.__DEFAULT_BASE_URL
self.api_base_url_streaming = self.__DEFAULT_BASE_URL_STREAMING
def user_stream(self, listener):
return self.__stream('/api/v1/streaming/user', listener)
def public_stream(self, listener):
return self.__stream('/api/v1/streaming/public', listener)
def hashtag_stream(self, tag, listener):
return self.__stream('/api/v1/streaming/hashtag', listener, params={'tag': tag})
def __stream(self, endpoint, listener, params=None):
headers = {}
params = params or {}
if self.access_token != None:
headers = {'Authorization': 'Bearer ' + self.access_token}
else:
raise ValueError('Access token required')
with closing(requests.get(self.api_base_url_streaming + endpoint,
data=params, headers=headers, stream=True)) as r:
if not r.ok:
raise Exception(
'Invalid request, code: %s, body: %s' % (r.status_code, r.text))
listener.handle_stream(r.iter_lines())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment