あーく・りなっくす

プログラミングとかガジェットとかの雑記

Slack 用の bot を作ってみた

Slack では簡単に bot を作れるようだが、Ruby で実装してみたかったので、 slack api で bot を作ってみた - Qiitaを参考に作ってみる。

必要な Gem をインストール

gem 'slack-api'

Gemfile に追記して、bundle を実行する。

$ bundle
Your Gemfile has no gem server sources. If you need gems that are not already on your machine, add a line like this to your Gemfile:
source 'https://rubygems.org'
Could not find gem 'slack-api' in any of the gem sources listed in your Gemfile or available on this machine.

あれ…。最初のメッセージは、特に source を指定してないからだろうけど、その下はなんだろう…。
根本的な原因は特定できていないが、source を http で指定したら問題なかった。

最終的な Gemfile

source "http://rubygems.org"

gem 'slack-api'

実装

簡易的な実装は下記の様になる。

# -*- coding: utf-8 -*-

require 'slack'

SLACK_TOKEN = 'ほげほげ'

Slack.configure {|config| config.token = SLACK_TOKEN }
client = Slack.realtime

client.on :hello do
    puts 'Successfully connected.'
end

client.on :message do |data|
  p data
  if data['text'] == 'test' && data['subtype'] != 'bot_message'
    params = {
      token: SLACK_TOKEN,
      channel: data['channel'],
      username: "bot test 1",
      text: "<@#{data['user']}> bot test"
    } 
    Slack.chat_postMessage params
  end
end

client.start

キーワード 2 種類に対してそれぞれのリプライを割り当ててみた図である。 f:id:arc680:20160409202146p:plain

実際に運用する際には、同記事の方が作っている bot の構成などを参考にしていく。 (ベースクラスを作って、それを継承していく形)