MacでRuby2.1を使い、Twitterのbotを作成する。
★★以下も合わせてどうぞ★★
■目的
改行区切りのリストをファイル(post.dat)から読み込み、ランダムに選択した行の文字列をツイートする。
※似たような生地はいっぱいありますが、gemのTwitterが更新されてクラス名などが大幅に変更されているため動かなかったので記事にしました。
■環境
mac osx mavericks
■事前準備
1. http://brew.sh/ 「homebrew」を入れます。
ruby -e "$(curl -fsSL https://raw.github.com/Homebrew/homebrew/go/install)"
2. opensslをいれます。
brew install openssl
3. gemでtwitterを入れます。
gem install twitter
4. gemでuserstreamを入れます。
gem install userstream
これで環境の準備は完了です。
次にアプリを銅させるため、
- CONSUMER_KEY
- CONSUMER_SECRET
- OAUTH_TOKEN
- OAUTH_TOKEN_SECRET
を取得します。
以下のサイトが非常に参考になります。
10分でできるTwitter bot @ Ruby - 酒と泪とRubyとRailsと
irbを使用して上記コードを取得するところまで実施してください。
いよいよプログラムですが、以下のようになります。
■post.rb
#!/usr/bin/ruby # -*- coding: utf-8 -*- require 'user_stream' require 'twitter' consumer_key = '取得したCONSUMER_KEY' consumer_secret = '取得したCONSUMER_SECRET' oauth_token = '取得したOAUTH_TOKEN' oauth_token_secret = '取得したOAUTH_TOKEN_SECRET' #config実施 client = Twitter::REST::Client.new do |config| config.consumer_key = consumer_key config.consumer_secret = consumer_secret config.access_token = oauth_token config.access_token_secret = oauth_token_secret end #行数を調べる max = 0 open('post.dat','r:utf-8'){|file| while file.gets max += 1 end } #ランダムな行数を指定しつぶやく rand = rand(max) open('post.dat', 'r:utf-8'){|file| client.update(file.readlines[rand]) }
■post.dat
つぶやきないよう1 つぶやきないよう2 つぶやきないよう3
あとはcronにぶっ込んでおけば勝手につぶやきます。
例:30分に一度つぶやく