nadoka からもごもごに投稿するボットも一応作っておいた

以下2つのエントリで「おたくなにしてるん?」系のサービスのボット作りました。

ここまできたらもごもご忘れたらかわいそうだろうということで作ってみました。

作ったはいいけど、ほかのサービスとはなんか毛色が違うから、本当にこれをつかっていいのかは微妙という感じだな。

そしてそろそろ共通部分くくりだしてスーパークラス作った方が良い気がする。

つかいかた

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

# -*-ruby-*-

require 'net/http'
require 'kconv'
require 'cgi'

class Mogo2Bot < 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_mogo2(status)
          @logger.slog "[#{self.class.to_s}] sent: #{status}"
        else
          @logger.slog "[#{self.class.to_s}] faild: #{status}"
        end
      end
    end
  end

  def send_mogo2 status
    begin
      Net::HTTP.version_1_2

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

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

        # ログインCookie取得
        cookie = res['set-cookie']
       
        if cookie
          req           = Net::HTTP::Post.new('/home/update')
          req['Cookie'] = cookie
          req.body      = 'comment=' + CGI.escape(status.toutf8) + '&commentis=friends'
          res           = http.request(req)
          temp          = res.body
        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   => :Mogo2Bot,
      :user   => 'hoge@half-done.net',
      :passwd => 'fuga',
      :ch     => '#伊勢的新常識', # このボットが反応するチャンネルを限定する場合に書きます
    },

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

あ、ちなみに僕のもごもごはこちらです

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