φ(.. ) 備忘録
   
  
ラベル hubot の投稿を表示しています。 すべての投稿を表示
ラベル hubot の投稿を表示しています。 すべての投稿を表示

2021年10月11日月曜日

hubotの文字化け対策

IRCボットのhubotはISO-2022-JPな環境で使うと文字化けする。なぜなら、hubotはUTF-8を前提として作られているから!

そのため、ZNC等のIRC proxyを介して接続するのが一般的だが、今回はhubotを直接いじって、文字化けを解決する手法を見つけたので紹介する。

#以前、irc.coffeeを改変して対応していたが、それより簡単にできる方法を見つけたので記事にする。
まずは、こちらの記事を参考にインストール。

次に、必要なモジュールをインストール。

$ cd ~/hubot
$ npm install jschardet
$ npm install iconv

次に、irc.jsのパッチを作成する。

$ cd ~/hubot/node_modules/irc/lib
$ cp irc.js irc.js.org
$ vi irc.js.patch
以下の内容をirc.js.patchとして保存。
--- irc.js.org  2021-10-06 21:44:28.692961900 +0900
+++ irc.js      2021-10-06 22:09:47.822961900 +0900
@@ -30,6 +30,9 @@ var CyclingPingTimer = require('./cyclin

 var lineDelimiter = new RegExp('\r\n|\r|\n')

+var Jschardet = require('jschardet');
+var Iconv = require('iconv').Iconv;
+
 function Client(server, nick, opt) {
     var self = this;
     self.opt = {
@@ -108,6 +111,11 @@ function Client(server, nick, opt) {
     }

     self.addListener('raw', function(message) {
+       for(i in message.args){
+            detectResult = Jschardet.detect(message.args[i]);
+           iconv = new Iconv(detectResult.encoding,'UTF-8//TRANSLIT//IGNORE');
+           message.args[i]=iconv.convert(message.args[i]).toString();
+       }
         var channels = [],
             channel,
             nick,
@@ -934,7 +942,10 @@ Client.prototype.send = function(command
         util.log('SEND: ' + args.join(' '));

     if (!this.conn.requestedDisconnect) {
-        this.conn.write(args.join(' ') + '\r\n');
+       iconv = new Iconv('UTF-8','ISO-2022-JP//TRANSLIT//IGNORE')
+       str = iconv.convert(args.join(' ')).toString()
+//      this.conn.write(args.join(' ') + '\r\n');
+        this.conn.write(str + '\r\n');
     }
 };
次に、irc.jsにパッチをあてる。
$ patch -p1 irc.js < irc.js.patch
これでhubotを再起動すれば、文字化けは解消しているはず。 notice発言や日本語チャンネル名も問題なくjoin可能!

2021年9月23日木曜日

既存UbuntuサーバをWindows10のWSL2に置換する!(其の五)

其の五:hubotの文字化けを直す

前回、hubotが無事インストールできたので、文字化けを対策する。

hubotで扱う文字コードはUTF-8が前提となっており、会社で使っているISO-2022-JPのチャットサーバーだと、文字化けを起こしてしまう。

以前perlのnkfモジュールを用いて対策を行ったことがあったが、coffeeスクリプトで対策できることが分かったので、そちらで対策する。

まずは、hubotをインストールしたディレクトリに移動して、必要なモジュール(jschardet、iconv)を追加インストールする。

$ cd ~/hubot
$ npm install jschardet
$ npm install iconv
次に、irc.coffeeに修正を加える。
$ cd ~/hubot/node_modules/hubot-irc/src
$ cp irc.coffee irc.coffee.org
$ vi irc.coffee
修正内容(diffイメージ)は以下で、最初にrequireで追加したモジュールをロード。
日本語のチャンネル名が指定された場合に備えて、チャンネル名をUTF8からISO-2022-JPに変更する処理を追加。
sendメソッドとnoticeメソッドに文字コードをUTF-8からISO-2022-JPに変更する処理を追加。messageやchannelを受け取るbotListener(message,notice等)に受け取った文字をUTF-8に変更する処理を追加。
ちなみに、iconv生成時のパラメータで指定している『TRANSLIT//IGNORE』はコード変換失敗時にエラーを無視するためのおまじないみたい。
 # Irc library
 Irc = require 'irc'

+# for ISO-2022-JP
+Jschardet = require 'jschardet'
+Iconv = (require 'iconv').Iconv
+
 class IrcBot extends Adapter
   send: (envelope, strings...) ->
     # Use @notice if SEND_NOTICE_MODE is set
@@ -15,6 +19,8 @@
       return console.log "ERROR: Not sure who to send to. envelope=", envelope

     for str in strings
+      iconv = new Iconv('UTF-8','ISO-2022-JP//TRANSLIT//IGNORE')
+      str = iconv.convert(str).toString()
       @bot.say target, str

   topic: (envelope, strings...) ->
@@ -52,6 +58,8 @@
       if not str?
         continue

+      iconv = new Iconv('UTF-8','ISO-2022-JP//TRANSLIT//IGNORE')
+      str = iconv.convert(str).toString()
       @bot.notice target, str

   reply: (envelope, strings...) ->
@@ -131,11 +139,15 @@

     do @checkCanStart

+    iconv = new Iconv('UTF-8','ISO-2022-JP//TRANSLIT//IGNORE')
+    roomsValue = iconv.convert(process.env.HUBOT_IRC_ROOMS).toString()
+
     options =
       nick:     process.env.HUBOT_IRC_NICK or @robot.name
       realName: process.env.HUBOT_IRC_REALNAME
       port:     process.env.HUBOT_IRC_PORT
-      rooms:    process.env.HUBOT_IRC_ROOMS.split(",")
+#      rooms:    process.env.HUBOT_IRC_ROOMS.split(",")
+      rooms:    roomsValue.split(",")
       ignoreUsers: process.env.HUBOT_IRC_IGNORE_USERS?.split(",") or []
       server:   process.env.HUBOT_IRC_SERVER
       password: process.env.HUBOT_IRC_PASSWORD
@@ -189,15 +201,27 @@

     if options.connectCommand?
       bot.addListener 'registered', (message) ->
+        detectResult = Jschardet.detect(message)
+        iconv = new Iconv(detectResult.encoding,'UTF-8//TRANSLIT//IGNORE')
+        message = iconv.convert(message).toString()
+
         # The 'registered' event is fired when you are connected to the server
         strings = options.connectCommand.split " "
         self.command strings.shift(), strings...

     bot.addListener 'names', (channel, nicks) ->
+      detectResult = Jschardet.detect(channel)
+      iconv = new Iconv(detectResult.encoding,'UTF-8//TRANSLIT//IGNORE')
+      channel = iconv.convert(channel).toString()
+
       for nick of nicks
         self.createUser channel, nick

     bot.addListener 'notice', (from, to, message) ->
+      detectResult = Jschardet.detect(message)
+      iconv = new Iconv(detectResult.encoding,'UTF-8//TRANSLIT//IGNORE')
+      message = iconv.convert(message).toString()
+
       if from in options.ignoreUsers
         console.log('Ignoring user: %s', from)
         # we'll ignore this message if it's from someone we want to ignore
@@ -209,6 +233,10 @@
       self.receive new TextMessage(user, message)

     bot.addListener 'message', (from, to, message) ->
+      detectResult = Jschardet.detect(message)
+      iconv = new Iconv(detectResult.encoding,'UTF-8//TRANSLIT//IGNORE')
+      message = iconv.convert(message).toString()
+
       if options.nick.toLowerCase() == to.toLowerCase()
         # this is a private message, let the 'pm' listener handle it
         return
@@ -231,6 +259,10 @@
       self.receive new TextMessage(user, message)

     bot.addListener 'action', (from, to, message) ->
+      detectResult = Jschardet.detect(message)
+      iconv = new Iconv(detectResult.encoding,'UTF-8//TRANSLIT//IGNORE')
+      message = iconv.convert(message).toString()
+
       console.log " * From #{from} to #{to}: #{message}"

       if from in options.ignoreUsers
@@ -247,9 +279,17 @@
       self.receive new TextMessage(user, message)

     bot.addListener 'error', (message) ->
+      detectResult = Jschardet.detect(message)
+      iconv = new Iconv(detectResult.encoding,'UTF-8//TRANSLIT//IGNORE')
+      message = iconv.convert(message).toString()
+
       console.error('ERROR: %s: %s', message.command, message.args.join(' '))

     bot.addListener 'pm', (nick, message) ->
+      detectResult = Jschardet.detect(message)
+      iconv = new Iconv(detectResult.encoding,'UTF-8//TRANSLIT//IGNORE')
+      message = iconv.convert(message).toString()
+
       console.log('Got private message from %s: %s', nick, message)

       if process.env.HUBOT_IRC_PRIVATE
@@ -267,21 +307,37 @@
       self.receive new TextMessage({reply_to: nick, name: nick}, message)

     bot.addListener 'join', (channel, who) ->
+      detectResult = Jschardet.detect(channel)
+      iconv = new Iconv(detectResult.encoding,'UTF-8//TRANSLIT//IGNORE')
+      channel = iconv.convert(channel).toString()
+
       console.log('%s has joined %s', who, channel)
       user = self.createUser channel, who
       user.room = channel
       self.receive new EnterMessage(user)

     bot.addListener 'part', (channel, who, reason) ->
+      detectResult = Jschardet.detect(channel)
+      iconv = new Iconv(detectResult.encoding,'UTF-8//TRANSLIT//IGNORE')
+      channel = iconv.convert(channel).toString()
+
       console.log('%s has left %s: %s', who, channel, reason)
       user = self.createUser '', who
       user.room = channel
       self.receive new LeaveMessage(user)

     bot.addListener 'kick', (channel, who, _by, reason) ->
+      detectResult = Jschardet.detect(channel)
+      iconv = new Iconv(detectResult.encoding,'UTF-8//TRANSLIT//IGNORE')
+      channel = iconv.convert(channel).toString()
+
       console.log('%s was kicked from %s by %s: %s', who, channel, _by, reason)

     bot.addListener 'invite', (channel, from) ->
+      detectResult = Jschardet.detect(channel)
+      iconv = new Iconv(detectResult.encoding,'UTF-8//TRANSLIT//IGNORE')
+      channel = iconv.convert(channel).toString()
+
       console.log('%s invited you to join %s', from, channel)

       if from in options.ignoreUsers

本来なら、環境変数もしくはコマンドパラメータで変換する文字コードを指定すべきだが、今回はそこまでやってない。
上記修正が正しく動作するか確認するために、hubot-scriptsのhttp-post-say.coffeeを使ったため、それの設定方法も残しておく。
まず、hubotインストールディレクトリに移動して、hubot-scripts.jsonを編集。
$ cd ~/hubot
$ vi hubot-scripts.json
hubot-scripts.jsonの内容は以下。他に追加したいスクリプトがあればカンマ(,)区切りで追加すればよい。
["http-post-say.coffee"]
hubotの待ち受けポートは、デフォルト8080になっている。変更する場合には、以下のようにhubot起動スクリプトに環境変数PORTの設定処理を追加し、起動すればよい。
$ vi runbot.sh
#!/bin/bash
# hubot http port setting
export PORT=9999
# runhubot
export HUBOT_IRC_NICK="hubot"
export HUBOT_IRC_ROOMS="#test01,#test02"
export HUBOT_IRC_SERVER="localhost"
#export HUBOT_IRC_PASSWORD="hoge"
bin/hubot -a irc
$ .runbot.sh 
http-post-say.coffeeを使って、http経由でhubotに発言させるにはcurlコマンド等で以下のようにすればよい。
$ curl -X POST http://localhost:9999/hubot/say -d message=文字化けた? -d room='#test01'
ISO-2022-JPのチャットサーバって、世の中一般では、レアなんですかね。。。うちの会社だけなのかなぁ。。。。

あと、おまけで、hubotの発言をnoticeにする方法がわかった。すごく簡単で、起動時に環境変数HUBOT_IRC_SEND_NOTICE_MODEにtrueを設定するだけだった。イメージは以下。
#!/bin/bash
# hubot http port setting
export PORT=9999
# runhubot
export HUBOT_IRC_NICK="hubot"
export HUBOT_IRC_ROOMS="#test01,#test02"
export HUBOT_IRC_SERVER="localhost"
#export HUBOT_IRC_PASSWORD="hoge"
export HUBOT_IRC_SEND_NOTICE_MODE="true"
bin/hubot -a irc

2021年9月22日水曜日

既存UbuntuサーバをWindows10のWSL2に置換する!(其の四)

   其の四:wsl2にhubotをインストールする

いよいよ本格的な移行作業として、wsl2のUbuntu 20.04 LTSにhubotをインストールする。いろんなサイトを参考にインストールしてみたがうまくいかず、かなり試行錯誤を繰り返したが、ようやくIRCチャットルームにbotをログインさせるところまで来たので、その手順を紹介する。

まず、hubotに必要なパッケージをインストールする。

$ sudo apt-get install nodejs npm coffeescript libicu-dev
次に、hubotをgit clone後、任意でディレクトリ名を変更し、ディレクトリを移動する。
$ git clone https://github.com/jgable/hubot-irc-runnable
$ mv hubot-irc-runnable hubot
$ cd hubot
次に、npmインストール実行。
$ npm install
次に、hubot-scripts.jsonを一応バックアップして編集。hubot-scripts.jsonうち、使用しないスクリプトを削除する。
$ cp hubot-scripts.json hubot-scripts.json.org
$ vi hubot-scripts.json
今回は全部つかわないので、以下の内容に変更。
[]
次に起動スクリプト(runbot.sh)を編集。
$ vi runbot.sh
内容は以下。ニックネームとかJOINするチャンネルとかは適当に変えてください。尚、同一WSL2内のチャットサーバに接続する場合には、以下設定(localhost)で接続できた。redis brainは今回使わないので起動しているところをコメントアウト。
#!/usr/bin/env sh

# Set Environment Variables
export HUBOT_IRC_NICK=hubot
export HUBOT_IRC_SERVER=localhost
export HUBOT_IRC_ROOMS="#test01,#test02"

# Using SSL?
#export HUBOT_IRC_PORT=6697
#export HUBOT_IRC_USESSL=true
#export HUBOT_IRC_SERVER_FAKE_SSL=true

# Server password?
#export HUBOT_IRC_PASSWORD=password

# Don't let hubot flood the room.
export HUBOT_IRC_UNFLOOD=true

# Output environment variables
echo HUBOT_IRC_NICK=$HUBOT_IRC_NICK
echo HUBOT_IRC_SERVER=$HUBOT_IRC_SERVER
echo HUBOT_IRC_ROOMS=$HUBOT_IRC_ROOMS

#echo HUBOT_IRC_PORT=$HUBOT_IRC_PORT
#echo HUBOT_IRC_USESSL=$HUBOT_IRC_USESSL
#echo HUBOT_IRC_SERVER_FAKE_SSL=$HUBOT_IRC_SERVER_FAKE_SSL
#echo HUBOT_IRC_PASSWORD=$HUBOT_IRC_PASSWORD

# Start the redis brain
#echo ""
#echo "Starting Redis Server"
#/usr/local/bin/redis-server > /dev/null &

echo ""
echo "Starting bot"
./bin/hubot -a irc

実行権を付与。
  $ chmod 755 runbot.sh
スクリプトを起動。正常に接続できると以下の応答がコンソールに出力される。
hubot has joined #test01
hubot has joined #test02
以上でインストールと起動は完了。ただし、hubotの文字コードはUTF-8が前提となっているため、ISO-2022-JP(Shift-jis)が前提のサーバだと、文字化けする。次回はこの文字化けを解消する。

2014年6月7日土曜日

hubot-loggerを設定する

hubot-loggerを設定する。文字化け対策もやる。対策に使うnkf.plは本ブログの過去記事を参照すること。ログの保存はutf-8になる。noticeでもログはとる。設定は以下。
(1)~/tools/hubot/package.jsonを修正。青字追加。
   :
  "dependencies": {
    "hubot": "~2.5.1",
    "hubot-scripts": ">= 2.1.0",
    "optparse": "1.0.3",
    "hubot-irc": "0.1.x",
    "hubot-logger": "~0.0.11"  },
   :
(2)~/tools/hubot/external-scripts.jsonを以下の内容で作成。
["hubot-logger"]
(3)% npm install
(4)~/tools/hubot/node_modules/hubot-logger/scripts/hubot-logger.coffeeを修正。
        :
log_message = (root, date, type, channel, meta) ->
  mkdirp(path.resolve root, channel)
  log_file = path.resolve root, channel, date.toString("%Y-%m-%d") + '.txt'
  meta.date = date
  meta.channel = channel
  meta.type = type
  if meta.message
    cmd = "~/tools/hubot/perl/nkf.pl -in " + escape(meta.message)
    exec = require('child_process').exec
    exec cmd, (err,stdout,stderr) ->
      meta.message=stdout
      fs.appendFile log_file, JSON.stringify(meta) + '\n', (err) ->
        if err
          throw err
  else

    fs.appendFile log_file, JSON.stringify(meta) + '\n', (err) ->
      if err
        throw err
        :
    robot.adapter.bot.on 'message', (nick, to, text, message) ->
      result = (text + '').match(/^\x01ACTION (.*)\x01$/)
      if !result
        log_message(logs_root, new Tempus(), "message", to, {nick: nick, message: text, raw: message })
      else
        log_message(logs_root, new Tempus(), "action", to, {nick: nick, action: result[1], raw: message })
    robot.adapter.bot.on 'notice', (nick, to, text, message) ->
      result = (text + '').match(/^\x01ACTION (.*)\x01$/)
      if !result
        log_message(logs_root, new Tempus(), "message", to, {nick: nick, message: text, raw: message })
      else
        log_message(logs_root, new Tempus(), "action", to, {nick: nick, action: result[1], raw: message }) 

        :
(5) ~/tools/hubot/runbot.shに以下の設定追加。
export IRCLOGS_PORT=3001 #expressがlistenするポート番号
export IRCLOGS_FOLDER="chatlogs" #ログの保存先
以上を設定すると、http://localhost:3001/irclogsでログを参照することができる。

2014年6月5日木曜日

hubotのbotスクリプトをperlで書く

hubotのbotスクリプトはcoffeescriptで書かれていて、ところどころ非同期動作となり初心者には難しく感じた。ある程度勉強してそれなりにかけるようになったが、複雑な処理をやらせようとするといつも私は壁に当たってしまう。めんどくさくなったので使い慣れたperlで書くことにした。
perlで書くといってもircとの接続部分はhubotを使うのでperlを起動し結果をircに渡す最低限の箇所だけcoffeescriptで書き、あとはperlで実装する方式を採用する。
実際、やってみたがあっさりできた。DB連携でき文字化けもせず今のところ問題ない。
やり方を公開しとく。
1.まず最初にやるのは本ブログで紹介したirc.coffeeの文字化け対策。詳細はこちら
2.次にbotをircに接続するため、以下の内容で
  ~/tools/hubot/node_modules/hubot-scripts/src/scripts/tellme.coffeeを作成。
# tellme.coffee
module.exports = (robot) ->
  robot.hear /^(tellme_del|tellme_add|tellme)(\ | ).+/i, (msg) ->
    cmd = "~/tools/hubot/perl/dbbot.pl "+escape('tellme')+" "+ escape(msg.match[0])
    exec = require('child_process').exec
    exec cmd, (err,stdout,stderr) ->
      msg.send stdout
3.runbot.shで上記スクリプトが読み込まれるよう
  ~/tools/hubot/hubot-scripts.jsonに以下青字を追加
["redis-brain.coffee", "shipit.coffee", "tellme.coffee"]
4.perlスクリプトを以下内容で~/tools/hubot/perl/dbbot.plに作成。mysqlのアカウントとパスワードは環境により修正要!
#!/usr/bin/perl
use utf8;
use DBI;
use Encode;
use URI::Escape;
exit if($#ARGV < 1);
$maxcnt=5; # 最大表示レコード数
$tbl=uri_unescape(decode("utf-8",$ARGV[0]));
$tbl=~s/%u([0-9a-fA-F]{4})/pack("U",hex($1))/ego;
$str=uri_unescape(decode("utf-8",$ARGV[1]));
$str=~s/%u([0-9a-fA-F]{4})/pack("U",hex($1))/ego;
$str=~s/\ /\ /g;$pos=index($str,' ');
exit if($pos == -1);
$exeid=substr($str,0,$pos);$key=substr($str,$pos+1);$exeid=~tr/A-Z/a-z/;
if($exeid =~ /.+_add$/){
    $pos=index($key,' ');
    if($pos == -1){print "内容がないよぅ\n";exit;}
    $val=substr($key,$pos+1);$key=substr($key,0,$pos);
}
if($key eq "help"||$key eq "?"||$key eq "?"){
    $exeid =~ tr/A-Za-z//;
    print "■".$exeid."マクロの使い方\n";
    print "\t登録・・・『 ".$exeid."_add <key> <val> 』\n";
    print "\t削除・・・『 ".$exeid."_del <key> 』\n";
    print "\t参照<完全一致>・・・『 ".$exeid." <key> 』\n";
    print "\t参照<部分一致>・・・『 ".$exeid." %<key>% 』\n";
    print "\t参照<前方一致>・・・『 ".$exeid." <key>% 』\n";
    print "\t参照<後方一致>・・・『 ".$exeid." %<key> 』\n";
    print " ※情報が複数ある場合は最大".$maxcnt."つまで表示する\n";
    exit;
}
if($exeid =~/.+_add/ || $exeid =~ /.+_del/){
    $dbh=DBI->connect('DBI:mysql:hubot', 'root', 'root');
    $dbh->do("set names utf8");
    $sql='SELECT * FROM `'.$tbl.'` WHERE `key` = '.$dbh->quote($key);%rows=();
    $sth=$dbh->prepare($sql);$sth->execute;
    while ($row = $sth->fetchrow_hashref()){$rows{$row->{key}}=$row->{val};}
    $sth->finish;
    if(scalar(keys(%rows)) == 0){
        if($exeid =~ /.+_del/){
            $dbh->disconnect;print "そんなキーワードないよ!!\n";exit;
        }
        $sql='INSERT INTO `hubot`.`'.$tbl.'` (`key`, `val`) VALUES ('.
            $dbh->quote($key).', '.$dbh->quote($val).');';
        $val="追加しました!!";
    }
    else{
        if($exeid =~ /.+_del/){
            $sql='DELETE FROM `hubot`.`'.$tbl.'` WHERE `'.$tbl.'`.`key` = '.
                $dbh->quote($key).';';
            $val="削除しました!!";
        }
        else{
            $sql='UPDATE `hubot`.`'.$tbl.'` SET `val` = '.$dbh->quote($val).
                ' WHERE `'.$tbl.'`.`key` = '.$dbh->quote($key).';';
            $val="更新しました!! 旧->".decode("utf-8",$rows{encode("utf-8",$key)});
        }
    }
    $sth=$dbh->prepare($sql);$sth->execute;
    if($sth->err){print "ERROR! ".$sth->errstr."\n";}else{print $val."\n";}
    $sth->finish;$dbh->disconnect;
}
else{
    $dbh=DBI->connect('DBI:mysql:hubot', 'root', 'root');
    $dbh->do("set names utf8");
    if($key =~ /.*%.*/){$ope="LIKE";}else{$ope="=";}
    $sql='SELECT * FROM `'.$tbl.'` WHERE `key` '.$ope.' '.$dbh->quote($key);
    $sth=$dbh->prepare($sql);$sth->execute;%rows=();
    while ($row = $sth->fetchrow_hashref()){$rows{$row->{key}}=$row->{val};}
    $sth->finish;$dbh->disconnect;
    if(scalar(keys(%rows)) == 0){print "そんなキーワードないですよ!!\n";exit;}
    foreach $key(keys(%rows)){
        print "%u0016".$key."%u000f ".$rows{$key}."\n" if($ope eq "LIKE");
        print $rows{$key}."\n" if($ope eq "=");
        $maxcnt--;last if($maxcnt < 1);
    }
    print "・・・以下省略。ほかにもあるよ!!\n" if(scalar(keys(%rows)) > 5)
}
5.DB準備。
 (1)MySqlインストール
 (2)DB作成。名前は「hubot」
 (3)テーブル作成。名前は「tellme」。カラム数は2
 (4)テーブルの構造設定。
   1カラム目:名前「key」データ型「char」長さ「255」照合順序「utf8-bin」
   2カラム目:名前「val」データ型「char」長さ「255」照合順序「utf8-bin」

これで準備完了。cd ~/tools/hubot ; ./runbot.shで起動するとmybot君がチャットに登場する。
使い方は、
 tellme_add キーワード 内容
でDBに情報登録
 tellme キーワード
でDBの情報をチャットに出力
 tellme_del キーワード
でDBのレコードを削除
ちなみに、tellme.coffeeの robot.hearの行を
 robot.hear /^(なんとか_del|なんとか_add|なんとか)(\ | ).+/i, (msg) ->
にかえると、「なんとか」でbotが反応するようになる。
また
    cmd = "~/tools/hubot/perl/dbbot.pl "+escape('tellme')+" "+ escape(msg.match[0])
のtellmeを「なんとか」にかえるとテーブル名「なんとか」でDB登録参照するようになる。

ゼロからわかる Perl言語超入門
高橋 順子
技術評論社
売り上げランキング: 81,545

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