LoginSignup
7
9

More than 5 years have passed since last update.

HubotでCoffeeScriptを使うのでコードの書き方メモ

Last updated at Posted at 2017-10-26

概要

  • Hubotを使うときのCoffeeScriptの書き方メモ

基礎編

サンプルコード

hello.coffee
module.exports = (robot) ->
  robot.hear /hello/, (msg) ->
    msg.reply 'hi'

「hello」と話しかけると「hi」と返信してくれるスクリプトです。

簡単な説明

module.exports = (robot) ->

Node.jsのモジュールをrobot引数で作っている(?)

robot.hear /hello/, (msg) ->
  msg.reply 'hi'

Robotクラスのインスタンスからhearメソッドを呼び出している。
/hello/は正規表現で受け取る発言を指定。
マッチしたらreplyメソッドによって'hi'と返信してくれる。

主要メソッド

サンプルコード

sample.coffee
module.exports = (robot) ->
  robot.hear /foo/i, (msg) ->
    msg.send "bar"

  robot.respond /hoge/i, (msg) ->
    msg.reply "fuga"

チャットに反応させる

メソッドが2種類ある

  • hear
  • respond

hear

チャットに出てきたら反応する。
/foo/iにマッチしてたら会話の途中に出てきても反応する。
意図しないときに反応する可能性がある。

respond

HUBOT_NAMEもしくはHUBOT_ALIASが文頭に存在する場合のみ反応する。
例: 'piala-bot hello'

Hubotに発言させる

メソッドが2種類ある

  • send
  • reply

send

Hubotに発言させることができます。

reply

発言者に対して返答してくれます。
Adapterによって返答の定義が異なるようです。

応用編

Botに1つ選んでもらう

select.coffee
module.exports = (robot) ->
  robot.hear /(.+)から選ぶ/, (msg) ->
    items = msg.match[1].split(/[ ・、\s]+/)
    item = msg.random items
    msg.reply "#{item}"

結果

hubot > りんご、ばなな、ぶどうから選ぶ
hubot > ばなな

msg.match

正規表現にマッチした結果を返します。
なので、りんご、ばなな、ぶどう を返しています。

msg.random

Arrayからランダムで一つ返します。
[りんご, ばなな, ぶどう]からばななを返しています。

参考記事

簡単な Hubot スクリプトをもっとつくろう (おみくじ系)

7
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
9