3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

slackbotを作成してherokuを使って定期的なメッセージを送るまで

Posted at

herokuを使ってSlackで定期的なメッセージを表示させる

Slackで定期的なメッセージを送る処理

Rubyで書きました。

slack.rb
require 'slack-ruby-client'

#slackの認証
Slack.configure do |config|
  config.token = "トークンを入力してください"
end

#testタグにメッセージを送りつける
def post_msg(message)
  client = Slack::Web::Client.new
  client.chat_postMessage(
    channel: '#test',
    as_user: true,
    text: "#{message}"
  )
end

#時刻を表示する処理
def test_scheduler
  post_msg("#{Time.now}")
  exit
end

test_scheduler

単体実行前の準備として、slack上のtestタグのメンバーにbotを追加しておいてください。
そうじゃないとエラーで弾かれてしまいます。

ご参考:

Slack Web API であそぼ

slack-ruby/slack-ruby-client

herokuで自動実行するための準備

heroku schedulerでrakeで実行したかったのでRakefileとGemfileを用意します。
Gemfileがないとherokuでgemを落としてくれないどころか、以下のエラーが出るので注意。

herokuへのpushが[ buildpack ]の問題でエラーになる。

Gemfile作ったらそのついでにHigh Sierraでbundle installコケるケースにも遭遇。対策させてもらった記事もつけておきます。Cloud9使ってて久々にHigh Sierraでbundle installしたは。

High Sierraにしたらbundle exec pod installできなくなったよ

Rakefile
require './slack.rb'

desc "This task is called by the Heroku scheduler add-on"
task :slack_post do
  ruby ./slack.rb
end

Gemfile
source 'https://rubygems.org'

gem 'rake'
gem 'slack-api'
gem 'slack-ruby-client'

heroku schedulerに登録

herokuを使うための前準備はできている前提で書きます。
まだの方はユーザー登録とクレジットカード登録をしておきましょう。超過しない限り無料です。参考にさせていただいたサイトは次の通りです。

Herokuでrakeファイルを定期実行する

herokuで適当なappを作って、Resourceタグからheroku schedulerを検索してアドオンを追加しましょう。
スクリーンショット 2018-05-21 0.04.53.png

あとはrake skack_postを登録するだけです。1日に1回。1時間に1回。10分に1回実行できます。
スクリーンショット 2018-05-21 0.08.44.png

詳細は触れていませんでしたが、あらかじめherokuに作ったappに対してソースコードはpushしておいてくださいね。

結果

こんな感じで1時間に一度時報が出ます。
IMG_4357.PNG

3
2
1

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
3
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?