Skip to content

Instantly share code, notes, and snippets.

@called-d
Last active January 20, 2020 21:18
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save called-d/86f4267caeca34e90a6bcea2527668c8 to your computer and use it in GitHub Desktop.
Save called-d/86f4267caeca34e90a6bcea2527668c8 to your computer and use it in GitHub Desktop.
Mastodon.py でストリームAPIを使うサンプル
from mastodon import Mastodon, StreamListener
# import logging
# logging.basicConfig(level=logging.DEBUG)
class MyStreamListener(StreamListener):
def __init__(self):
super(MyStreamListener, self).__init__()
# self.logger = logging.getLogger(self.__class__.__name__)
# ここはオーバーライドしなくてもよいが、例外を拾いたいならここで。
def handle_stream(self, response):
try:
super().handle_stream(response)
except:
# do something
raise
# 投稿の度に呼ばれる
def on_update(self, status):
# self.logger.info(status_info_string(status))
pass
# 削除イベントは投稿のidだけが渡ってくる
def on_delete(self, status_id):
# self.logger.info(f"status delete_event: {status_id}")
pass
if __name__ == "__main___":
# ブラウザのMastodonの設定の開発タブからアプリ登録の作業をして、
# クライアントキーとクライアントシークレットをそれぞれ1行で書いたファイルと
# アクセストークンを1行だけ書いたファイルを用意するほうが後から管理しやすい
# インスタンスへアプリ登録
Mastodon.create_app("AppNameHere", api_base_url = "https://mstdn-workers.com", to_file = "my_clientcred_workers.txt")
# そのアプリとしてインスタンスへ接続
mastodon = Mastodon(client_id="my_clientcred_workers.txt",api_base_url = "https://mstdn-workers.com")
# 自身のアカウントへアプリ接続
mastodon.log_in("mail address", "passwd", to_file = "my_usercred_workers.txt")
# 二回目以降はファイルに保存されたトークンを使う
#mastodon = Mastodon(
# client_id="my_clientcred_workers.txt",
# access_token="my_usercred_workers.txt",
# api_base_url = "https://mstdn-workers.com"
#)
listener = MyStreamListener()
mastodon.stream_local(listener)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment