13-Jan-2014 by Allison McMillan

Read Time: Approx. 3 minutes

Bot Refactoring

When something is built, it’s never fully done. A application without bugs doesn’t exists and once you release something into the world, there are always issues that come up and ways to make the code better. Releasing the bot into the irc channel brought to the surface a few issues that I’m working on. For example, the bot awards points not just to nicknames but to any word that comes after a number with a + or – symbol in front of it. I’ve also had to change a few regular expressions to make them more specific.

One of the main things I started working on once the initial bot was out was refactoring. Refactoring is important. It’s a way of going back into your code, cleaning it up, making it easier to understand and more transparent. Refactoring also helps to DRY out code, meaning that you look at your code to see when and how you repeat yourself and take out that repetition.

In the bot, there are two main places to refactor based on methods that are called often. For a majority of the functions, I provided an array of responses or gifs as a variable. I then called m.reply variable.sample. So instead of continuing to write this over and over again, I turned these actions into a method.

The method looks like this:

def reply_random(m, list)
m.reply list.sample
This is pretty easy to read but basically, the list is the array and so the method is to give a random reply based on the list given and replying with a random response from that list.

This is what a corresponding function now looks like:
  on :message, /.(coffee)./i do |m|
reply_random m, [

The second method I created to DRY out the code was the second most common functionality. This is where there is an array of response that are either replies or actions and instead of writing out the whole process (as explained in this post about bot functionality) I created an action or reply response method, which operates similarly to the reply_random method above.

def action_or_reply_response(m, list) 
list = list.sample
if list.first == :action
m.channel.action list.last
m.reply list.last

and again, with this change, this is what the code looks like:
  on :message, /.morning./ do |m|
action_or_reply_response m, [
[:reply, "Good morning to you too!"],
[:reply, "it's a brand new day!"],
[:reply, "I'm sleepy today"],
[:reply, "http://gifrific.com/wp-content/uploads/2012/04/bunny-sleep-work.gif"],
[:action, "yawns"],
[:action, "makes coffee"],
[:action, "throws open all the windows it's a glorious day today"]

Ready to chat?

Join my mailing list

* indicates required

Set up a free call

phone icon