hubotで突然の死に備える

hubot-scripts Advent Calendar 2013の6日目の記事になります。
1日空きましたが、4日目はdaxanya2さんによる Hubot-scriptsでサイコロを投げる でした。

_人人人人人人_
> 突然の死 <
 ̄Y^Y^Y^Y^Y ̄

突然の死とは (トツゼンノシとは) [単語記事] - ニコニコ大百科

botでは比較的よく見るベタなネタではありますが、自分の調べた範囲ではhubot用のものがまだ無さそうだったので作ってみました。

対象文字列の長さによって吹き出しの幅を変える必要がありますが、
上の「人」は全角文字数(半角文字は2個で1)+2個分、下は「Y」1つと「^Y」を全角文字数分で表示するようにしました。

全角半角が混ざった場合の幅の計算はなんかメンドそうなのでライブラリに任せてます。
https://npmjs.org/package/eastasianwidth

事前に npm install しておきましょう。

$ npm install eastasianwidth

実際のコードは以下のようになります。

# Description:
#   >Prepare for sudden death.<
#
# Dependencies:
#   "eastasianwidth": "~0.1.0"
#
# Configuration:
#   None
#
# Commands:
#   hubot >< <message> - Ascii art generator for sudden death.
#
# Notes:
#   None
#
# Author:
#   saihoooooooo

eastasianwidth = require 'eastasianwidth'

strpad = (str, count) ->
  new Array(count + 1).join str

module.exports = (robot) ->
  robot.respond />< (.*)$/i, (msg) ->
    message = msg.match[1].replace /^\s+|\s+$/g, ''
    return until message.length

    length = Math.floor eastasianwidth.length(message) / 2

    suddendeath = [
      "_#{strpad '人', length + 2}_"
      "> #{message} <"
      " ̄Y#{strpad '^Y', length} ̄"
    ]
    msg.send suddendeath.join "\n"

簡単ですね!

使い方は

hubot >< 突然の死

とするだけです。
これで例え急にサーバが落ちてしまっても快適なhubot生活を送れること間違いないですね!

次回はnpm化でもしてみようと思います。 → しました。
それでは。