Hubotからslackに画像を投稿してみる
ある時、突然こんな要望をされて困った。
「猫」って発言されたらこの画像を表示したい!
※ 本当は「猫」ではありませんでしたが、猫でマスクしておきます。
まずは普通に応答
nekobot.coffee
module.exports = (robot) ->
robot.hear /(猫)$/i, (msg) ->
room = msg.envelope.room
if room == "image"
text = msg.match[1]
msg.send "#{text} の画像アップするよ"
画像をアップロード
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種類のどれかの画像がアップします。
※ 連続で同じ画像ばっかりアップされたため、なかなか出なかった画像が当たり扱いされ、いつの間にかくじ引き機能として活躍されるしまつ。。。
Author And Source
この問題について(Hubotからslackに画像を投稿してみる), 我々は、より多くの情報をここで見つけました https://qiita.com/kijitora-neko/items/a976a08da080e2376858著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .