LoginSignup
14
13

More than 5 years have passed since last update.

Hubotからslackに画像を投稿してみる

Posted at

ある時、突然こんな要望をされて困った。
「猫」って発言されたらこの画像を表示したい!
 ※ 本当は「猫」ではありませんでしたが、猫でマスクしておきます。

まずは普通に応答

nekobot.coffee
module.exports = (robot) ->
    robot.hear /(猫)$/i, (msg) ->
      room = msg.envelope.room
      if room == "image"
        text = msg.match[1]
        msg.send  "#{text} の画像アップするよ"

画像をアップロード

curlにてアップしたい画像のpathとアップ先のchannelを指定

nekobot.coffee
module.exports = (robot) ->
    robot.hear /(猫)$/i, (msg) ->
      room = msg.envelope.room
      if room == "image"
        text = msg.match[1]
        msg.send  "#{text} の画像アップするよ"
        # 下記を追加
        filename = 'image/nya-o.png'
        channel = msg.message.rawMessage.channel
        exec "curl -F file=@#{filename} -F channels=#{channel} -F token=#{process.env.HUBOT_SLACK_TOKEN} https://slack.com/api/files.upload", (err, stdout, stderr) ->
          if err
            # 一応Errorのハンドリングしておく?

後は、該当のチャンネルでの 発言をhubotが拾って指定された猫画像をSlackにアップロード
※画像サイズによってはアップロードに時間がかかります。

更に複数の画像をランダムで表示させたい

ということで、表示する画像の配列を作成して、 random で取得してみる

nekobot.coffee
# 表示したい画像path
neko = ['nya-o.png','bow-wow.png','Cock-a-doodle-doo.png']
module.exports = (robot) ->
    robot.hear /(猫)$/i, (msg) ->
      room = msg.envelope.room
      if room == "image"
        text = msg.match[1]
        msg.send  "#{text} の画像アップするよ"
        # 下記を追加
        filename = msg.random neko
        channel = msg.message.rawMessage.channel
        exec "curl -F file=@#{filename} -F channels=#{channel} -F token=#{process.env.HUBOT_SLACK_TOKEN} https://slack.com/api/files.upload", (err, stdout, stderr) ->
          if err
            # 一応Errorのハンドリングしておく?

コレで に反応したら3種類のどれかの画像がアップします。
※ 連続で同じ画像ばっかりアップされたため、なかなか出なかった画像が当たり扱いされ、いつの間にかくじ引き機能として活躍されるしまつ。。。

14
13
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
14
13