9/12/2011

pTerm

facebook, twitterの両方に、Macのターミナルからポストするrubyのスクリプト。

何しろ素人なので、コードを公開するのは、恥ずかしいが、そんなことを言っていると、語学と同じでいつまで経っても上達しないので..。

require 'rubygems'
require 'net/https'
require 'oauth'
require 'uri'
require 'yaml'

# Facebook
class Facebook
  attr_accessor :conf
  ACCESS_TOKEN= 'access_token'
  MESSAGE = 'message'

  def initialize (conf_from_yaml)
    @conf = conf_from_yaml ["facebook"]
  end

  def post ( message )
    https = Net::HTTP.new('graph.facebook.com', 443)
    https.use_ssl = true
    https.verify_mode = OpenSSL::SSL::VERIFY_NONE

    post_hash = { ACCESS_TOKEN => conf[ACCESS_TOKEN], MESSAGE => message }
    msg = post_hash.map { |key,value|
        "#{URI.encode(key)}=#{URI.encode(value)}"
        }.join("&")

    https.start{
      response = https.post('/me/feed', msg)
    puts response.body
    }
  end
end

#Twitter
class Twitter
  KEY          = 'consumer_key'
  SECRET       = 'consumer_secret'
  TOKEN        = 'access_token'
  TOKEN_SECRET = 'access_token_secret'
  UPDATE_URL   = 'https://api.twitter.com/1/statuses/update.xml'

  attr_accessor :config

  def initialize (conf_from_yaml)
    @config =conf_from_yaml ["twitter"]
  end

  def post (msg)
    consumer = OAuth::Consumer.new(config[KEY], 
      config[SECRET],
      :site => 'http://api.twitter.com')
    token_hash = {
      :oauth_token => config[TOKEN],
      :oauth_token_secret => config[TOKEN_SECRET]
    }
    access_token = OAuth::AccessToken.from_hash(consumer, token_hash)
    msg_hash = { :status => msg}
    response = access_token.post( UPDATE_URL, msg_hash )
  end
end

# YAMLファイル読み込み
class Config_setup
  attr_accessor :conf_pTerm

  def initialize
    @conf_pTerm = YAML.load_file("/Users/tom/pTerm_config.yaml")
  end
end

# argument解析
class Arguments
  attr_accessor :facebook, :twitter, :message, :msg_length, :url

  def initialize
    @facebook = true
    @twitter = true
    @message = ""
    @url = ""
    @msg_length = 0
  end

  def analyse (argv)
    argv.each { |arg|
    case arg
    when /-f/
      @facebook = false
    when /-t/
      @twitter = false
#    when /^http:\/\/.+?/i
#      @url = arg
    else
      @message = arg
      @msg_length = arg.split(//u).length
    end
    }
  end

  def display
    print "facebook= ", @facebook, ",   twitter= ", @twitter, "   文字数= ", @msg_length, " 文字", "\n"
    print "本文= ", @message, "\n"
  end
end

# main
conf = Config_setup.new
arg = Arguments.new
arg.analyse(ARGV)
arg.display

print "post ? (y/n):  "
if STDIN.getc == 121 then
  puts "posting..."

    # twitterにPOST
   if arg.twitter then
     tw =Twitter.new(conf.conf_pTerm)
     tw.post( arg.message )
     print "Twitter: posted !", "\n"
   end

   # facebookにPOST
   if arg.facebook then
     fb = Facebook.new(conf.conf_pTerm)
     response = fb.post( arg.message )
     print "Facebook posted !", "\n"
   end
  else 
    puts "not posted, nothing happened"
end