Account Activity APIの特定のイベントだけ受信するwebhookの設定
やりたいこと
Account Activity APIの特定のイベントだけ受信するwebhookの設定
現状、すべてのアクティビティ(リプライやRT、ファボなど)に対してwebhook側が受信してしまうので、リプライ(tweet_create_events)があった場合のみ受信を行えるようにしたい。
方法
イベントを受信した際に呼ばれるwebhook
関数に対して、特定の条件下にのみ実行されるようにデコレータを自作し実装する。
以下、特定の条件
- 受信したイベントのアクティベィティがtweet_create_eventsである かつ
- 受信したイベントは自分のアカウントのアクティビティでない
対応前
@csrf_exempt def webhook(request): """webhook""" body = request.body.decode('utf-8') json_body = json.loads(body) .... ....
実装
tweet_replyは自作したデコレータ。これをwebhook関数にかけてあげれば完成。
def tweet_reply(func): def checker(request): body = request.body.decode('utf-8') json_body = json.loads(body) isTweetCreateEvents = ('tweet_create_events' in json_body) if isTweetCreateEvents: user_id_str = json_body['tweet_create_events'][0]['user']['id_str'] isMyUserId = (user_id_str == my_user_id) if not isMyUserId: # func(≒ webhook関数)を実行 func(request) return checker .... .... @csrf_exempt @tweet_reply def webhook(request): """webhook""" body = request.body.decode('utf-8') json_body = json.loads(body) .... ....
ただ、RTを拾ってしまうので、もう少し条件とtweetオブジェクトの調査が必要そう。