LoginSignup
serendip-IT
@serendip-IT (serendip -IT)

Are you sure you want to delete the question?

Leaving a resolved question undeleted may help others!

Account Activity APIでwebhookのPOSTリクエストを受信できない

解決したいこと

TwitterのAccount Activity APIで引用リツイートを検知したい。
(まずはその前段として、webhook(POSTリクエスト)を受け取れているかを確認するために、
受け取った時の処理として処理ファイルと同フォルダにファイルを生成させようとしています)

例)
Account Activity API + Python3で引用リツイートを検知したいです。
いろんなページを参考にしつつ、Flaskとmod_wsgiを導入し、
なんとかwebhookの登録とサブスクリプションの登録まではできました。

具体的には、まず下記フォルダにapp.pyを配置(CRCテスト用)

/home/webhook/twitter/app.py

from flask import Flask, request
import base64
import hashlib
import hmac
import json
application = Flask("application-name")
consumer_secret = 'xxxxx(自分のCSを記載)'
@application.route('/webhooks/twitter', methods = ['GET'])
def get():
    if 'crc_token' in request.args and len(request.args.get('crc_token')) == 48:
        crc_token = request.args.get('crc_token')
        sha256_hash_digest = hmac.new(consumer_secret.encode(), msg = crc_token.encode(), digestmod = hashlib.sha256).digest()
        response_token = 'sha256=' + base64.b64encode(sha256_hash_digest).decode()
        response = {'response_token': response_token}
        return json.dumps(response), 200, {'Content-Type': 'application/json'}
    return 'No Content', 204, {'Content-Type': 'text/plain'}

次に、「https://〇〇〇〇〇/webhooks/twitter」に飛んできたGETリクエスト、POSTリクエストを/home/webhook/twitter/app.pyに飛ばすためにtwitter.confを新規作成。

/etc/httpd/conf.d/twitter.conf

# twitter.conf
LoadModule wsgi_module /usr/lib64/python3.6/site-packages/mod_wsgi/server/mod_wsgi-py36.cpython-36m-x86_64-linux-gnu.so
WSGIPythonPath /home/webhook/twitter
WSGIScriptAlias / /home/webhook/twitter/app.py

<Directory /home/webhook/twitter>
        Require all granted
</Directory>

webhook登録情報

{"environments":[{"environment_name":"〇〇〇","webhooks":[{"id":"xxxxxxxxxxxxxx","url":"https://〇〇〇〇〇/webhooks/twitter","valid":true,"created_timestamp":"2022-01-26 19:17:01 +0000"}]}]}

都合上一部伏せ字にはしておりますが、このような状態で登録は完了しているので、
app.pyのレスポンスが正しく機能したのだと思います。
また、sbscriptions.jsonへの登録もうまくできていると思います。

発生している問題・エラー

上記前提の元、/home/webhook/twitter/app.pyに

@application.route('/webhooks/twitter', methods = ['POST'])
def post():
    f = open('/home/webhook/twitter/myfile.txt', 'w')
    f.write('こんにちは\n')
    f.close()

    return 'OK'

を追記して、一旦ツイッター側で何らかのアクションがありPOSTが飛んできた時に
「こんにちは」と書かれたファイルがローカルに書き出されるようにプログラムを
組んでみたのですが、何も起こりません。。

自分の予測ですが、

https://〇〇〇〇〇/webhooks/twitter

に飛んできたPOSTリクエストをapp.pyに飛ばせていないのかなと思ってましたが、
webhookの登録ができた = 上記URLのGETリクエストがapp.pyに到達して正常にリターンできた
だと思うので、迷宮入りしております。

TwitterのAccount Activity APIは参考文献も少なく、
VPS上でpythonを使ってやってる人が少ないようで、
なかなか解決に至らないため、ご教示いただければ大変幸甚です。

以上、よろしくお願いします。

0

No Answers yet.

Your answer might help someone💌