コマンドラインでツイートするRubyスクリプト

komatagaさんのブログ記事、『非同期コミュニケーションツール』を読んで、「vimでプログラミング中でも、外部コマンド実行でツイートできたらなぁ...」と思い、作ってみました。

[追記:2/11 1:54]
Google URL Shortener APIでURLを短縮化するバージョンを作ってみました。-> 『コマンドラインでツイートするRubyスクリプト(つづき)

ソース

#!/usr/bin/env ruby
$KCODE = 'u'

require 'fileutils'
require 'yaml'
require 'rubygems'
require 'oauth'

class Tw
  KEY          = 'consumer_key'
  SECRET       = 'consumer_secret'
  TOKEN        = 'access_token'
  TOKEN_SECRET = 'access_token_secret'

  MAX_LENGTH   = 140
  UPDATE_URL   = 'https://api.twitter.com/1/statuses/update.xml'

  attr_accessor :config

  def initialize
    config_file = File.join(File.expand_path('~'), '.twrc')
    begin
      @config = YAML.load(File.read(config_file))
    rescue
      @config = {
        KEY          => prompt(KEY),
        SECRET       => prompt(SECRET),
        TOKEN        => prompt(TOKEN),
        TOKEN_SECRET => prompt(TOKEN_SECRET)
      }
      File.open(config_file, 'w') {|f| f.write(@config.to_yaml)}
      FileUtils.chmod(0600, config_file)
      puts "saved to #{config_file}"
    end
  end

  def get_token
    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)
  end

  private

  def prompt(string)
    print string.gsub('_', ' ').capitalize + ":"
    gets.strip
  end
end

tw = Tw.new
unless (status = ARGV.join(' ')).empty? && status.split('').length > Tw::MAX_LENGTH
  response = tw.get_token.post(Tw::UPDATE_URL, {:status => status})
  exit(Net::HTTPOK == response)
else
  exit(false)
end

設定

アプリをTwitter Applicationsで登録してください。アプリケーションの種類は、「クライアントアプリケーション」です。

引数なしで起動し、Consumer Key、Consumer Secret、Access Token、Access Token Secretを入力してください。

Access TokenとAccess Token Secretは、アプリを登録した後、右サイドメニューにある「My Access Token」をクリックすると取得できます。

使い方

Twitterに投稿したいメッセージを引数として、起動してください。複数の引数は、半角の空白で連結します。ただし、半角括弧が文中にある場合は、文章全体をダブルクォーテーションで囲ってください。

注意点

当たり前のことですが、「AS IS」*1です。