3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

twurlを使ってユーザをTwitter Account Activity APIでsubscribeする

Posted at

Twitter Account Activity APIでは、以下のURLへPOSTリクエストを送ることでイベントを購読するユーザを登録できる。

https://api.twitter.com/1.1/account_activity/all/dev/subscriptions.json

登録時しかリクエストを送らないので、わざわざコードを書くよりもInsomniaなどで送ると楽。
Twitter Appを作成した時のConsumer Key, Consumer Secret, Access Token, Access Token Secretを使ってOAuth1認証すれば良い。

が、このAPIはpayloadを何も受け付けない(Premium版のみ。Enterprise版はwebhook_idをbodyで受け取る)。購読対象のユーザはAccess Token/Secretを発行したユーザになる。
App作成時のTokenでは、Developerとして登録したTwitterアカウントのイベントを購読してしまうが、大体の場合はbot用アカウントのイベントを拾いたいため、そちらを登録する必要がある。

WebでのOAuth認証を実装すればToken発行はできるのだが、今回は一般ユーザが自由に購読できるようなものではなくbotがリプライに反応するために使いたいだけなので、わざわざ実装するのがめんどくさい。bot用のTokenぐらいもっと手軽に発行できないのだろうか?と思っていたところ、twurlを使うといいよと書いてあった。gemでインストールできる。

$ gem install twurl

CONSUMER KEYとCONSUMER SECRETを使って認証する。以下のコマンドを実行するとブラウザが開くので、表示されたPINを入力する。(historyに残るのが嫌だったので環境変数から取っているが、別に直接渡しても良い)

$ twurl authorize --consumer-key $TWITTER_CONSUMER_KEY \
                  --consumer-secret $TWITTER_CONSUMER_SECRET

認証に成功すると~/.twurlrcが生成されており、ここに書かれている認証情報を使って上記のAPIを叩けば、このユーザが購読開始される。

---
profiles:
  screen_name:
    consumer_key_will_be_insert_here:
      username: sutaba_police
      consumer_key: xxxxxxxx
      consumer_secret: xxxxxxx
      token: xxxxxxx # <- Access Token
      secret: xxxxxxxx # <- Access Token Secret
configuration:
  default_profile:
  - screen_name
  - consumer_key_will_be_insert_here

もし既にイベントを受け取るwebhookを登録していれば、適当なツイートにLikeしてみるとfavorite_eventsが飛んでくるのがわかる。

3
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?