Webは用いる人のリテラシーで決まる ウェブ運用と開発現場を経験したエンジニアのTIPS
TOP > BLOG > IT記事

Twitter APIを利用した分析ツールを作ったメモ

早川朋孝 早川朋孝
EC専門のSE

Twitter APIを利用した分析ツールを作ったのでそのメモとサンプルを公開する。下記はそのスクショで、だいたいこんな感じのグラフとなる。


Twitter APIで作った分析ツール

いたってシンプルなプログラムで、1週間のうちのどの曜日、どの時間帯に

  • 自分がツイートしているか
  • 自分のフォロワーが「いいね」しているか
  • 自分のフォロワーがツイートしているか

が、一つのグラフで可視化される。これによって、どの時間にツイートすれば効果的な反響が得られるかが分かる。

一般的にツイートすると反響が得られやすい効果的な時間帯があるなどと言われているが、それはあくまで一般論であって、それぞれの利用者にあてはまるかは分からない。だからデータに基づいてTwitterを運用しようというのが、このアプリを作った経緯である。

使用言語とライブラリー、ミドルウェアなど

  • Twitter API
  • chartjs
  • mysql
  • Flask
  • Python

仕様

APIにはデータ取得量に制限があるので、サンプルでは適宜必要なデータをDBに保存している。

Twitter API

Twitter APIを始めるに際しての一番の障害はapikeyの取得だと思う。これをクリアできれば、仕様はシンプルなので利用するのは簡単。

Twitter APIを利用したPythonのサンプルコード

ここではTwitterのアカウントを指定して、そのアカウントの基本情報とそのアカウントのフォロワー情報を取得するコードの例を載せる。こまかいところを突き詰めるとけっこうめんどかったりする。

user_id = row['follower_id']
basic_data = twitter_functions.get_user_info(user_id)
followers_count = basic_data['followers_count']
max_tweets_get_count = twitter_functions.get_how_many_times(basic_data['statuses_count'], count, max_count)
cursor = -1  #-1はAPIの初回を意味するようだ。仕様で設定する値

follower_id_list = []
follower_list, next_cursor = twitter_functions.get_follower_list(user_id, str(cursor), str(count), skip_status, execute_time, count)
follower_id_list.append(follower_list)
 
if next_cursor != '':
     cursor = next_cursor
#続いてidsを取得
request_ids = 'https://api.twitter.com/1.1/followers/ids.json' + '?screen_name=' + user_id
response = requests.get(request_ids, auth=local_auth)
number_follower = len(response.json()['ids'])
  
 #Twitter APIは一度に取得できる件数には上限があり、次のデータがある場合の処理
 if number_follower > 200:
    number_get_data = int(number_follower / count)
    #上限は1000人くらい、つまり5回にする
    if number_get_data > 5:
       number_get_data = 5
    elif number_follower <= 200:
       number_get_data = 1
  
 if cursor != '-1':
    for i in range(0, number_get_data):
       try:
          follower_ids, next_cursor = twitter_functions.get_follower_list(user_id, str(cursor),  str(count), skip_status, execute_time, count)
          follower_id_list.append(follower_ids)
          cursor = next_cursor
       except KeyError:
          pass
  
 sql = ('''
      INSERT INTO  table_name
      (id, name, screen_name, profile_image_url, protected, statuses_count, followers_count, friends_count, created_count, executed_at, url, favourites_count, lo    cation, new_id, get_count) 
      VALUES
       (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)
       ''')

sql_data_for_users = []
for rowj in follower_id_list:
   for row in rowj:
      if row['protected'] == False:
         tmp = (row['id'], row['name'], row['screen_name'], row['profile_image_url'], row['protected'], row['statuses_count'], row['followers_count'], row['friends_count'], row['created_at'], row['executed_at'], row['url'], row['favourites_count'], row['location'], row['new_id'], row['get_count'])
         sql_data_for_users.append(tmp)
     #鍵アカウントは飛ばす処理
     elif row['protected'] == True:
        pass
db_functions.db_create(sql, sql_data_for_users)

鍵アカウントは飛ばす処理をしないとエラーで止まる。同じことを書くけど、こういう処理をしないといけないからめんどい。ま、プログラムを書く以上は仕方ないか。

こちらは取得したデータにmysqlに保存するPyhtonのサンプルコード。

 def db_create(command, data):
     connector = MySQLdb.connect(host='127.0.0.1', db=setting.DB_NAME, user=setting.DB_USER, passwd=setting.DB_PW, charset="utf8")
     connector.cursorclass = MySQLdb.cursors.DictCursor
     cursor = connector.cursor()
     cursor.execute("SET NAMES utf8")
     cursor.execute = connector.cursor()
     try:
        cursor.execute.executemany(command, data)
     except MySQLdb._exceptions.IntegrityError:
        pass
     connector.commit()
     res = cursor.execute.fetchall()
     cursor.close()
     connector.close()

Pythonの場合は関数にreturnは必須です。データ保存するだけの処理でも、何らかの返値が必要となる。

本格的に利用したいという人はご相談ください。

×
このブログを書いてる人
早川 朋孝 EC専門のSE
IT業界歴20年のエンジニアです。ネットショップ勤務で苦労した経験から、EC・ネットショップ事業者に向けて、バックオフィス業務の自動化・効率化を提案するSEをしています。
プロフィール
API連携の相談にのります
趣味は読書、ピアノ、マリノスの応援など
PAGE TOP