The “Facebook’s Like” Alarm

Hi there! Ever wanted to know in real time if someone likes your facebook page?

We’ve got the solution for you! Here, in Mikamai, as most companies do, we have a Facebook page, and we are very proud of it. We wanted to have some kind of physical feedback in our office, to let us know in real time when we get a new fan.

So, that’s how we did it.

First of all, the device. We needed to have it on 24/7, it should be very cheap, low powered, and we wanted to have the possibility to add new features (audio, video, lights, physical devices ecc…) so the perfect choice was the RaspberryPI

Second, the programming language. The obvious choice for us is Ruby 🙂

Third… what will happen? We wanted something simple, effective and not too annoying, so we choose a simple sound, the Super Mario coin sample was perfect for us.

The set up is very very simple.

We started froma a brand new RaspberryPI, and we installed Ruby with RVM, following these easy steps

https://rvm.io/rvm/install

everything worked like a charm.

Then, we put this simple script in /home/pi/like_it/

    
require 'rubygems'
require 'net/http'
require 'json'

LIKES_FILE = "likes"
PLAYER = (RUBY_PLATFORM == "armv6l-linux-eabihf") ? "omxplayer" : "mpg123"

while true do
  begin
    response = Net::HTTP.get_response("graph.facebook.com","/mikamai")
    json = JSON.parse(response.body)

    old_likes =  File.open(LIKES_FILE, 'r').gets.to_i
    likes = json["likes"].to_i

    if (likes > old_likes)
      #fixme: with mpg123 the -o local option (obviously) returns an error, it's non blocking but could be fixed
      system(PLAYER + " coin.mp3 -o local")
      p "like"
    end

    File.open(LIKES_FILE, 'w') { |file| file.write(likes) }

    sleep (10)
  rescue
    p "ERROR!!! YOU SHOULD INVESTIGATE"
  end
end

If you are using GIT (You have to install GIT on your RaspberryPI as well) simply go in the home directory via ssh and checkout the project from

https://github.com/amicojeko/Like-It

In the Github project we also added a simple start script

#! /bin/sh

DIR=/home/pi/like_it
cd $DIR

# stdout goes in trash, stderr gets logged 
rvm-auto-ruby like_it.rb 1> /dev/null 2> $DIR/logs/like_it_error &

the coin sample file, the (empty) log files for errors and stdout, and the counter file (using a database for this project is a bit overkill)

and… that’s it!

The script is supersimple, it runs an infinite loop and checks for new likes every 10 seconds (since the real time API for likes is not available yet). It just calls the Facebook Open Graph Public API, it searches for the “likes” counter in the JSON file, and confronts it with the likes previously stored in the “likes” file. If the likes are increasing, it plays the audio file.

Simple, stupid and sooo effective 🙂

To make it start automatically everytime the RaspberryPI reboots, jus add this in the /etc/rc.local file

# starts like-it daemon as pi user
su pi -c '/home/pi/like_it/start'

Leave a Reply

wpDiscuz