社会ノマド

備忘録と書きもの練習帳。とくに何らかのハンドリング系と、雑多な話題に関する読書録になるかなと思います。

過去50ツイート時間をリプで返す

リプライで「おい」と飛んできたら、飛ばしてきたアカウントの過去50ツイートのツイート時間を返すbotの作成。下記の機能をtwitterに実装したものです。

こんな感じを目指します。 f:id:zawazawalong:20151210160934p:plain

#!/usr/local/bin/ruby -Ku

require 'kconv' 
require 'twitter'

client = Twitter::REST::Client.new do |config|
  config.consumer_key = "なんとか"
  config.consumer_secret = "かんとか"
  config.access_token        = "うんとか"
  config.access_token_secret = "すんとか"
end


recentid = ツイート取得id初期値 #client.mentions_timeline[0].id とかで得られます

loop{
  ripu = client.mentions_timeline(:since_id => recentid)  #リプライを取得
  if ripu.size != 0
      for i in 0..(ripu.size-1)
        if ripu[i].text.index(/おい/).class==Fixnum  #「おい」を含むか判定
            user_id = ripu[i].user.id
    
            #カウント配列に0をセット
            tweet_counts = []
            (0..23).each { |j| tweet_counts[j] = 0 }
    
            #順番に該当時をカウント(本当は50より大きくしたいけどこれ以上にすると140字を超える)
            client.user_timeline(user_id, { count: 50 } ).each do |tweet|
                tweet_counts[tweet.created_at.hour] += 1
            end
            
            #リプ内容を作る(#のヒストグラム)
            hoge = ""
            (0..23).each do |j|
              hoge = hoge + "%02d"% j+"#" * tweet_counts[j] + "\n" 
            end
    
            post = "@#{ripu[i].user.screen_name} \n#{hoge}"
    
            twi_id=ripu[i].id
            client.update(post, {:in_reply_to_status_id => twi_id })
        end
      end
      
    # recentidの更新
    recentid = ripu[0].id
  end
  
  # 60秒ごとに稼働させる 
  sleep(60)
}