マイペースなプログラミング日記

x86エミュレータやFPGA、WebGLにお熱なd-kamiがマイペースに書くブログ

はてなハイクに投稿するスクリプトを書いてみた

はてなハイクに投稿するスクリプトを書いてみた。注意するのはパスワード、http://h.hatena.ne.jp/apiに書いてある、例えばあなたのパスワードは〜です、という部分を使うこと。

require 'net/http'
require 'rexml/document'
require 'uri'
require 'kconv'
require 'parsedate'

username = 'hoge'
password = 'hoge'

class User
    attr_reader :id
    attr_reader :name
    attr_reader :url
    attr_reader :followers_count
    attr_reader :profile_image_url

    def initialize(element)
        @id = element.elements['id'].text()
        @name = element.elements['name'].text()
        @url = element.elements['url'].text()
        @followes_count = element.elements['followers_count'].text()
        @profile_image_url = element.elements['profile_image_url'].text()
    end
end

class Status
    attr_reader :id
    attr_reader :text
    attr_reader :user
    attr_reader :source
    attr_reader :created_at
    attr_reader :keyword

    def initialize(element)
        @id = element.elements['id'].text()
        @user = User.new(element.elements['user'])
        @keyword = element.elements['keyword'].text()
        @text = element.elements['text'].text().split(/=/)[1]
        @user = User.new(element.elements['user'])
        @source = element.elements['source'].text().gsub(/<[^>]+>/, '')
        t_array = ParseDate::parsedate(element.elements['created_at'].text)
        time = Time::local(*t_array[0..-3]) + 9 * 3600
        @created_at = time.strftime('%Y/%m/%d %H:%M:%S')
    end
end

class Haiku
    HaikuServer = 'h.hatena.ne.jp'

    def initialize(username, password)
        @username = username
        @password = password
    end

    def update(keyword, text)
        request = Net::HTTP::Post.new('/api/statuses/update.xml')
        submit_text = URI.escape(text.toutf8)
        submit_keyword = URI.escape(keyword.toutf8)

        request.basic_auth(@username, @password)
        http = Net::HTTP.start(HaikuServer)
        response = http.request(request, "status=#{submit_text}&keyword=#{submit_keyword}&source=d-haiku")

        doc = REXML::Document.new(response.body)
        status = Status.new(doc.elements['/status'])

        return status
    end
end

haiku = Haiku.new(username, password)
haiku.update("テスト", "テスト")