LoginSignup
2
2

More than 5 years have passed since last update.

緊急地震速報をTwitterAPIとIFTTTで取得する Part2 #Webhook受信+TwitterAPI取得編

Last updated at Posted at 2019-01-30

Webhookを受信する

前回のパートでiftttに登録してWebhookが送信されるようになりました!
今回は実際にWebhookを受信していきます

今回書いていくプログラムのソースコード
https://harigami.net/contents?id=86eea9d9-eb77-47bc-9eaf-6848555820da

必要なライブラリのインポートと環境について

僕は
Windows 10 Home / Pro [Version 10.0.18317.1000]
Python 3.6.3
で開発しました
おそらくMacやLinuxでも動くとは思いますが動作未確認です
ご了承ください

以下ライブラリをpipでインストールしてください
- flask
- numpy
- requests_oauthlib
- pprint
ひとまずライブラリのインポートをしましょう!

get.py
import os
import time
from flask import Flask, render_template, request, redirect, url_for
import json
from requests_oauthlib import OAuth1Session
import pprint #デバッグ用
import numpy #今後使用予定..?

受信部のコードを書く

最初にIFTTTから送られてくる情報を確認しましょう!
test.com = サーバーのURL
12345 = ポート

http://test.com:12345/webhook/http://twitter.com/zishin3255/status/xxxxxxx
(一例: https://twitter.com/zishin3255/status/1089498436242567168)
....なんだこれは...w
[/]がいっぱいあるぞ...と最初は僕も思いましたが意外と簡単に解決できてですね...

get.py
twitter = OAuth1Session("APIKey", "API SECRET", "ACCESS TOKEN", "ACCESS TOKEN SECRET")
headers = {'content-type': 'application/json; charset=utf-8'}


app = Flask(__name__)

@app.route('/webhook/http://twitter.com/zishin3255/status/<text>', methods=['GET', 'POST'])
def index(text):
    title = "Hi"
    it = text.replace("!#http://twitter.com/honkeasari_eew/status/","")
    params = {"id":it}
    req = twitter.get("https://api.twitter.com/1.1/statuses/show.json", params = params)

    timeline = json.loads(req.text)
    pprint.pprint(timeline)
    return render_template('./index.html')


if __name__ == '__main__':
    app.debug = False
    app.run(host='0.0.0.0',port=12345) 

と一気に書きましたが..
まず見てほしいのがこの部分
@app.route('/webhook/http://twitter.com/zishin3255/status/<text>', methods=['GET', 'POST'])
なかなか無理やり書きましたが要は
test.com/webhook/http://twitter.com/zishin3255/status/までをURLにしてツイートIDだけをきれいに取得してみよう! と思ったら成功しちゃったパターンですw
まあ動けばどうでもいいんですけどね...(苦笑)
twitter = OAuth1Session("APIKey", "API SECRET", "ACCESS TOKEN", "ACCESS TOKEN SECRET")ここには TwitterDevelopersで取得したAPI Key,API Secret,AccessToken,AccessTokenSecretを入れてください
下のやつみたいに設定ファイル化してもいいかもです

settings.py
key = "" #API KEY
secret = "" #API SECRET
token = "" # ACCESS TOKEN 
token_s "" # ACCESS TOKEN SECRET
get.py
import settings
twitter = OAuth1Session(settings.key, settings.secret, settings.token, settings.token_s)

こんな感じですかね...
試しに
http://SERVERURL:12345/webhook/http://twitter.com/zishin3255/status/1089498436242567168
にアクセスしてみてください
SERVERURLにはこのプログラムを動かしているサーバーのIPやアドレスを
ポートはこのコードをそのまま使った場合は12345になります
おそらく以下のようにコンソールに表示されたと思います

{'contributors': None,
 'coordinates': {'coordinates': [125.3, 24.2], 'type': 'Point'},
 'created_at': 'Sun Jan 27 12:20:43 +0000 2019',
 'entities': {'hashtags': [{'indices': [75, 86], 'text': 'earthquake'}],
              'symbols': [],
              'urls': [],
              'user_mentions': []},
 'favorite_count': 8,
 'favorited': False,
 'geo': {'coordinates': [24.2, 125.3], 'type': 'Point'},
 'id': 1089498436242567168,
 'id_str': '1089498436242567168',
 'in_reply_to_screen_name': None,
 'in_reply_to_status_id': None,
 'in_reply_to_status_id_str': None,
 'in_reply_to_user_id': None,
 'in_reply_to_user_id_str': None,
 'is_quote_status': False,
 'lang': 'ja',
 'place': None,
 'retweet_count': 0,
 'retweeted': False,
 'source': '<a href="https://zishin.mitsugogo.tech/" '
           'rel="nofollow">緊急地震速報BOT1号機</a>',
 'text': '■■緊急地震速報(第3報)■■ 宮古島近海で地震 最大震度 2(推定) [詳細] 2019/01/27 21:20:00発生 M4.5 '
         '深さ10km #earthquake',
 'truncated': False,
 'user': {'contributors_enabled': False,
          'created_at': 'Mon Oct 26 06:15:19 +0000 2009',
          'default_profile': True,
          'default_profile_image': False,
          'description': '2019/1/27より、お試しで稼働再開しました。【高度利用者向け緊急地 震速報】を利用しています。M3.0または最大震度1以上と推定されたときにつぶやきます。大きな地 震のみ知りたい方は '
                         '@zishin3255_2 をご利用ください。  中の人は @mitsugogo',
          'entities': {'description': {'urls': []},
                       'url': {'urls': [{'display_url': 'zishin.mitsugogo.tech',
                                         'expanded_url': 'https://zishin.mitsugogo.tech/',
                                         'indices': [0, 23],
                                         'url': 'https://t.co/I8Xqoy3Ae3'}]}},
          'favourites_count': 12,
          'follow_request_sent': False,
          'followers_count': 225631,
          'following': False,
          'friends_count': 8,
          'geo_enabled': True,
          'has_extended_profile': False,
          'id': 85251743,
          'id_str': '85251743',
          'is_translation_enabled': False,
          'is_translator': False,
          'lang': 'ja',
          'listed_count': 10325,
          'location': '日本',
          'name': '緊急地震速報bot(β)',
          'notifications': False,
          'profile_background_color': 'C0DEED',
          'profile_background_image_url': 'http://abs.twimg.com/images/themes/theme1/bg.png',
          'profile_background_image_url_https': 'https://abs.twimg.com/images/themes/theme1/bg.png',
          'profile_background_tile': False,
          'profile_image_url': 'http://pbs.twimg.com/profile_images/1887652050/20_normal.jpg',
          'profile_image_url_https': 'https://pbs.twimg.com/profile_images/1887652050/20_normal.jpg',
          'profile_link_color': '1DA1F2',
          'profile_sidebar_border_color': 'C0DEED',
          'profile_sidebar_fill_color': 'DDEEF6',
          'profile_text_color': '333333',
          'profile_use_background_image': True,
          'protected': False,
          'screen_name': 'zishin3255',
          'statuses_count': 39485,
          'time_zone': None,
          'translator_type': 'none',
          'url': 'https://t.co/I8Xqoy3Ae3',
          'utc_offset': None,
          'verified': False}}

次回はここから必要なデータを取り出してポップアップウィンドウで表示するようにしようと思います!

2
2
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
2
2