Hubotで++/–で投票するスクリプトを実装する

今回も引き続きHubotネタです。
++, –のような命令で、誰かに対して投票するようなスクリプトを実装します。

hubot


スクリプト

早速スクリプト本体です。Gistsにおいておきました。
末尾のgihyo.jpのサンプルスクリプトを参考にしてます。

# Description:
# Utility commands for voting someone.
#
# Commands:
# <name>++, <name>--, !vote-list, !vote-clear
 
module.exports = (robot) ->
KEY_SCORE = 'key_score'
 
getScores = () ->
return robot.brain.get(KEY_SCORE) or {}
 
changeScore = (name, diff) ->
source = getScores()
score = source[name] or 0
new_score = score + diff
source[name] = new_score
 
robot.brain.set KEY_SCORE, source
return new_score
 
robot.hear /!vote-list/i, (msg) ->
source = getScores()
console.log source
for name, score of source
msg.send "#{name}: #{score}"
 
robot.hear /!vote-clear/i, (msg) ->
robot.brain.set KEY_SCORE, null
 
robot.hear /([A-z]+)\+\+$/i, (msg) ->
name = msg.match[1]
new_score = changeScore(name, 1)
msg.send "#{name}: #{new_score}"
 
robot.hear /([A-z]+)--$/i, (msg) ->
name = msg.match[1]
new_score = changeScore(name, -1)
msg.send "#{name}: #{new_score}"

hearとrespond

HubotにはBotがリアクティブにアクションするための方法として、respondとhearが用意されています。

respondを使うと、Botに対して名前付きで話しかけてきた発言に反応します。

(moomindani) moobot inoshishi++
(moobot) inoshishi: 1

一方、hearを使うと、チャット上に流れてきた発言に反応します。

(moomindani) inoshishi++
(moobot) inoshishi: 1

個人的にはBotの存在をあまり意識したくないので、hearを使うことが多いです。

robot.brain

robot.brainはデータを永続化するためのインタフェースです。
これを使うと、Redisにデータを読み書きすることができます。

GET
robot.brain.get('key')
SET
robot.brain.set 'key' 'value'

データ消したければnullをSETしちゃいます。

robot.brain.set 'key' null

使い方

インクリメント

(moomindani) inoshishi++
(moobot) inoshishi: 1
(moomindani) inoshishi++
(moobot) inoshishi: 2

デクリメント

(moomindani) inoshishi--
(moobot) inoshishi: 1

リスト表示

(moomindani) !vote-list
(moobot) inoshishi: 1
(moobot) ushi: 1
(moobot) hituji: 1

クリア

(moomindani) !vote-clear

参考文献

下記に参考にした資料を記載します。
特に、hubot-plusplusは便利そうだったのですが、自分の用途にはオーバースペックだったので今回は使わず。

  1. トラックバックはまだありません。

コメントを残す