nadoka から nowa に投稿するボット

nadoka から Twitter に投稿するボットnowa版です。

つかいかた

以下のコードを nowabot.nb として plugin フォルダに入れます。

# -*-ruby-*-
require 'net/http'
require 'kconv'
require 'cgi'

class NowaBot < Nadoka::NDK_Bot
  def on_client_privmsg client, ch, message
    if (@ch == nil) or ((@ch != nil) and (@ch.upcase == ch.upcase))
      if @pattern =~ message
        status  = message.sub(@pattern, '')
        if send_nowa(status)
          @logger.slog "[#{self.class.to_s}] sent: #{status}"
        else
          @logger.slog "[#{self.class.to_s}] faild: #{status}"
        end
      end
    end
  end

  def send_nowa status
    begin
      Net::HTTP.version_1_2

      # nowa サーバーとのセッション
      Net::HTTP.start('my.nowa.jp', 80) {|http| 
        http.read_timeout = @timeout

        # nowa へログイン
        req      = Net::HTTP::Post.new('/login/')
        req.body = "nowa_id=#{@user}&password=#{@passwd}"
        res      = http.request(req)
        temp     = res.body

        # ログインCookie取得
        cookie = res['set-cookie']
       
        if cookie

          #rkey取得
          req           = Net::HTTP::Get.new('/home/')  
          req['Cookie'] = cookie  
          res           = http.request(req)  
          temp          = res.body  
          match         = /hitokoto.\init\( "([^\"]*)"/.match(temp)
          rkey          = match[1]

          # メッセージ送信
          if rkey
            req           = Net::HTTP::Get.new('/internal_api/status_message/?body=' + CGI.escape(status.toutf8) + '&rkey=' + rkey)
            req['Cookie'] = cookie
            res           = http.request(req)
            temp          = res.body
            
            if res.code != 200
              return false
            end
          else
            return false
          end
        else
          return false
        end
      }
    rescue Exception => e
      return false
    end
    return true
  end

  def bot_state
    return "<#{self.class.to_s} user: #{@user}>"
  end

  def bot_initialize
    @ch      = @bot_config.fetch(:ch,      nil)
    @user    = @bot_config.fetch(:user,    nil)
    @passwd  = @bot_config.fetch(:passwd,  nil)
    @pattern = @bot_config.fetch(:pattern, /\s\.$/)
    @timeout = @bot_config.fetch(:timeout, 60)
  end
end

あとはこんな設定を追加すればOK。

    {
      :name   => :NowaBot,
      :user   => 'hoge',
      :passwd => 'fuga',
      :ch     => '#伊勢的新常識', # このボットが反応するチャンネルを限定する場合に書きます
    },
__CODE2__

設定が終わったら nadoka をリロード。末尾に半角スペース*1をつけた発言をすると twitter に送られます。

あ、ちなみに僕のnowaこちらです

*1:設定「:pattern」に正規表現オブジェクトを指定すると条件を変更できます。デフォルト値は末尾に半角スペース+ドット (/\s\.$/) になっています