Creating a Simple Slack Bot

Episode #162 by Teacher's Avatar David Kimura

Summary

Slack is a great application to keep in contact with friends, coworkers and a community. With bots, its capabilities are endless. In this episode, learn how to create a Slack Bot to interact with.
ruby api 10:16

Resources

Summary

#Gemfile
source "https://rubygems.org"

git_source(:github) {|repo_name| "https://github.com/#{repo_name}" }

gem 'slack-ruby-bot'
gem 'puma'
gem 'dotenv'
gem 'celluloid-io'

# drifting_ruby.rb
require 'slack-ruby-bot'
require 'drifting_ruby/commands/get_episode'
require 'drifting_ruby/bot'

# config.ru
$LOAD_PATH.unshift(File.dirname(__FILE__))

require 'dotenv'
Dotenv.load

require 'drifting_ruby'

DriftingRuby::Bot.run

# .env
SLACK_API_TOKEN=token_from_slack_api

# .gitignore
.env

# drifting_ruby/bot.rb
module DriftingRuby
  class Bot < SlackRubyBot::Bot
    help do
      title 'Drifting Ruby Bot'
      desc 'This bot is about Drifting Ruby.'

      command :get_latest_episode do
        title 'get_latest_episode'
        desc 'Returns the url of the latest Drifting Ruby Episode'
        long_desc 'Returns the url of the latest Drifting Ruby Episode'
      end
    end
  end
end

# drifting_ruby/commands/get_episode.rb
require 'rss'
require 'open-uri'

module DriftingRuby
  module Commands
    class GetEpisode < SlackRubyBot::Commands::Base
      command 'get_latest_episode' do |client, data, _match|
        url = 'https://www.driftingruby.com/episodes/feed.rss'
        rss = RSS::Parser.parse(open(url).read, false).items.first
        client.say(channel: data.channel, text: rss.link)
      end

      command 'say_hello' do |client, data, _match|
        client.say(channel: data.channel, text: HelloText.say_hello)
      end
    end
  end
end

class HelloText
  def self.say_hello
    'Hello! This is a Bot!'
  end
end