φ(.. ) 備忘録
   
  

2014年5月31日土曜日

hubot文字化け対策

会社のchatbotが調子悪そうなので、新しいマシンにhubotをインストールして構築しなおしている。チャットの文字コードはISO-2022-JPだが、hubotがutf-8しか対応していないので結構文字化けに悩まされた。
ちまたでは、ZNCなどのプロキシを使うのが常套手段らしいがメンテするツールが増えるのがいやだったので、coffeescriptの改版で乗り切ったので備忘録を残しておく。
改版するスクリプトはこれ。
 hubot/node_modules/hubot-irc/src/irc.coffee

■変更箇所①sendするところでutf-8からISO-2022-JPに変換するperlを起動する。
      8   send: (envelope, strings...) ->
      9     mybot = @bot
     10     # Use @notice if SEND_NOTICE_MODE is set
     11     return @notice envelope, strings if process.env.HUBOT_IRC_SEND_NOTICE_MODE?
     12
     13     target = @_getTargetFromEnvelope envelope
     14
     15     unless target
     16       return console.log "ERROR: Not sure who to send to. envelope=", envelope
     17
     18     for str in strings
     19       cmd = "hubot/perl/nkf.pl -out " + escape(str)
     20       exec = require('child_process').exec
     21       exec cmd, (err,stdout,stderr) ->
     22         mybot.say target, stdout

■変更箇所②message受信時にISO-2022-JPからutf-8に変換するperlを起動する。
    215     bot.addListener 'message', (from, to, message) ->
    216       cmd = "hubot/perl/nkf.pl -in " + escape(message)
    217       exec = require('child_process').exec
    218       exec cmd, (err,stdout,stderr) ->
    219         message = stdout
    220         if options.nick.toLowerCase() == to.toLowerCase()
    221           # this is a private message, let the 'pm' listener handle it
    222           return
    223
    224         if from in options.ignoreUsers
    225           console.log('Ignoring user: %s', from)
    226           # we'll ignore this message if it's from someone we want to ignore
    227           return
    228
    229         console.log "From #{from} to #{to}: #{message}"
    230
    231         user = self.createUser to, from
    232         if user.room
    233           console.log "#{to} <#{from}> #{message}"
    234         else
    235           unless message.indexOf(to) == 0
    236             message = "#{to}: #{message}"
    237           console.log "msg <#{from}> #{message}"
    238
    239         self.receive new TextMessage(user, message)
以上、2箇所。noticeもかえたければ上記を参考に変更する。220行目以降は変更はないが、インデントを2文字ずつ後ろにする必要がある。これをやらないとうまくうごかないぞ!
次は文字コード変換perl。
※ここはperlのnkfモジュールを使うように以前の投稿から変更する。以前はファイル出力しnkfコマンドを使っていたがモジュールを使うことにする。
perlのnkfモジュールは sudo apt-get install libnkf-perlでインストールできる。
■hubot/perl/nkf.pl
#!/usr/bin/perl
use utf8;use NKF;use URI::Escape;
exit if($#ARGV < 1);
$str=uri_unescape($ARGV[1]);
if($ARGV[0] eq "-in"){print nkf("--oc=utf-8 --ic=ISO-2022-JP",$str);}
else{
    $str=~s/%u([0-9a-fA-F]{4})/pack("U",hex($1))/ego;
    print nkf("--ic=utf-8 --oc=ISO-2022-JP",$str);
}

chmod 755 nkf.pl を忘れずに!。
これでほぼ文字化けは回避できた。ポイントは文字をescapeしてからperlに渡しているところで、これをしないと「Д」とか「:」が入力されたとき動作がおかしくなる。


つくって覚えるCoffeeScript入門
飯塚直
アスキー・メディアワークス
売り上げランキング: 292,335

0 件のコメント :

コメントを投稿