Invalid URL 'URL': No schema supplied. Perhaps you meant http://URL?の対処方法
事象
AWSのlambdaをテスト実行していたら。 以下のエラーが発生。
Response: { "errorMessage": "Invalid URL 'URL': No schema supplied. Perhaps you meant http://URL?", "errorType": "MissingSchema", .... ....
原因
urlの指定は問題なかったが、lambda新規作成時の環境変数がうまく読み込めていなかった。
import requests import os def lambda_handler(event, context): res = do() # APIのURL url = "https://chickenvoice.herokuapp.com/api/do_tweet" # APIを叩く r = requests.get(url) print('success', r) def do(): res = requests.get(os.environ.get('URL')) ←こいつでアウチ return res
対応方法
import requests import os def lambda_handler(event, context): # res = do() # APIのURL url = "https://chickenvoice.herokuapp.com/api/do_tweet" # APIを叩く r = requests.get(url) print('success', r) def do(): # res = requests.get(os.environ.get('URL')) return res
Account Activity APIでidsから@以下の情報(アカウント)を取得する
目的
上の記事で取得したidsから、ユーザ情報を取得して、@~~以下の文字列(アカウント情報)を取得する
方法
#botのAccessToken/AccessSecret/CustomerKey/CustomerSecretを設定 CK = ... CS = ... AT = ... AS = ... # OAuth認証 twitter = OAuth1Session(CK, CS, AT, AS) # ユーザー情報取得のリクエストを送る user_req = twitter.get(user_url, params = user_params) user_req2 = user_req.json() print(user_req2['screen_name'])
user_req2['screen_name']に@~~以下の文字列(アカウント情報)が保存される。
参考記事
Account Activity APIでフォロワーリスト(ids)を取得する。
目的
Account Activity APIをpythonで利用してフォロワーを取得する
方法
... # フォロワー取得するURLの設定 url = 'https://api.twitter.com/1.1/followers/ids.json' params = { 'cursor': '-1', 'screen_name': screen_name, 'count': '5000' } #botのAccessToken/AccessSecret/CustomerKey/CustomerSecretを設定 CK = ... CS = ... AT = ... AS = ... # OAuth認証 twitter = OAuth1Session(CK, CS, AT, AS) # webhookは登録済 req = twitter.get(url, params = params) json_req = req.json() print('json_body2 確認', json_req['ids'])
json_req['ids']にscreen_name
で指定したユーザのフォロワーが5000まで取得できる。cursorは-1を指定すると最近フォローされたユーザ順に取得される。
※idsに格納されているアカウントは@に続く文字列ではないので、別途user情報を取得する必要がある。
Error at webhook: 400 {"errors":[{"code":214,"message":"Webhook URL does not meet the requirements. Invalid CRC token or json response format."}]}の対処
事象
twitrer Account Activity APIの技術調査にて以下のエラーが発生。
Error at webhook: 400 {"errors":[{"code":214,"message":"Webhook URL does not meet the requirements. Invalid CRC token or json response format."}]}
原因
Django側のwebhookでCRCのテストに合格できていない。
対応方法
from django.views.decorators.csrf import csrf_exempt from django.shortcuts import render from django.http import HttpResponse import base64 import hashlib import hmac import json # Create your views here. def test_view(request): """テストページ""" return HttpResponse('テストページ') @csrf_exempt def webhook(request): """webhook""" key = ':API secret key'.encode() msg = request.GET.get('crc_token') msg_bytes = msg.encode() hash = hmac.new(key, msg=msg_bytes, digestmod=hashlib.sha256).digest() twitter_response = {'response_token': 'sha256=' + base64.b64encode(hash).decode()} return HttpResponse(json.dumps(twitter_response), content_type='application/json')
Error at webhook: 401 {"errors":[{"code":32,"message":"Could not authenticate you."}]}の対処
事象
twitterのAccount Activity APIの利用時にwebhookの登録を行いたいが以下のエラーが発生
Error at webhook: 401 {"errors":[{"code":32,"message":"Could not authenticate you."}]}
原因
postするURLとパラメータを分離して書く必要があるっぽい。
... url = 'https://api.twitter.com/1.1/account_activity/all/:環境名/webhooks.json?url=:webhookのアドレス' twitter = OAuth1Session(CK, CS, AT, AS) req = twitter.post(url) ....
対応方法
以下のようにパラメータとしてwebhookアドレスを指定したら認証できた。
... url = 'https://api.twitter.com/1.1/account_activity/all/:環境名/webhooks.json' params = {"url": ":webhookのアドレス'"} twitter = OAuth1Session(CK, CS, AT, AS) req = twitter.post(url, params = params) ....
だけど、以下のエラーが今度はでた。 webhookに対するCRCテスト?が合格できていないよう。
Error at webhook: 400 {"errors":[{"code":214,"message":"Webhook URL does not meet the requirements. Invalid CRC token or json response format."}]}
chicken voiceの作成備忘録(4)〜Herokuにデプロイ〜
TwitterのAccount Activity APIを利用してリプライのトリガを構築するので、先にdjangoをHerokuにデプロイしておく。
「gunicorn」および「django-heroku」のインストール
$ pip3 install gunicorn django-heroku
以下のエラーがでてきた。
Error: pg_config executable not found. pg_config is required to build psycopg2 from source. Please add the directory containing pg_config to the $PATH or specify the full executable path with the option: python setup.py build_ext --pg-config /path/to/pg_config build ...
pg_configはpostgresqlに含まれてるようなので、以下を実行
$ brew install postgresql
再度インストールする。
$ pip3 install gunicorn django-heroku ... ... Successfully built psycopg2 Installing collected packages: gunicorn, dj-database-url, whitenoise, psycopg2, django-heroku Successfully installed dj-database-url-0.5.0 django-heroku-0.3.1 gunicorn-20.0.4 psycopg2-2.8.4 whitenoise-5.0.1
正常に終了した◎
実行環境ファイルの作成
- runtime.txt Pythonのバージョン指定
python-3.7.6
- Procfile Herokuプロセスの起動コマンド
web: gunicorn chickenvoice.wsgi --log-file -
- requirements.txt 依存パッケージのリスト freezeで自動生成する
$ pip3 freeze > requirements.txt
設定ファイルの作成・変更
- local_settings.pyの作成
import os DEBUG = True
- setting.pyの末尾に設定を追記
... ... # herokuの設定 DEBUG = False # herokuの設定 Falseに設定 try: from .local_settings import * except ImportError: pass if not DEBUG: import django_heroku django_heroku.settings(locals())
- ALLOWED_HOSTS設定 herokuで使えるようにsettings.pyにて修正
ALLOWED_HOSTS = ['*']
- .gitignoreの追加 local_settings.pyの追加
chicken_twitterAPI chickenEnv db.sqlite3 __pycache__ .DS_Store local_settings.py
Herokuの準備
- Heroku CLIインストール
$ brew tap heroku/brew && brew install heroku
インストール完了後ログインする。
$ heroku login ... Logging in... done Logged in as ...
- プロジェクトの作成
$ heroku create chickenvoice
- Herokuにプッシュする
$ git push heroku master
以下のコマンドを実行しろとエラーが吐かれたので実行
$ heroku config:set DISABLE_COLLECTSTATIC=1
- Dynoを起動させる
heroku ps:scale web=1
- データベース設定
$ heroku run python3 manage.py migrate $ heroku run python3 manage.py createsuperuser
- 画面確認
$ heroku open
chicken voiceの作成備忘録(3)〜twitterAPIの利用〜
tweepyのインストール
$ pip3 install tweepy
つぶやくスクリプトの作成
import tweepy # 各種キーを代入する CK = 'xxx' CS = 'xxx' AT = 'xxx' AS = 'xxx' # Twitterオブジェクトの生成 auth = tweepy.OAuthHandler(CK, CS) auth.set_access_token(AT, AS) api = tweepy.API(auth) print("何をつぶやきますか?") tweet = input('>> ') print("----------------------------------------------------") # ツイート api.update_status(tweet) print("終了")
実行してみる
$ python3 tweet.py 何をつぶやきますか? >>テスト実行 終了
いい感じ。