rack Gem について勉強した時にBot アプリを作成したので、そのメモとして残そうと思います。
もしBot アプリを作成してみたいという方がいれば参考程度にしてみてください。
どういうアプリ?
Slack のチャットフォームの方で@botユーザー say_hello
と入力すると、@botユーザー が挨拶してくれるアプリです。
準備
Slack token 取得する
(1) https://slack.com/services/new/bot にアクセスする
(2) ユーザー名を記入しボットインテグレーション
からボットユーザーを作成する
(3) (2)で作成したボットユーザーのインテグレーションの設定 > API トークン からtoken(xoxb-から始まるもの)を取得する
token は Slack Bot アプリの .env
ファイルの環境変数で使用します。
(4) Slack のアカウントから追加したユーザーを追加してください。
アプリを実装する
ディレクトリ全体構造
.
├── Dockerfile
├── Gemfile
├── Gemfile.lock
├── README.md
├── config.ru
├── docker-compose.yml
├── lib
│ ├── bot.rb
│ └── commands
│ └── greeting.rb
└── .env
2 directories, 9 files
実装用ファイルを追加する
- Dockerfile
FROM ruby:3.0.0
ENV TZ Asia/Tokyo
ENV APP_ROOT /usr/src/app
ENV BUILD_PACKAGES="vim"
WORKDIR $APP_ROOT
RUN \
apt-get update -qq && apt-get install -y $BUILD_PACKAGES --no-install-recommends && \
apt-get clean && rm -rf /var/lib/apt/lists/* /var/cache/apt/archives/* /tmp/* /var/tmp/*
COPY Gemfile $APP_ROOT/
COPY Gemfile.lock $APP_ROOT/
RUN \
echo 'gem: --no-document' >> ~/.gemrc && \
cp ~/.gemrc /etc/gemrc && \
chmod uog+r /etc/gemrc && \
bundle config build.nokogiri --use-system-libraries && \
bundle config jobs 4 && \
bundle install && \
rm -rf ~/.gem
COPY . $APP_ROOT/
CMD ["rackup"]
- docker-compose.yml
version: "3.9"
services:
web:
volumes:
- .:/myapp
build: .
command: bash -c "rackup"
stdin_open: true
tty: true
- Gemfile
source 'https://rubygems.org'
ruby '3.0.0'
git_source(:github) { |repo_name| "https://github.com/#{repo_name}" }
gem 'puma'
gem 'rack'
gem 'async-websocket', '~> 0.8.0'
gem 'celluloid-io'
gem 'slack-ruby-bot'
gem 'dotenv'
- Gemfile.lock
空のファイルでOKです
- config.ru
$LOAD_PATH.unshift(File.dirname(__FILE__))
require 'lib/bot'
require 'dotenv'
Dotenv.load
Bot::Engine.run
- lib/bot.rb
require 'slack-ruby-bot'
require 'lib/commands/greeting'
require 'rack'
module Bot
class Engine < SlackRubyBot::Bot
help do
title 'サンプルSlack Bot'
desc 'コマンド紹介help'
command :say_hello do
title 'say_hello'
desc '挨拶するコマンドです'
end
end
end
end
- lib/commands/greeting.rb
module Bot
module Commands
class Greeting < SlackRubyBot::Commands::Base
command 'say_hello' do |client, data, _match|
client.say(channel: data.channel, text: 'こんにちは。僕はSlack Botです。')
end
end
end
end
- .env
SLACK_API_TOKEN=xoxb-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
サーバを起動させ操作確認してみる
ここまでできれば実装完了です。サーバを起動させ、動作確認してみましょう!
$ docker-compose up --build
Slack でボットユーザー の名前にメンションをつけて実行してみます!
@botユーザー help
または@botユーザー say_hello
と送信してみてください。するとbot アプリが返信してくれます
備考
今回実装したソースコードは githubにまとめています。
必要があれば参考にしてみてください。
次回は、DB(MySQL)を追加したバージョンも記事にしたいと思います。