3
4

More than 3 years have passed since last update.

Twitterから特定の単語を新着検索し、結果をLINEに通知する

Last updated at Posted at 2020-06-16

完成イメージ

スクリーンショット (50).png

環境

  • Windows10
  • Python 3.7.6
  • Jupyter Notebook

前提

Twitterの情報を扱うためにAPI登録を済ませておきましょう
Twitter API 登録 (アカウント申請方法) から承認されるまでの手順まとめ

準備

PythonでOAuth認証をするために、Requests-OAuthlib(ライブラリ)が必要です
コマンドプロンプトを起動して下記のコードを実行

pip install requests-oauthlib

この後ツイート検索に用いるOAuth1Sessionには下記の入力が必要

  • consumer_key
  • consumer_secret
  • acces_token
  • acces_token_secret

こちらを参考に進めてみてください
PythonでTwitterしてみた

config.py
consumer_key = '********'
consumer_secret = '********'
access_token = '********'
access_token_secret = '********'

*********に自分のキーをペーストしておきましょう!

Tweetを取得する

Tweet_search.py
import json,config
from requests_oauthlib import OAuth1Session

ck = config.consumer_key
cs = config.consumer_secret
at = config.access_token
ats = config.access_token_secret

twitter = OAuth1Session(ck, cs, at,ats)#OAuth認証


API_URL = "https://api.twitter.com/1.1/search/tweets.json?q="
keyword = "可愛い 猫 -RT"
what_type_result_data = "resent"  # mixed, recent, popular
how = 1
url = API_URL + keyword + "&result_type=" + what_type_result_data + "&count=" + str(how)
response = twitter.get(url)

response_data = json.loads(response.text) 
response_data #データ可視化

API_URLはTwitter Developerに記載されている、検索用ツールを用いたものです

  • keyword:検索したいワードを入力すると出力します
    and検索に対応、-RTで検索段階でリツイートの除外を推奨

  • what_type_result_date: recentは新着順表示です

  • howはツイートの取得数
    あとはgetメソッドを行い、jsonで読み込んでいます

実行するとこんな感じに表示されます

{'statuses': [{'created_at': 'Tue Jun 16 14:37:12 +0000 2020',
   'id': 1272901044272586754,
   'id_str': '1272901044272586754',
   'text': '努力しなくても可愛いのは猫だけ、、、、🤔',
   'truncated': False,
   'entities': {'hashtags': [],
    'symbols': [],
    'user_mentions': [],
    'urls': []},
   'metadata': {'iso_language_code': 'ja', 'result_type': 'recent'},
   'source': '<a href="http://twitter.com/download/iphone" rel="nofollow">Twitter for iPhone</a>',
   '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,
   'in_reply_to_screen_name': None,
   'user': {'id': 152910352,
    'id_str': '152910352',
    'name': 'ドライなマブ🎞',
    'screen_name': 'usarin_Dry_mabu',
    'location': 'ゆかり王国ときどき湘南',
    'description': '田村ゆかりさんのライブやイベントは大体参加/(・х・)\あとは上坂すみれさん高垣彩陽さん水樹奈々さん分島花音さんJUNNAさん石原夏織さんを中心に参加しています。',
    'url': None,
    'entities': {'description': {'urls': []}},
    'protected': False,
    'followers_count': 160,
    'friends_count': 414,
    'listed_count': 6,
    'created_at': 'Mon Jun 07 05:25:44 +0000 2010',
    'favourites_count': 9299,
    'utc_offset': None,
    'time_zone': None,
    'geo_enabled': True,
    'verified': False,
    'statuses_count': 19301,
    'lang': None,
    'contributors_enabled': False,
    'is_translator': False,
    'is_translation_enabled': False,
    'profile_background_color': 'DBE9ED',
    'profile_background_image_url': 'http://abs.twimg.com/images/themes/theme17/bg.gif',
    'profile_background_image_url_https': 'https://abs.twimg.com/images/themes/theme17/bg.gif',
    'profile_background_tile': True,
    'profile_image_url': 'http://pbs.twimg.com/profile_images/1198478023982346240/S3JxLKxY_normal.jpg',
    'profile_image_url_https': 'https://pbs.twimg.com/profile_images/1198478023982346240/S3JxLKxY_normal.jpg',
    'profile_banner_url': 'https://pbs.twimg.com/profile_banners/152910352/1590751230',
    'profile_link_color': 'CC3366',
    'profile_sidebar_border_color': 'DBE9ED',
    'profile_sidebar_fill_color': 'E6F6F9',
    'profile_text_color': '333333',
    'profile_use_background_image': True,
    'has_extended_profile': True,
    'default_profile': False,
    'default_profile_image': False,
    'following': False,
    'follow_request_sent': False,
    'notifications': False,
    'translator_type': 'none'},
   'geo': None,
   'coordinates': None,
   'place': None,
   'contributors': None,
   'is_quote_status': False,
   'retweet_count': 0,
   'favorite_count': 0,
   'favorited': False,
   'retweeted': False,
   'lang': 'ja'}],
 'search_metadata': {'completed_in': 0.019,
  'max_id': 1272901044272586754,
  'max_id_str': '1272901044272586754',
  'next_results': '?max_id=1272901044272586753&q=%E7%8C%AB%E3%80%80%E5%8F%AF%E6%84%9B%E3%81%84&count=1&include_entities=1&result_type=resent',
  'query': '%E7%8C%AB%E3%80%80%E5%8F%AF%E6%84%9B%E3%81%84',
  'refresh_url': '?since_id=1272901044272586754&q=%E7%8C%AB%E3%80%80%E5%8F%AF%E6%84%9B%E3%81%84&result_type=resent&include_entities=1',
  'count': 1,
  'since_id': 0,
  'since_id_str': '0'}}

