Create a Slack bot to interact with your wiki

0

Wiki hubs have been the go-to tool for many teams. They are also used by many open source projects as a communication and organizational medium.

Over the past few years, Slack has become a tool used by many companies. Its main objective is effective communication between team members. Besides chat, Slack also offers apps that allow you to easily connect to other services, such as Trello, MailChimp, Blue Jeans, etc. But app integration isn’t the only feature Slack has to offer. Today we are going to look at something different. Bots in chat apps are nothing new, they date back to the days of IRC where we had bots that took care of different things, like bad chat behavior, weather forecast, games, etc The same concepts apply in Slack.

In this article, we are going to work on a wiki robot. Your team might need the help of a bot here and there sometimes, right?

The wiki platform we will be using is MediaWiki. Mediawiki is an open source wiki package that originally started on Wikipedia. It is one of the most widely used wiki systems.

To install

We will be using two main Ruby gems in this tutorial: media-wiki-api and slack-ruby-bot. We also want our bot to live somewhere, so let’s use the Sinatra framework and host our bot on Heroku.

Start by creating a directory named mou-wikibotand inside it, create two Ruby files, called mou-wikibot.rb and GemfileName. In the GemfileNameadd:

Gemfile:

source 'http://rubygems.org'

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

Let’s run bundle install to install these gems:

bundle install

Create another directory with the same name (mou-wikibot) and inside this directory create a Ruby file with the name bot.rb. the bot.rb the file looks like:

bot.rb:

module SlackWikibot
  class Bot < SlackRubyBot::Bot
  end
end

To create a web.rb file that will contain our web application and facilitate the hosting of the bot. Platforms like Heroku and OpenShift make it easy to deploy Sinatra apps.

web.rb:

require 'sinatra/base'

module SlackWikibot
  class Web < Sinatra::Base
    get "https://www.sitepoint.com/" do
      'Bot is running...'
    end
  end
end

MediaWiki

To create an article via the API, we first need to point to our MediaWiki API URL:

wiki_connection = MediawikiApi::Client.new "http://MEDIAWIKI-ADDRESS/api.php"

We use the create_page method to create an article, which requires two parameters: the title and the content of the article.

wiki_connection.create_page "SitePoint", "Some basic info about SitePoint"

Wiki article created

This created a page, but when this code is run directly from a script, we get nothing in return. There is an object we can use to access a parsed MediaWiki API response.

Contribution:

response = wiki_connection.create_page "SitePoint", "Some basic info about SitePoint"

If we call the data method now responsewe get a good hash.

{"result"=>"Success", "pageid"=>26, "title"=>"SitePoint", "contentmodel"=>"wikitext", "nochange"=>""}

We now have access to the pageid of the new wiki article. We can make a simple request http://MediaWiki-Address/?curid=26 and this will return the item.

Let’s look at another method used to delete our article. the delete requires two arguments: the title of the page and the reason for deleting the article. Since MediaWiki offers revisions and allows you to go back in time, having a removal reason is very useful.

wiki_connection.delete_page "SitePoint", "Reason for deletion"

To use this method, you must have an account and be logged in. It’s very simple :

wiki_connection.log_in "username", "password"

Now wherever we use the wiki_connection object, we are authenticated. If you are still not authorized to delete articles, it means that you are not in the groups which authorize this type of action. I had this problem even though I was the first user of the MediaWiki installation. In this case, you should go to Special: user rights page and add yourself to the bureaucrat and administrator groups.

Now create a directory named orders where we will add the commands that the SlackWikiBot will use. Inside of orders directory, create a new file called wiki.rb. The path to this new file is slack-wikibot/slack-wikibot/commands/wiki.rb.

This is where our commandments live, it can be structured in different ways. I suggest you take a look at the documentation for the slack-ruby-bot gem. I use the match operator, but there are other ways like command and scan. In this case, our bot monitors our chat and whenever it sees that we have used the !wiki create Where !wiki delete keywords, it will perform an action.

