{"id":13879957,"url":"https://github.com/slack-ruby/slack-ruby-bot","last_synced_at":"2025-05-14T18:01:48.708Z","repository":{"id":34508111,"uuid":"38449382","full_name":"slack-ruby/slack-ruby-bot","owner":"slack-ruby","description":"The easiest way to write a Slack bot in Ruby.","archived":false,"fork":false,"pushed_at":"2021-05-02T20:05:07.000Z","size":5849,"stargazers_count":1114,"open_issues_count":37,"forks_count":186,"subscribers_count":32,"default_branch":"master","last_synced_at":"2025-05-14T08:57:55.548Z","etag":null,"topics":["bots","ruby","slackbot"],"latest_commit_sha":null,"homepage":"","language":"Ruby","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/slack-ruby.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":".github/FUNDING.yml","license":"LICENSE.md","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null},"funding":{"github":["dblock"]}},"created_at":"2015-07-02T18:21:53.000Z","updated_at":"2025-05-13T04:10:20.000Z","dependencies_parsed_at":"2022-09-06T04:11:54.111Z","dependency_job_id":null,"html_url":"https://github.com/slack-ruby/slack-ruby-bot","commit_stats":null,"previous_names":[],"tags_count":39,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/slack-ruby%2Fslack-ruby-bot","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/slack-ruby%2Fslack-ruby-bot/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/slack-ruby%2Fslack-ruby-bot/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/slack-ruby%2Fslack-ruby-bot/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/slack-ruby","download_url":"https://codeload.github.com/slack-ruby/slack-ruby-bot/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254131270,"owners_count":22019913,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["bots","ruby","slackbot"],"created_at":"2024-08-06T08:02:40.484Z","updated_at":"2025-05-14T18:01:48.690Z","avatar_url":"https://github.com/slack-ruby.png","language":"Ruby","readme":"Slack-Ruby-Bot\n==============\n\n[![Gem Version](https://badge.fury.io/rb/slack-ruby-bot.svg)](http://badge.fury.io/rb/slack-ruby-bot)\n[![Build Status](https://travis-ci.org/slack-ruby/slack-ruby-bot.svg)](https://travis-ci.org/slack-ruby/slack-ruby-bot)\n[![Code Climate](https://codeclimate.com/github/slack-ruby/slack-ruby-bot/badges/gpa.svg)](https://codeclimate.com/github/slack-ruby/slack-ruby-bot)\n\n---\n\n**Warning**: As of December 4th, 2020 Slack no longer accept resubmissions from apps that are not using granular permissions, or so-called \"classic apps\". On November 18, 2021 Slack will start delisting apps that have not migrated to use granular permissions. This library implements legacy, real-time support for classic apps. You should not be building a new bot with it and use [slack-ruby-bot-server-events](https://github.com/slack-ruby/slack-ruby-bot-server-events) instead. For a rudimentary bot you can even start with [slack-ruby-bot-server-events-app-mentions](https://github.com/slack-ruby/slack-ruby-bot-server-events-app-mentions). See [MIGRATION](MIGRATION.md) for migration help.\n\n---\n\nThe slack-ruby-bot library is a generic Slack bot framework written in Ruby on top of [slack-ruby-client](https://github.com/slack-ruby/slack-ruby-client). This library does all the heavy lifting, such as message parsing, so you can focus on implementing slack bot commands. It also attempts to introduce the bare minimum number of requirements or any sorts of limitations. It's a Slack bot boilerplate.\n\nIf you are not familiar with Slack bots or Slack API concepts, you might want to watch [this video](http://code.dblock.org/2016/03/11/your-first-slack-bot-service-video.html).\n\n![](slack.png)\n\n# Table of Contents\n\n- [Useful to Me?](#useful-to-me)\n- [Stable Release](#stable-release)\n- [Usage](#usage)\n  - [A Minimal Bot](#a-minimal-bot)\n    - [Gemfile](#gemfile)\n    - [pongbot.rb](#pongbotrb)\n  - [A Production Bot](#a-production-bot)\n  - [More Involved Examples](#more-involved-examples)\n  - [Commands and Operators](#commands-and-operators)\n  - [Threaded Messages](#threaded-messages)\n  - [Bot Aliases](#bot-aliases)\n  - [Generic Routing](#generic-routing)\n  - [Matching text in message attachments](#matching-text-in-message-attachments)\n  - [Providing description for your bot and commands](#providing-description-for-your-bot-and-commands)\n  - [Customize your command help output](#customize-your-command-help-output)\n  - [SlackRubyBot::Commands::Base](#slackrubybotcommandsbase)\n  - [Authorization](#authorization)\n  - [Built-In Commands](#built-in-commands)\n    - [[bot name]](#bot-name)\n    - [[bot name] hi](#bot-name-hi)\n    - [[bot name] help](#bot-name-help)\n  - [Hooks](#hooks)\n    - [Implementing and registering a Hook Handler](#implementing-and-registering-a-hook-handler)\n      - [Hooks registration on SlackRubyBot::Server initialization](#hooks-registration-on-slackrubybotserver-initialization)\n      - [Hooks registration on a SlackRubyBot::Server instance](#hooks-registration-on-a-slackrubybotserver-instance)\n      - [Hooks registration on SlackRubyBot::Server class](#hooks-registration-on-slackrubybotserver-class)\n  - [Bot Message Protection](#bot-message-protection)\n  - [Message Loop Protection](#message-loop-protection)\n  - [Logging](#logging)\n  - [Advanced Integration](#advanced-integration)\n  - [Proxy Configuration](#proxy-configuration)\n  - [Model-View-Controller Design](#model-view-controller-design)\n    - [Controller](#controller)\n    - [Model](#model)\n    - [View](#view)\n  - [Testing](#testing)\n    - [RSpec Shared Behaviors](#rspec-shared-behaviors)\n    - [Testing Lower Level Messages](#testing-lower-level-messages)\n  - [Useful Libraries](#useful-libraries)\n- [Contributing](#contributing)\n- [Upgrading](#upgrading)\n- [Copyright and License](#copyright-and-license)\n\n## Useful to Me?\n\n* If you are just trying to send messages to Slack, use [slack-ruby-client](https://github.com/slack-ruby/slack-ruby-client), which this library is built on top of.\n* If you're trying to roll out a full service with Slack button integration, check out [slack-ruby-bot-server](https://github.com/slack-ruby/slack-ruby-bot-server), which uses this library.\n* Otherwise, this piece of the puzzle will help you create a single bot instance for one team.\n\n## Stable Release\n\nYou're reading the documentation for the **next** release of slack-ruby-bot.\nPlease see the documentation for the [last stable release, v0.16.1](https://github.com/slack-ruby/slack-ruby-bot/tree/v0.16.1) unless you're integrating with HEAD.\nSee [CHANGELOG](CHANGELOG.md) for a history of changes and [UPGRADING](UPGRADING.md) for how to upgrade to more recent versions.\n\n## Usage\n\n### A Minimal Bot\n\n#### Gemfile\n\n```ruby\nsource 'https://rubygems.org'\n\ngem 'slack-ruby-bot'\ngem 'async-websocket', '~\u003e0.8.0'\n```\n\n#### pongbot.rb\n\n```ruby\nrequire 'slack-ruby-bot'\n\nclass PongBot \u003c SlackRubyBot::Bot\n  command 'ping' do |client, data, match|\n    client.say(text: 'pong', channel: data.channel)\n  end\nend\n\nPongBot.run\n```\n\nAfter [registering the bot](DEPLOYMENT.md), run with `SLACK_API_TOKEN=... bundle exec ruby pongbot.rb`. Have the bot join a channel and send it a ping.\n\n![](screenshots/demo.gif)\n\n### A Production Bot\n\nA typical production Slack bot is a combination of a vanilla web server and a websocket application that talks to the Slack Real Time Messaging API. See our [Writing a Production Bot](TUTORIAL.md) tutorial for more information.\n\n### More Involved Examples\n\nThe following examples of bots based on slack-ruby-bot are listed in growing order of complexity.\n\n* [slack-bot-on-rails](https://github.com/dblock/slack-bot-on-rails): A bot running on Rails and using React to display Slack messages on a website.\n* [slack-mathbot](https://github.com/dblock/slack-mathbot): Slack integration with math.\n* [slack-google-bot](https://github.com/dblock/slack-google-bot): A Slack bot that searches Google, including CSE.\n* [slack-aws](https://github.com/dblock/slack-aws): Slack integration with Amazon Web Services.\n* [slack-deploy-bot](https://github.com/accessd/slack-deploy-bot): A Slack bot that helps you to deploy your apps.\n* [slack-gamebot](https://github.com/dblock/slack-gamebot): A game bot service for ping pong, chess, etc, hosted at [playplay.io](http://playplay.io).\n* [slack-victorbot](https://github.com/uShip/victorbot): A Slack bot to talk to the Victorops service.\n\n### Commands and Operators\n\nBots are addressed by name, they respond to commands and operators. You can combine multiple commands.\n\n```ruby\nclass CallBot \u003c SlackRubyBot::Bot\n  command 'call', '呼び出し' do |client, data, match|\n    client.say(channel: data.channel, text: 'called')\n  end\nend\n```\n\nCommand match data includes `match['bot']`, `match['command']` and `match['expression']`. The `bot` match always checks against the `SlackRubyBot::Config.user` and `SlackRubyBot::Config.user_id` values obtained when the bot starts.\n\nThe `command` method can take strings, which will have to be escaped with `Regexp.escape`, and regular expressions.\n\n```ruby\nclass CallBot \u003c SlackRubyBot::Bot\n  command 'string with spaces', /some\\s*regex+\\?*/ do |client, data, match|\n    client.say(channel: data.channel, text: match['command'])\n  end\nend\n```\n\nOperators are 1-letter long and are similar to commands. They don't require addressing a bot nor separating an operator from its arguments. The following class responds to `=2+2`.\n\n```ruby\nclass MathBot \u003c SlackRubyBot::Bot\n  operator '=' do |client, data, match|\n    # implementation detail\n  end\nend\n```\n\nOperator match data includes `match['operator']` and `match['expression']`. The `bot` match always checks against the `SlackRubyBot::Config.user` setting.\n\n### Threaded Messages\n\nTo reply to a message in a thread you must provide a reference to the first message that initiated the thread, which is available as either `data.ts` if no threaded messages have been sent, or `data.thread_ts` if the message being replied to is already in a thread. See [message-threading](https://api.slack.com/docs/message-threading) for more information.\n\n```ruby\ncommand 'reply in thread' do |client, data, match|\n  client.say(\n    channel: data.channel,\n    text: \"let's avoid spamming everyone, I will tell you what you need in this thread\",\n    thread_ts: data.thread_ts || data.ts\n  )\nend\n```\n\n_Note that sending a message using only `thread_ts: data.ts` can cause some permanent issues where Slack will keep reporting inaccessible messages as unread. At the time of writing the slack team is still having problems clearing those notifications. As recommended by the slack documentation ..._\n\n\u003e A true parent's thread_ts should be used when replying. Providing a child's message ID will result in a new, detached thread breaking all context and sense.\n\n_... the replies to a thread should always be sent to the message `ts` that started the thread, available as `thread_ts` for subsequent messages. Hence `data.thread_ts || data.ts`._\n\nFor additional options, including broadcasting, see [slack-ruby-client#chat_postMessage](https://github.com/slack-ruby/slack-ruby-client/blob/41539c647ac877400f20aa338aa42d2ebfd2866b/lib/slack/web/api/endpoints/chat.rb#L105).\n\n### Bot Aliases\n\nA bot will always respond to its name (eg. `rubybot`) and Slack ID (eg. `@rubybot`), but you can specify multiple aliases via the `SLACK_RUBY_BOT_ALIASES` environment variable or via an explicit configuration.\n\n```\nSLACK_RUBY_BOT_ALIASES=:pp: table-tennis\n```\n\n```ruby\nSlackRubyBot.configure do |config|\n  config.aliases = [':pong:', 'pongbot']\nend\n```\n\n![](screenshots/aliases.gif)\n\nBots will also respond to a direct message, with or without the bot name in the message itself.\n\n![](screenshots/dms.gif)\n\n### Generic Routing\n\nCommands and operators are generic versions of bot routes. You can respond to just about anything by defining a custom route.\n\n```ruby\nclass Weather \u003c SlackRubyBot::Bot\n  match /^How is the weather in (?\u003clocation\u003e\\w*)\\?$/ do |client, data, match|\n    client.say(channel: data.channel, text: \"The weather in #{match[:location]} is nice.\")\n  end\nend\n```\n\n![](screenshots/weather.gif)\n\nYou can also capture multiple matchers with `scan`.\n\n```ruby\nclass Market \u003c SlackRubyBot::Bot\n  scan(/([A-Z]{2,5})/) do |client, data, stocks|\n    # lookup stock market price\n  end\nend\n```\n\n![](screenshots/market.gif)\n\nSee [examples/market](examples/market/marketbot.rb) for a working example.\n\n### Matching text in message attachments\n\nYou can respond to text in [attachments](https://api.slack.com/docs/message-attachments) with\n`attachment`. It will scan `text`, `pretext` and `title` fields in each attachment until a first\nmatch is found.\n\nFor example you can match [this example attachment](http://goo.gl/K0cLkH)\nby its `title` with the following bot:\n\n```ruby\nclass Attachment \u003c SlackRubyBot::Bot\n  attachment 'Slack API Documentation' do |client, data, match|\n    client.say(channel: data.channel, text: \"Matched by #{match.attachment_field}.\")\n    client.say(channel: data.channel, text: \"The attachment's text: #{match.attachment.text}.\")\n  end\nend\n```\n\nYou can also define which fields in attachment object should be scanned.\n\nScan only a single field:\n\n```ruby\nclass Attachment \u003c SlackRubyBot::Bot\n  attachment 'Slack API Documentation', :title do |client, data, match|\n    # implementation details\n  end\nend\n```\n\nScan multiple fields:\n\n```ruby\nclass Attachment \u003c SlackRubyBot::Bot\n  attachment 'Slack API Documentation', %i[text pretext author_name] do |client, data, match|\n    # implementation details\n  end\nend\n```\n\n### Providing description for your bot and commands\n\nYou can specify help information for bot or commands with `help` block, for example:\n\nin case of bot:\n\n```ruby\nclass WeatherBot \u003c SlackRubyBot::Bot\n  help do\n    title 'Weather Bot'\n    desc 'This bot tells you the weather.'\n\n    command 'clouds' do\n      desc 'Tells you how many clouds there\\'re above you.'\n    end\n\n    command 'What\\'s the weather in \u003ccity\u003e?' do\n      desc 'Tells you the weather in a \u003ccity\u003e.'\n      long_desc \"Accurate 10 Day Weather Forecasts for thousands of places around the World.\\n\" \\\n        'Bot provides detailed Weather Forecasts over a 10 day period updated four times a day.'\n    end\n  end\n\n  # commands implementation\nend\n```\n\n![](screenshots/help.png)\n\nin case of your own command:\n\n```ruby\nclass Deploy \u003c SlackRubyBot::Commands::Base\n  help do\n    title 'deploy'\n    desc 'deploys your app'\n    long_desc 'command format: *deploy \u003cbranch\u003e to \u003cenv\u003e* where \u003cenv\u003e is production or staging'\n  end\nend\n```\n\n### Customize your command help output\n\nIf you've used the `help` block described above to document your\ncommands, you can provide your own implementation of outputting help\nfor commands like so:\n\n```ruby\nclass Market \u003c SlackRubyBot::Bot\n  command 'help' do |client, data, match|\n    user_command = match[:expression]\n    help_attrs = SlackRubyBot::Commands::Support::Help.instance.find_command_help_attrs(user_command)\n    client.say(channel: data.channel, text: \"#{help_attrs.command_desc}\\n\\n#{help_attrs.command_long_desc}\")\n  end\nend\n```\n\n### SlackRubyBot::Commands::Base\n\nThe `SlackRubyBot::Bot` class is DSL sugar deriving from `SlackRubyBot::Commands::Base`. For more involved bots you can organize the bot implementation into subclasses of `SlackRubyBot::Commands::Base` manually. By default a command class responds, case-insensitively, to its name. A class called `Phone` that inherits from `SlackRubyBot::Commands::Base` responds to `phone` and `Phone` and calls the `call` method when implemented.\n\n```ruby\nclass Phone \u003c SlackRubyBot::Commands::Base\n  command 'call'\n\n  def self.call(client, data, match)\n    client.say(channel: data.channel, text: 'called')\n  end\nend\n```\n\nTo respond to custom commands and to disable automatic class name matching, use the `command` keyword. The following command responds to `call` and `呼び出し` (call in Japanese).\n\n```ruby\nclass Phone \u003c SlackRubyBot::Commands::Base\n  command 'call'\n  command '呼び出し'\n\n  def self.call(client, data, match)\n    client.say(channel: data.channel, text: 'called')\n  end\nend\n```\n\n### Authorization\n\nThe framework does not provide any user authentication or command authorization capability out of the box. However, the `SlackRubyBot::Commands::Base` class does check every command invocation for permission prior to executing the command. The default method always returns true.\n\nTherefore, subclasses of `SlackRubyBot::Commands::Base` can override the `permitted?` private method to provide its own authorization logic. This method is intended to be exploited by user code or external gems that want to provide custom authorization logic for command execution.\n\n```ruby\nclass AuthorizedBot \u003c SlackRubyBot::Commands::Base\n  command 'phone home' do |client, data, match|\n    client.say(channel: data.channel, text: 'Elliot!')\n  end\n\n  # Only allow user 'Uxyzabc' to run this command\n  def self.permitted?(client, data, match)\n    data \u0026\u0026 data.user \u0026\u0026 data.user == 'Uxyzabc'\n  end\nend\n```\n\n### Built-In Commands\n\nSlack-ruby-bot comes with several built-in commands. You can re-define built-in commands, normally, as described above.\n\n#### [bot name]\n\nThis is also known as the `default` command. Shows bot version and links.\n\n#### [bot name] hi\n\nPolitely says 'hi' back.\n\n#### [bot name] help\n\nGet help.\n\n### Hooks\n\nHooks are event handlers and respond to Slack RTM API [events](https://api.slack.com/events), such as [hello](lib/slack-ruby-bot/hooks/hello.rb) or [message](lib/slack-ruby-bot/hooks/message.rb). You can implement your own in a couple of ways:\n\n#### Implementing and registering a Hook Handler\n\nA Hook Handler is any object that respond to a `call` message, like a proc, instance of an object, class with a `call` class method, etc.\n\nHooks can be registered using different methods based on user preference / use case.\nCurrently someone can use one of the following methods:\n\n* Pass `hooks` in `SlackRubyBot::Server` initialization.\n* Register `hooks` on `SlackRubyBot::Server` using `on` class method.\n* Register `hooks` on `SlackRubyBot::Server` using `on` instance method.\n\n\n##### Hooks registration on `SlackRubyBot::Server` initialization\n\n```ruby\nSlackRubyBot::Server.new(hook_handlers: {\n  hello: MyBot::Hooks::UserChange.new,\n  user_change: [-\u003e(client, data) {  }, -\u003e(client, data) {}]\n})\n```\n\n##### Hooks registration on a `SlackRubyBot::Server` instance\n\n```ruby\n# Register an object that implements `call` method\nclass MyBot::Hooks::Hello\n  def call(client, data)\n    puts \"Hello\"\n  end\nend\n\nserver.on(:hello, MyBot::Hooks::Hello.new)\n\n# or register a lambda function to handle the event\nserver.on(:hello, -\u003e(client, data) { puts \"Hello!\" })\n```\n\nFor example, the following hook handles [user_change](https://api.slack.com/events/user_change), an event sent when a team member updates their profile or data. This can be useful to update the local user cache when a user is renamed.\n\n```ruby\nmodule MyBot\n  module Hooks\n    class UserChange\n      def call(client, data)\n        # data['user']['id'] contains the user ID\n        # data['user']['name'] contains the new user name\n        # ...\n      end\n    end\n  end\nend\n```\n\n##### Hooks registration on `SlackRubyBot::Server` class\n\nExample:\n\n```ruby\nmodule MyBot\n  class MyServer \u003c SlackRubyBot::Server\n    on 'hello' do |client, data|\n      # data['user']['id'] contains the user ID\n      # data['user']['name'] contains the new user name\n    end\n\n    on 'user_change', -\u003e(client, data) {\n      # data['user']['id'] contains the user ID\n      # data['user']['name'] contains the new user name\n    }\n  end\nend\n```\n\nThese will get pushed into the hook set on initialization.\n\nEither by configuration, explicit assignment or hook blocks, multiple handlers can exist for the same event type.\n\n### Bot Message Protection\n\nBy default bots do not respond to self or other bots. If you wish to change that behavior globally, set `allow_bot_messages` to `true`.\n\n```ruby\nSlackRubyBot.configure do |config|\n  config.allow_bot_messages = true\nend\n```\n\n### Message Loop Protection\n\nBy default bots do not respond to their own messages. If you wish to change that behavior globally, set `allow_message_loops` to `true`.\n\n```ruby\nSlackRubyBot.configure do |config|\n  config.allow_message_loops = true\nend\n```\n\n### Logging\n\nBy default bots set a logger to `$stdout` with `DEBUG` level. The logger is used in both the RealTime and Web clients.\n\nSilence logger as follows.\n\n```ruby\nSlackRubyBot::Client.logger.level = Logger::WARN\n```\n\nIf you wish to customize logger, set `logger` to your logger.\n\n```ruby\nSlackRubyBot.configure do |config|\n  config.logger = Logger.new(\"slack-ruby-bot.log\", \"daily\")\nend\n```\n\n### Advanced Integration\n\nYou may want to integrate a bot or multiple bots into other systems, in which case a globally configured bot may not work for you. You may create instances of [SlackRubyBot::Server](lib/slack-ruby-bot/server.rb) which accepts `token` and `aliases`.\n\n```ruby\nEM.run do\n  bot1 = SlackRubyBot::Server.new(token: token1, aliases: ['bot1'])\n  bot1.start_async\n\n  bot2 = SlackRubyBot::Server.new(token: token2, aliases: ['bot2'])\n  bot2.start_async\nend\n```\n\nFor an example of advanced integration that supports multiple teams, see [slack-gamebot](https://github.com/dblock/slack-gamebot) and [playplay.io](http://playplay.io) that is built on top of it.\n\n### Proxy Configuration\n\nThere are [several proxy options](https://github.com/slack-ruby/slack-ruby-client#web-client-options) that can be configured on `Slack::Web::Client`. You can also control what proxy options are used by modifying the `http_proxy` environment variable per [Net::HTTP's documentation](https://docs.ruby-lang.org/en/2.0.0/Net/HTTP.html#class-Net::HTTP-label-Proxies).\n\nNote that Docker on OSX seems to incorrectly set the proxy, [causing `Faraday::ConnectionFailed`](https://github.com/slack-ruby/slack-ruby-bot/issues/155), `ERROR -- : Failed to open TCP connection to : (getaddrinfo: Name or service not known)`. You might need to manually unset `http_proxy` in that case, eg. `http_proxy=\"\" bundle exec ruby ./my_bot.rb`.\n\n### Model-View-Controller Design\n\nThe `command` method is essentially a controller method that receives input from the outside and acts upon it. Complex behaviors could lead to a long and difficult-to-understand `command` block. A complex `command` block is a candidate for separation into classes conforming to the Model-View-Controller pattern popularized by Rails.\n\nThe library provides three helpful base classes named `SlackRubyBot::MVC::Model::Base`, `SlackRubyBot::MVC::View::Base`, and `SlackRubyBot::MVC::Controller::Base`.\n\nTesting a `command` block is difficult. As separate classes, the Model/View/Controller's behavior can be tested via `rspec` or a similar tool.\n\n#### Controller\n\nThe Controller is the focal point of the bot behavior. Typically the code that would go into the `command` block will now go into an instance method in a Controller subclass. The instance method name should match the command name exactly (case sensitive).\n\nAs an example, these two classes are functionally equivalent.\n\nConsider the following `Agent` class which is the simplest default approach to take.\n\n```ruby\nclass Agent \u003c SlackRubyBot::Bot\n  command 'sayhello', 'alternate way to call hello' do |client, data, match|\n    client.say(channel: data.channel, text: \"Received command #{match[:command]} with args #{match[:expression]}\")\n  end\nend\n```\n\nUsing the MVC functionality, we would create a controller instead to encapsulate this function.\n```ruby\nclass MyController \u003c SlackRubyBot::MVC::Controller::Base\n  def sayhello\n    client.say(channel: data.channel, text: \"Received command #{match[:command]} with args #{match[:expression]}\")\n  end\n  alternate_name :sayhello, :alternate_way_to_call_hello\nend\nMyController.new(MyModel.new, MyView.new)\n```\nNote in the above example that the Controller instance method `sayhello` does not receive any arguments. When the instance method is called, the Controller class sets up some accessor methods to provide the normal `client`, `data`, and `match` objects. These are the same objects passed to the `command` block.\n\nHowever, the Controller anticipates that the model and view objects should contain business logic that will also operate on the `client`, `data`, and `match` objects. The controller provides access to the model and view via the `model` and `view` accessor methods. The [inventory example](examples/inventory/inventorybot.rb) provides a full example of a Model, View, and Controller working together.\n\nA Controller may need helper methods for certain work. To prevent the helper method from creating a route that the bot will respond to directly, the instance method name should begin with an underscore (e.g. `_my_helper_method`). When building the bot routes, these methods will be skipped.\n\nCalling `alternate_name` after the method definition allows for method aliases similar to the regular `command` structure. When commands can be triggered by multiple text strings it's useful to have that ability map to the controller methods too.\n\nLastly, the Controller class includes `ActiveSupport::Callbacks` which allows for full flexibility in creating `before`, `after`, and `around` hooks for all methods. Again, see the [inventory example](examples/inventory/inventorybot.rb) for more information.\n\n#### Model\n\nA complex bot may need to read or write data from a database or other network resource. Setting up and tearing down these connections can be costly, so the model can do it once upon instantiation.\n\nThe Model also includes `ActiveSupport::Callbacks`.\n\n```ruby\nclass MyModel \u003c SlackRubyBot::MVC::Model::Base\n  define_callbacks :sanitize\n  set_callback :sanitize, :around, :sanitize_resource\n  attr_accessor :_resource\n\n  def initialize\n    @db = setup_database_connection\n  end\n\n  def read(resource)\n    self._resource = resource\n    run_callbacks :sanitize do\n      @db.select(:column1 =\u003e resource)\n      # ... do some expensive work\n    end\n  end\n\n  private\n\n  def sanitize_resource\n    self._resource.downcase\n    result = yield\n    puts \"After read, result is #{result.inspect}\"\n  end\nend\n```\n\nLike Controllers, the Model is automatically loaded with the latest version of the `client`, `data`, and `match` objects each time the controller method is called. Therefore the model will always have access to the latest objects when doing its work. It will typically only use the `data` and `match` objects.\n\nModel methods are not matched to routes, so there is no restriction on how to name methods as there is in Controllers.\n\n#### View\n\nA typical bot just writes to a channel or uses the web client to react/unreact to a message. More complex bots will probably require more complex behaviors. These should be stored in a `SlackRubyBot::MVC::View::Base` subclass.\n\n```ruby\nclass MyView \u003c SlackRubyBot::MVC::View::Base\n  define_callbacks :logit\n  set_callbacks :logit, :around, :audit_trail\n\n  def initialize\n    @mailer = setup_mailer\n    @ftp = setup_ftp_handler\n  end\n\n  def email_admin(message)\n    run_callbacks :logit do\n      @mailer.send(:administrator, message)\n    end\n  end\n\n  def react_thumbsup\n    client.web_client.reactions_add(\n      name: :thumbsup,\n      channel: data.channel,\n      timestamp: data.ts,\n      as_user: true)\n  end\n\n  def react_thumbsdown\n    client.web_client.reactions_remove(\n      name: :thumbsup,\n      channel: data.channel,\n      timestamp: data.ts,\n      as_user: true)\n  end\n\n  private\n\n  def audit_trail\n    Logger.audit(\"Sending email at [#{Time.now}]\")\n    yield\n    Logger.audit(\"Email sent by [#{Time.now}]\")\n  end\nend\n```\nAgain, the View will have access to the most up to date `client`, `data`, and `match` objects. It will typically only use the `client` and `data` objects.\n\nView methods are not matched to routes, so there is no restriction on how to name methods as there is in Controllers.\n\n### Testing\n\n#### RSpec Shared Behaviors\n\nSlack-ruby-bot comes with a number of shared RSpec behaviors that can be used in your RSpec tests.\n\n* [behaves like a slack bot](lib/slack-ruby-bot/rspec/support/slack-ruby-bot/it_behaves_like_a_slack_bot.rb): A bot quacks like a Slack Ruby bot.\n* [respond with slack message](lib/slack-ruby-bot/rspec/support/slack-ruby-bot/respond_with_slack_message.rb): The bot responds with a message.\n* [respond with slack messages](lib/slack-ruby-bot/rspec/support/slack-ruby-bot/respond_with_slack_messages.rb): The bot responds with a multiple messages.\n* [respond with error](lib/slack-ruby-bot/rspec/support/slack-ruby-bot/respond_with_error.rb): An exception is raised inside a bot command.\n* [start typing](lib/slack-ruby-bot/rspec/support/slack-ruby-bot/start_typing.rb): The bot calls `client.start_typing`.\n\nRequire `slack-ruby-bot/rspec` in your `spec_helper.rb` along with the following dependencies in Gemfile.\n\n```ruby\ngroup :development, :test do\n  gem 'rack-test'\n  gem 'rspec'\n  gem 'vcr'\n  gem 'webmock'\nend\n```\n\nUse the `respond_with_slack_message` matcher.\n\n```ruby\ndescribe SlackRubyBot::Commands do\n  it 'responds with any message' do\n    expect(message: \"#{SlackRubyBot.config.user} hi\").to respond_with_slack_message\n  end\n  it 'says hi' do\n    expect(message: \"#{SlackRubyBot.config.user} hi\").to respond_with_slack_message('hi')\n  end\nend\n```\n\nUse the `respond_with_slack_messages` matcher for multiple messages.\n\n```ruby\ndescribe SlackRubyBot::Commands do\n  it 'responds with more than one message' do\n    expect(message: \"#{SlackRubyBot.config.user} count\").to respond_with_slack_messages\n  end\n  it 'says one and two' do\n    expect(message: \"#{SlackRubyBot.config.user} count\").to respond_with_slack_messages(['one', 'two'])\n  end\nend\n```\n\nMessage matchers support regular expressions.\n\n```ruby\ndescribe SlackRubyBot::Commands do\n  it 'says hi' do\n    expect(message: \"#{SlackRubyBot.config.user} hi\").to respond_with_slack_message(/hi/)\n  end\nend\n```\n\nCheck that the bot called `client.start_typing(channel: 'channel')`.\n\n```ruby\ndescribe SlackRubyBot::Commands do\n it 'starts typing on channel' do\n    expect(message: \"#{SlackRubyBot.config.user} hi\").to start_typing(channel: 'channel')\n  end\nend\n```\n\n#### Testing Lower Level Messages\n\nYou can test client behavior at a lower level by fetching the message hook. The following example expects a bot command to call `client.typing(channel: data.channel)`.\n\n```ruby\ndescribe SlackRubyBot::Commands do\n  let(:app) { Server.new }\n  let(:client) { app.send(:client) }\n  let(:message_hook) { SlackRubyBot::Hooks::Message.new }\n  it 'receives a typing event' do\n      expect(client).to receive(:typing)\n      message_hook.call(\n        client,\n        Hashie::Mash.new(text: \"#{SlackRubyBot.config.user} type something\", channel: 'channel')\n      )\n    end\n  end\nend\n```\n\n### Useful Libraries\n\n* [newrelic-slack-ruby-bot](https://github.com/dblock/newrelic-slack-ruby-bot): NewRelic instrumentation for slack-ruby-bot.\n\n## Contributing\n\nSee [CONTRIBUTING](CONTRIBUTING.md).\n\n## Upgrading\n\nSee [CHANGELOG](CHANGELOG.md) for a history of changes and [UPGRADING](UPGRADING.md) for how to upgrade to more recent versions.\n\n## Copyright and License\n\nCopyright (c) 2015-2020, [Daniel Doubrovkine](https://twitter.com/dblockdotorg), [Artsy](https://www.artsy.net) and [Contributors](CHANGELOG.md).\n\nThis project is licensed under the [MIT License](LICENSE.md).\n","funding_links":["https://github.com/sponsors/dblock"],"categories":["Ruby"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fslack-ruby%2Fslack-ruby-bot","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fslack-ruby%2Fslack-ruby-bot","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fslack-ruby%2Fslack-ruby-bot/lists"}