これらを参考に必要な情報を抜き出します

Tweet_search.py
data = response_data['statuses'][0]
what = data['text']
twitter_url = 'https://twitter.com/yjbtjn/status/' + str(data['id'])
who = data['user']['name']#任意
when = data['created_at'][:19]#任意
where = data['place']#任意
profile =  data['description']#任意

output = (what) + (twitter_url)

上記のコードでは日時やユーザー情報といった必要以上の情報まで抽出していますが、最低限の情報だけ取得したい場合には、#任意と書かれている行は削除して構いません

output = (what) + (twitter_url) ではライン上で通知したい情報を入力しています
LINE上では最低限ツイート内容と発言者さえ分かれば良いと思うので、今回はwhattwitter_urlを使用します

LINEに送信する

今回使うのはLINE Notifyという、実行したものをLINEでキャッチするものです
LINE Notfyを使用するのもトークンが必要なので、こちらを参考に登録してみてください
Pythonの自動売買ボットからLINEへ通知を飛ばす方法〜仮想通貨自動売買〜

Tweet_search.py
import requests

def LineNotify(message):
    line_notify_token = "*********************************"
    line_notify_api = "https://notify-api.line.me/api/notify"

    payload = {"message":message}
    headers = {"Authorization":"Bearer " + line_notify_token}
    requests.post(line_notify_api, data = payload, headers = headers)

LineNotify(output)

トークンを******の部分にペーストしたら完成です!

定期実行について

windows内ですべて完結させる
今回はタスクスケジューラーというソフトを使って定期実行を行います
こちらを参考に進めてみてください
windows10でPythonスクリプトを定期的に自動実行する方法 タスクスケジューラ

エラーが頻発する場合

タスクスケジューラーは起動画面でエラーが頻発する不具合報告が上がっています
大抵の場合はこちらのブログで紹介されているツールで解決できます
タスクスケジューラーのエラーを修復してくれるツール RepairTask

参考にしたサイト

Twitter API 登録 (アカウント申請方法) から承認されるまでの手順まとめ

Pythonの自動売買ボットからLINEへ通知を飛ばす方法〜仮想通貨自動売買〜

windows10でPythonスクリプトを定期的に自動実行する方法 タスクスケジューラ

タスクスケジューラーのエラーを修復してくれるツール RepairTask

【Twitter×Python】自分専用のエゴサーチボットを作る方法

素人が今更Twitter APIで遊ぶ 〜その1〜

3
4
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
4