wiki.rb:

require 'mediawiki_api'
module SlackWikibot
  module Commands
    class Wiki < SlackRubyBot::Commands::Base
      wiki_connection = MediawikiApi::Client.new "http://MediaWiki-URL/api.php"
      wiki_connection.log_in "username", "password"
      match(/^!wiki create (?w*)s(?.*)$/) do |client, data, match |
        response = wiki_connection.create_page match[:titlewiki], match[:contentwiki]
        pageid = response.data["pageid"]
        client.say(channel: data.channel, text: "Your wiki is created http://MediaWiki-URL?curid=#{pageid}")
      end
      match(/^!wiki delete (?w*)s(?.*)$/) do |client, data, match |
        wiki_connection.delete_page match[:titlewiki], match[:reason]
        client.say(channel: data.channel, text: "Article #{match[:titlewiki]} page is deleted. Reason: #{match[:reason]}")
      end
    end
  end
end

Let’s take a look at our project structure:

└── slack-wikibot
    ├── Gemfile
    ├── Gemfile.lock
    ├── slack-wikibot.rb
    └── slack-wikibot
        ├── bot.rb
        └── commands
            └── wiki.rb

Now edit mou-wikibot.rb, which we created in the root directory, and which require the slack-ruby-bot gem. With this, our bot and wiki commands are created.

slack-wikibot.rb:

require 'slack-ruby-bot'
require 'slack-wikibot/bot'
require 'slack-wikibot/commands/wiki'

To create a config.ru file for our Rack application. We will create a thread for our bot and run the web server:

config.ru

$LOAD_PATH.unshift(File.dirname(__FILE__))

require 'dotenv'
Dotenv.load

require 'slack-wikibot'
require 'web'

Thread.abort_on_exception = true

Thread.new do
  begin
    SlackWikibot::Bot.run
  rescue Exception => e
    STDERR.puts "ERROR: #{e}"
    STDERR.puts e.backtrace
    raise e
  end
end

run SlackWikibot::Web

Let’s use Foreman because it allows us to easily manage our runtime dependencies. Foreman is also useful when we have environment variables, like in a .env file. Additionally, Heroku also uses Foreman.

We need an API key from Slack to be able to interact with the bot in the chat. Visit the bot service page while logged into your Slack team. The first step is to define a username for our bot:

slackbot_username

After clicking the “Add bot integration” button, the next step is to add information about our bot. We can set a name, upload an image, and set other properties. In addition, the necessary API key can be found on this page:

Slack API key

To create a .env file in the root directory of our project and add the API key:

SLACK_API_TOKEN=xoxb-68226463922-ceoVi1mZgGIQJxuVD6Gpu2CV

To create a Profile in the root directory, which Foreman will use when you run the command below:

Profile:

web: bundle exec puma -p $PORT

Now let’s run our bot:

foreman start

Deploy to Heroku

You will need to have the Heroku tools installed:

gem install heroku

Use the Heroku command to create the app:

heroku create

It will assign a random name and add a git remote repository. Now push your code to the Heroku repository.

To note: You will need to use git for this part, so if you haven’t, be sure to git add and git commit your code before pushing.

git push heroku master

Now, if you visit your Heroku app URL (yours will be different):

https://agile-retreat-96798.herokuapp.com/

You should get a page showing The robot is running…

Go back to Slack and use the /invite @YourBotsName to invite your bot to a channel. Then try one of the commands we created:

Wiki-bot_in_action

Conclusion

Bots are a very practical tool to automate part of our work. You can find more information about creating Slack bots in this article on SitePoint.

Whenever you find yourself doing repetitive work, think about whether it can be done by a bot. If the answer is “yes”, then there is no time to waste, start creating one. There are many advantages to having bots to do our work: they are fast and make few to no errors, to name a few. Now is the time to accept our new Slack-bot based lords 🙂

Share.

About Author

Comments are closed.