LoginSignup
11
10

More than 5 years have passed since last update.

RedmineとSlackを連携させて新しいチケットが発行されたら通知するBotをRubyで作ってみる

Last updated at Posted at 2016-05-31

SlackAPIのGem導入

以下のコマンドを実行

# gem install slack-api

SlackBOT用のトークン取得

以下のURLにてトークンを生成

RedmineのAPIアクセスキー入手

個人設定の画面にて、右側にあるAPIアクセスキーを作成

スクリプト作成

以下のスクリプトを作成

/home/scripts/slack.rb
#!/usr/local/bin/ruby
# encoding: utf-8

require 'json'
require 'uri'
require 'net/http'
require 'date'
require "slack"

uri = URI.parse('https://[Redmineのアドレス]/issues.json?sort=updated_on:desc&key=[APIアクセスキー]')
json = Net::HTTP.get(uri)
result = JSON.parse(json)

filename = "/home/scripts/redmine.txt"

f = open(filename, "r")
tmp = f.readlines[0]
f.close

Slack.configure do |config|
  config.token = "[SlackBOT用トークン]"
end

id = 0
updated_on = ""

result["issues"].each do |row|

  if id == 0 then
    id = row["id"].to_i
    updated_on = row["updated_on"]
  end

  if DateTime.parse(row["updated_on"]) > DateTime.parse(tmp)
    text = "[Redmine新着情報] " + row["project"]["name"] + ":" + row["subject"]
    if row.has_key?("assigned_to")
      text += "(#{row["assigned_to"]["name"]})"
    end
    Slack.chat_postMessage(text: text, username: 'Redmine', channel:'#redmine')
  end

end

f = open(filename, "w")
f.write(id)
f.close

以下のコマンドを実行

$ touch /home/scripts/redmine.txt

cronに登録

以下のコマンドを実行

# crontab -e

「i」キーを押し、下記のとおり入力

*/15 * * * * /usr/local/bin/ruby /home/scripts/redmine.rb

入力後、「:wq」と入力しエンターキーを押す
次に、以下のコマンドを実行

# service crond restart

テスト

チケットを追加し、最長15分以内にSlackへ投稿されることを確認

11
10
2

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
11
10