Skip to content
Create a Slack bot that is smart and so easy to expand, create new bots on demand, run ruby code on chat, create shortcuts... The main scope of this gem is to be used internally in the company so teams can create team channels with their own bot to help them on their daily work, almost everything is suitable to be automated!! slack-smart-bot can…
Ruby
Branch: master
Clone or download
Latest commit 891b4c4 Sep 4, 2019
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
lib small bugfix Sep 4, 2019
.gitignore first commit May 14, 2019
.yardopts
LICENSE first commit May 14, 2019
README.md download file from slack Sep 3, 2019
slack-smart-bot.gemspec small bugfix Sep 4, 2019

README.md

Slack Smart Bot

Gem Version

Create a Slack bot that is really smart and so easy to expand.

The main scope of this ruby gem is to be used internally in your company so teams can create team channels with their own bot to help them on their daily work, almost everything is suitable to be automated!!

slack-smart-bot can create bots on demand, create shortcuts, run ruby code... just on a chat channel, you can access it just from your mobile phone if you want and run those tests you forgot to run, get the results, restart a server... no limits.

Table of Contents

Installation and configuration

$ gem install slack-smart-bot

After you install it you will need just a couple of things to configure it.

Create a file like this on the folder you want:

# the channel that will act like the master channel, main channel
MASTER_CHANNEL="my_master_channel"
#names of the master users
MASTER_USERS=["mario"]

require 'slack-smart-bot'

settings = {
    nick: 'my_smart_bot', # the smart bot name
    token: 'xxxxxxxxxxxxxxxxxx' # the API Slack token
}

puts "Connecting #{settings.inspect}"
SlackSmartBot.new(settings).listen

The MASTER_CHANNEL will be the channel where you will be able to create other bots and will have special treatment.

The MASTER_USERS will have full access to everything. You need to use the slack user name defined on https://YOUR_WORK_SPACE.slack.com/account/settings#username.

For the token remember you need to generate a token on the Slack web for the bot user.

You can get one by any of these options:

  • Slack App. Bot Token. (Recommended)

    1. Create a Slack App

    2. Add a bot user to your app. On Add features and functionality section for your app, select Bots. Click on Add a Bot User

    3. On your app click on the menu on the left: OAuth & Permissions and click on Install App to Workspace.

    4. Copy your Bot User OAuth Access Token.

  • Legacy API Token.

Remember to invite the smart bot to the channels where they will be accessible before creating the bot

Usage

creating the MASTER BOT

Let's guess the file you created was called my_smart_bot.rb so, just run it:

ruby my_smart_bot.rb

After the run, it will be generated a rules file with the same name but adding _rules, in this example: my_smart_bot_rules.rb

The rules file can be edited and will be only affecting this particular bot.

You can add all the rules you want for your bot in the rules file, this is an example:

def rules(user, command, processed, dest)
  from = user.name
  firstname = from.split(" ").first
  case command

    # help: `echo SOMETHING`
    # help:     repeats SOMETHING
    # help:
    when /^echo\s(.+)/i
      respond $1

    # help: `go to sleep`
    # help:   it will sleep the bot for 10 seconds
    # help:
    when /^go\sto\ssleep/i
      unless @questions.keys.include?(from)
        ask("do you want me to take a siesta?", command, from)
      else
        case @questions[from]
          when /yes/i, /yep/i, /sure/i
            @questions.delete(from)
            respond "I'll be sleeping for 10 secs... just for you"
            respond "zZzzzzzZZZZZZzzzzzzz!"
            sleep 10
          when /no/i, /nope/i, /cancel/i
            @questions.delete(from)
            respond "Thanks, I'm happy to be awake"
          else
            respond "I don't understand"
            ask("are you sure do you want me to sleep? (yes or no)", "go to sleep", from)
        end
      end

    # help: ----------------------------------------------
    # help: `run something`
    # help:   It will run the process and report the results when done
    # help:
    when /^run something/i
      respond "Running", dest

      process_to_run = "ruby -v"
      process_to_run = ("cd #{project_folder} &&" + process_to_run) if defined?(project_folder)
      stdout, stderr, status = Open3.capture3(process_to_run)
      if stderr == ""
        if stdout == ""
          respond "#{user.name}: Nothing returned.", dest
        else
          respond "#{user.name}: #{stdout}", dest
        end
      else
        respond "#{user.name}: #{stderr}", dest
      end

    else
      unless processed
        resp = %w{ what huh sorry }.sample
        respond "#{firstname}: #{resp}?"
      end
  end
end

How to access the smart bot

You can access the bot directly on the MASTER CHANNEL, on a secondary channel where the bot is running and directly by opening a private chat with the bot, in this case the conversation will be just between you and the bot.

Available commands even when the bot is not listening to you

Some of the commands are available always even when the bot is not listening to you but it is running

bot help

bot what can I do?

It will display all the commands we can use What is displayed by this command is what is written on your rules file like this: #help: THE TEXT TO SHOW

Hello Bot

Hello THE_NAME_OF_THE_BOT

