Twitter4R の使い方が、最低限わかって来たので、レンタルしているサーバー*1にスクリプトを仕込んでのメールから更新とできるようにしてみました。
ぼくは WillCom の PHS を使っているのですが、音声定額でオプションは止めてしまったの、メールは使い放題ですが。ネット接続は有料なので、メールで全部できると便利です。
|ruby|
!/usr/local/bin/ruby
post_twitter.rb
#
メールを受取って twitter に書き込み、タイムラインを取得
by Hiroshi Okada Released to public domain 2008-04-13
このプログラムは sandmail 等から機動されることを想定しています。
たとえば /etc/mail/aliases に
post100: |/usr/local/bin/post_twitter.rb
というような行を追加して newaliases しておきます。
#
設定ファイルの形式
twitter:
login: <Twitterのログイン名>
password: <Twitterのパスワード>
mail:
phone_mail: <携帯メールのアドレス>
this_mail: <このスクリプトのメールアドレス>
reply_subject: <返信メールのタイトル>
limit:
post_len: 5
max_timeline_num: 20
件名が post_len 未満のときは投稿はせずタイムライン取得のみ
取得するタイムラインは最大 max_timeline_num
require 'rubygems' gem 'twitter4r', '>=0.3.0' require 'twitter' require 'twitter/console' require 'time' require 'yaml' require 'mailread' require 'nkf' require 'net/smtp'
xml とか扱うコードは utf-8 で書いた方が嵌らない
$KCODE='utf-8'
class PostTwitter # 設定ファイルの名前 CONFILG_FILE_NAME = '/usr/local/etc/post_twitter.yaml'
# 初期化
def initialize
# 設定ファイルからメールアドレス等のパラメータを読みだす。
@config = YAML.load_file( CONFILG_FILE_NAME)
@this_mail_address = @config['mail']['this_mail']
@phone_mail_address = @config['mail']['phone_mail']
@reply_subject = @config['mail']['reply_subject']
@post_len = @config['limit']['post_len'].to_i
@max_timeline_num = @config['limit']['max_timeline_num'].to_i
# Twitterクライアントオブジェクトの準備
@twitter = Twitter::Client.from_config( CONFILG_FILE_NAME,'twitter')
end
# 実行
def run
# 標準入力からメールデータを読み込む
mail = Mail.new $stdin
header = mail.header
# From アドレスを比較して、一致しなければ何もしない
return if !header.has_key?( 'From') || !header['From'].include?( @phone_mail_address)
# twitter に投稿する(@post_len 以下の長さは無視する)
body = mail.body ? mail.body.join('') : ''
if body.length >= @post_len then
@twitter.status(:post, NKF.nkf('-w', body))
end
# friend のタイムラインを取得
timeline = @twitter.timeline_for(:friend)
# 返信用メールのヘッダ組立
mail_string = "From: #{@this_mail_address}\r\n" +
"To: #{@phone_mail_address}\r\n" +
"Subject: " + NKF.nkf('-WjM', @reply_subject) + "\r\n" +
"Content-Type: text/plain; charset=\"ISO-2022-JP\"\r\n" +
"Content-Transfer-Encoding: 7bit\r\n\r\n"
# 返信用メールのボディー
timeline[0..@max_timeline_num-1].each do | status |
mail_string += status.created_at.strftime('%H:%M') +
NKF.nkf( "-Wj", " #{status.user.screen_name} #{status.text}") + "\r\n"
end
# メール送信
Net::SMTP.start( 'localhost', 25 ) do |smtp|
smtp.send_mail mail_string, @this_mail_address, @phone_mail_address
end
end
end
PostTwitter.new.run
||< メールの本文に投稿する内容を、書くとその内容が書き込まれます。本文が空(もしくはとても短い)と何も投稿しない仕様です。
投稿の如何にかかわらず、タイムラインを返信するので、空メールを送って更新状況を確認できます。
なお、チェックは送り元メールアドレスしかチェックしていないので、セキュリティ的にはだめだめです。