RubyでTwitterBotを作ってみた(5 STEP)

RubyでTwitterBotを作ることにしました (・ε・)

仕様:
 1.定期postをする
 2.コメント付きRTをすると返信をする。
 3.posrデータとreplyデータはファイルから読み込む


STEP 1:メールアカウントの作成

まずはTwitter登録のためのメールアカウントを作成する。
Hotmailにて新規アカウントを作成。


STEP 2:Twitterアカウントの作成

次にBotTwitterアカウントを作成する。
Twitterの右下の新規登録から登録を行う。



STEP 3:TwitterDeveloperへの登録

次にTwitterアプリの登録をする。
TwitterDeveloperの右上の「ログイン」から先ほど作ったTwitterアカウントでログインをする。

次に「Create an app」からapp登録をする。

name:アプリケーション名
Description:説明
Website:なんでもOK!

初期状態ではRead onlyのみの設定になってる。
Read and Writeに変更しなければいけない。
「Setting」から変更を行う

「Application type」をRead and Writeに変更し、「Update this Twitter application's settings」をクリックし設定を保存する

「Detaile」に戻り、「Your access taken」の「Recreate my access taken」をし、トークンを作りなおす。



STEP 4:Rubyコードの記述

Rubyのバージョンは1.9を使用する

$ ruby -verion
ruby 1.9.2p290 (2011-07-09 revision 32553) [x86_64-linux]
-e:1:in `<main>': undefined local variable or method `rion' formain:Object (NameError)

Twitterにpostするためには以下のライブラリが必要である。
 require 'user_stream'
 require 'twitter'
基本的なインストール方法などはrubyでtwitterbotを作ってみるを参照。

& gem install twitter
& gem install userstream

今回は
1.定期postをするスクリプト
2.RTに対してreplyを送るスクリプト
の2つを作ることにした。

1.定期postをする

#!/usr/local/bin/ruby
# -*- coding: utf-8 -*-

require 'user_stream'
require 'twitter'
require 'pp'

#①〜④は下記の画像を参照して下さい
consumer_key = '①Consumer_keyを入力'
consumer_secret = '②Consumer_secret を入力'
oauth_token = '③Access_oken を入力'
oauth_token_secret = '④Access_token_secret を入力'

UserStream.configure do |config|
  config.consumer_key = consumer_key
  config.consumer_secret = consumer_secret
  config.oauth_token = oauth_token
  config.oauth_token_secret = oauth_token_secret
end

Twitter.configure do |config|
  config.consumer_key = consumer_key
  config.consumer_secret = consumer_secret
  config.oauth_token = oauth_token
  config.oauth_token_secret = oauth_token_secret
end

client = UserStream.client


line = 0
endline = 0

loop{

  # past.datを読み込み。行数を調べる
  open("past.dat") {|file|
    max = 0
    while l = file.gets
      max += 1
    end
    endline = max
  }

  # 1時間に1ツイートをするために…:00の時にツイートを行う
  t = Time.now
  if t.min == 0
    # 最後まで読み込んだら最初に1行目に戻る
    if line >= endline
        line = 0
    end 

    #1行ずつ読み込みツイートを行う
    open("past.dat") {|file|
      Twitter.update(file.readlines[line])   
      line += 1
    }
  end

  # sleepをしないとCPU負荷が高い
  sleep 60
}

DevelopersからOAouthのキーを調べる

past.dat

【平成21年度春期】問1 DNSキャッシュポイズニングに分類される攻撃はどれか。http://twitpic.com/9wsrpy
【平成21年度春期】問2 SSLを使用して通信を暗号化する場合、SSL-VPN装置に必要な条件はどれか。 http://twitpic.com/9wstg5
【平成21年度春期】問3 シングルサインオンの説明のうち、適切なものはどれか。 http://twitpic.com/9wtt5v
【平成21年度春期】問4 スパムメールの対策として、あて先ポート番号25番目のメールに対しISPが実施するOP25Bの説明はどれか。 http://twitpic.com/9wz6en 

2.RTに対してreplyを送る

#!/usr/local/bin/ruby
# -*- coding: utf-8 -*-

require 'user_stream'
require 'twitter'
require 'pp'

#①〜④は下記の画像を参照して下さい
consumer_key = '①Consumer_keyを入力'
consumer_secret = '②Consumer_secret を入力'
oauth_token = '③Access_oken を入力'
oauth_token_secret = '④Access_token_secret を入力'

UserStream.configure do |config|
  config.consumer_key = consumer_key
  config.consumer_secret = consumer_secret
  config.oauth_token = oauth_token
  config.oauth_token_secret = oauth_token_secret
end

Twitter.configure do |config|
  config.consumer_key = consumer_key
  config.consumer_secret = consumer_secret
  config.oauth_token = oauth_token
  config.oauth_token_secret = oauth_token_secret
end

client = UserStream.client

def reply tweet 
  open("question.dat") {|file|
    while l = file.gets
      ### quesion.datには[問題番号,答え,URL]がある
      data = l.split(",")

      ### 問題文を探す data[0]="【平成21年度春期】問1"
      if tweet.text.include?(data[0]) then

        ### 正誤 data[1]="イ"
        if tweet.text.index(data[1]) == 0 then
          str="正解!"
        else
          str="不正解"
        end

        ### data[2]="http://www.youtube.com/watch?v=dhAnF6eAhzY&fmt=18"
        reply = "#{str} 答え:#{data[1]} #{data[2]}"

        option = {"in_reply_to_status_id"=>tweet.id}
        msg = "@#{tweet.user.screen_name} #{reply}"

        ### メッセージをポストする
        Twitter.update msg,option
        break #while文を抜ける

      end
    end
  }

  

end

# filter.json 使ってみる
client.endpoint = 'https://stream.twitter.com/'

# "RT @security_past:"を含んだツイートに対して返信を行う
client.post('/1/statuses/filter.json', track: "RT @security_past:") do |status|
  reply status 
end
question.dat

【平成21年度春期】問1,イ,http://www.youtube.com/watch?v=dhAnF6eAhzY&fmt=18
【平成21年度春期】問2,ア,http://www.youtube.com/watch?v=aS6AvnRp6Bw&fmt=18
【平成21年度春期】問3,エ,http://www.youtube.com/watch?v=DBFDozKWcEY&fmt=18
【平成21年度春期】問4,イ,http://www.youtube.com/watch?v=kK74KG09-RU&fmt=18

STEP 5:スクリプトの起動

スクリプトを起動される。

$ ruby post.rb

しかし、これではログアウトするとスクリプトは止まってしまう。
そのために nohupコマンドを使う。

$ nohup ruby post.rb &

& はバックグラウンドで起動させる。
psコマンドでちゃんと起動できているかを確認!

$ ps aux | grep "ruby"
user   9024  0.0  0.7 168408 31592 ?        SNl  17:57   0:00 ruby reply.rb
user  12181  106  0.7 164436 31976 pts/3    RNl  21:23   0:06 ruby post.rb
user  12184  0.0  0.0  65452   852 pts/3    S+   21:23   0:00 grep ruby


以上で確認OK!!

じゃ実際に実行されているかを確認してみよう。


ってことで以上 \(^o^)/
お疲れ様です(^^ゞ


====================================
追記(1/20):
Twitterデベロッパーの画面が変更されていました。
リンク先はこちらか