Also apart of Hello you can use Hallo, Hi, Hola, What's up, Hey, Hæ

Bot starts listening to you

If you want to avoid a single message to be treated by the smart bot, start the message by -

Bye Bot

Bye THE_NAME_OF_THE_BOT

Also apart of Bye you can use Bæ, Good Bye, Adiós, Ciao, Bless, Bless Bless, Adeu

Bot stops listening to you

exit bot

quit bot

close bot

The bot stops running and also stops all the bots created from this master channel

You can use this command only if you are an admin user and you are on the master channel

start bot

start this bot

The bot will start to listen

You can use this command only if you are an admin user

pause bot

pause this bot

The bot will pause so it will listen only to admin commands

You can use this command only if you are an admin user

bot status

Displays the status of the bot

If on master channel and admin user also it will display info about bots created

create bot on CHANNEL_NAME

Creates a new bot on the channel specified.

slack-smart-bot will create a default rules file specific for your channel. You can edit it and add the rules you want. As soon as you save the file after editing it will become available on your channel.

It will work only if you are on Master channel

kill bot on CHANNEL_NAME

Kills the bot on the specified channel

Only works if you are on Master channel and you created that bot or you are an admin user

notify MESSAGE

notify all MESSAGE

It will send a notificaiton message to all bot channels

It will send a notification message to all channels the bot joined and private conversations with the bot

Only works if you are on Master channel and you are an admin user

Available commands only when listening to you or on demand or in a private conversation with the Smart Bot

All the commands described on here or on your specific Rules file can be used when the bot is listening to you or on demand or in a private conversation with the Smart Bot.

For the bot to start listening to you you need to use the "Hi bot" command or one of the aliases

Also you can call any of these commands on demand by using:

!THE_COMMAND

@BOT_NAME THE_COMMAND

BOT_NAME THE_COMMAND

Apart of the specific commands you define on the rules file of the channel, you can use:

ruby RUBY_CODE

code RUBY_CODE

runs the code supplied and returns the output. Also you can send a Ruby file. Examples:

code puts (34344/99)*(34+14)

ruby require 'json'; res=[]; 20.times {res<<rand(100)}; my_json={result: res}; puts my_json.to_json

Also it is possible to attach a Ruby file.

add shortcut NAME: COMMAND

add shortcut for all NAME: COMMAND

shortchut NAME: COMMAND

shortchut for all NAME: COMMAND

It will add a shortcut that will execute the command we supply.

In case we supply 'for all' then the shorcut will be available for everybody

Example: add shortcut for all Spanish account: /code require 'iso/iban'; 10.times {puts ISO::IBAN.random('ES')}

Then to call this shortcut:

sc spanish account

spanish account

shortcut Spanish Account

delete shortcut NAME

It will delete the shortcut with the supplied name

see shortcuts

It will display the shortcuts stored for the user and for :all

use rules from CHANNEL

it will use the rules from the specified channel.

you need to be part of that channel to be able to use the rules.

only when on a private conversation.

stop using rules from CHANNEL

it will stop using the rules from the specified channel.

only when on a private conversation.

extend rules to CHANNEL_NAME

use rules on CHANNEL_NAME

it will allow to use the specific rules from this channel on the CHANNEL_NAME

stop using rules on CHANNEL_NAME

it will stop using the extended rules on the specified channel.

Available commands from channels without a Smart Bot

@BOT_NAME on #CHANNEL_NAME COMMAND

It will run the supplied command using the rules on the channel supplied.

You need to join the specified channel to be able to use those rules.

Also you can use this command to call another bot from a channel with a running bot.

Creating cloud bots

If you need to run a channel bot from a different machine you can use the command:

create cloud bot on #CHANNEL_NAME

After that you will need to copy your current Smart Bot folder into the the new location. Install all you need: Ruby, slack-smart-bot... and run the command supplied by the Smart Bot after you run the create cloud command.

The new cloud bot will be managed by your Master Bot like the others, closing, pausing...

This is very useful when you need to run certain processes on a different environment for example on a Windows machine while your Master Bot is on Ubuntu.

Tips

Send a file

    send_file(to, msg, filepath, title, format, type = "text")
    send_file(dest, 'the message', "#{project_folder}/temp/logs_ptBI.log", 'title', 'text/plain', "text")
    send_file(dest, 'the message', "#{project_folder}/temp/example.jpeg", 'title', 'image/jpeg', "jpg")

Download a file

When uploading a file the message added to 'Add a message about the file' will be the command treated by the bot rule. Then in your rules file:

    when /^do something with my file/i
      if !files.nil? and files.size == 1 and files[0].filetype == 'yaml'
        require 'nice_http'
        http = NiceHttp.new(host: "https://files.slack.com", headers: { "Authorization" => "Bearer #{config[:token]}" })
        res = http.get(files[0].url_private_download, save_data: './tmp/')
        # if you want to directly access to the content use: `res.data`
      end

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/marioruiz/slack-smart-bot.

License

The gem is available as open source under the terms of the MIT License.

You can’t perform that action at this time.