Posts Tagged ‘Ruby’

Update to AGItate

Friday, March 11th, 2011

I have released v0.1.3 of AGItate today. In case you have forgotten, AGItate turns Tropo into an Asterisk AGI client for use with the likes of Adhearsion, Asterisk-Java and others.

The following enhancements were made today:

  • AGItate now requires YAML to coincide with upcoming upgrade to JRuby 1.5.6 on Tropo.
  • There is now full support for the STREAM FILE command in Asterisk AGI.
  • The SAY DIGITS AGI command speaks the digits properly again.

If you are pulling directly from Github then you already have the update, if not go ahead and follow the instructions here to get the AGItate update up and running.

How to Build a Reminder Service Using Tropo and Ruby on Rails

Sunday, February 27th, 2011

Have you ever thought about starting a Reminder Service company and getting millions of dollars in funding all from a weekend project?  Tropo is here to help you with your communications needs in this endeavor!

The Reminder Service source code that I am about to share with you was started on the Nerd Bird (good to have in-flight WiFi) from Orlando to Phoenix, on my way back from the HIMSS conference.  It’s written in Ruby on Rails 3.0.4 and the Tropo Scripting API.

This is Tropo application is designed to demonstrate building a Reminder Service application using both Voice and SMS alerts.  The application will place an outbound reminder call to you 1 week in advance and then 1 day in advance and an SMS message 1 hour in advance of your appointment time.

You can demo the Reminder Service running on Heroku now.  It’s a basic Ruby on Rails scaffolding interface with the ability to create, update, and delete reminders.  All reminders are tracked in UTC time to simplify the demo and there is no authentication because IT’S A DEMO.

The source code is on GitHub.  Simply clone this application from GitHub and run the following statements from your command line:

bundle install
rake db:create
rake db:migrate

Setup an account at Tropo and create a new Scripting API application.  Copy and paste the source code from tropo_scripting_api.rb into separate scripts running under the same application. One for placing outbound voice call reminders and one for sending SMS message reminders.

Here is the source code to place the phone call on Tropo.

message($remindermessage, {
  :to => $phonenumber,
  :channel => "VOICE"
})

Here is the source code to send an SMS message on Tropo.

message($remindermessage, {
  :to => $phonenumber,
  :network => "SMS"
})

Add a phone number to your Tropo application.  SMS messages will not work without one.

The rest of the magic happens in the API controller as shown below:

class ApiController < ApplicationController
  def check
    require 'time'

    @reminders = Reminder.where("(appointment > ?) and (appointment < ?) and ( flag1 IS NULL or flag2 IS NULL or flag3 IS NULL)", Time.now.utc, Time.now.utc+1.week )

    @reminders.each do |reminder|

      if reminder.appointment-1.hour < Time.now.utc && reminder.flag3.nil?

        # Send SMS
        RestClient.get 'https://api.tropo.com/1.0/sessions', {:params => {
          :action => 'create',
          :token => '848b6b17c6229844827847b381...58eaa12683b6ea0a8aa5e166ee7bfcc8',
          :phonenumber => formatphone(reminder.phonenumber),
          :remindermessage => 'dont forget ' + reminder.message.to_s + ' at ' + reminder.appointment.to_s}}

        # Write Flag3
        @reminder = Reminder.find(reminder.id)
        @reminder.flag3 = true
        @reminder.save

      elsif reminder.appointment-1.day < Time.now.utc  && reminder.flag2.nil?

        # Place outbound reminder call
        RestClient.get 'https://api.tropo.com/1.0/sessions', {:params => {
          :action => 'create',
          :token => '3d5eed33429706408efcc0e92307b...d04af908e583112195de9ec7b05b9e',
          :phonenumber => formatphone(reminder.phonenumber),
          :remindermessage => 'dont forget ' + reminder.message.to_s + ' at ' + reminder.appointment.to_s}}

        # Write Flag2
        @reminder = Reminder.find(reminder.id)
        @reminder.flag2 = true
        @reminder.save

      elsif reminder.appointment-1.week < Time.now.utc && reminder.flag1.nil?

        # Place outbound reminder call
        RestClient.get 'https://api.tropo.com/1.0/sessions', {:params => {
          :action => 'create',
          :token => '3d5eed33429706408efcc0e92307b04...908e583112195de9ec7b05b9e',
          :phonenumber => formatphone(reminder.phonenumber),
          :remindermessage => 'dont forget ' + reminder.message.to_s + ' at ' + reminder.appointment.to_s}}

        # Write Flag1
        @reminder = Reminder.find(reminder.id)
        @reminder.flag1 = true
        @reminder.save
      end
    end

    if @reminders
      render :text => "sent " + @reminders.length.to_s + " reminders"
    else
      render :text => "no reminders"
    end
  end

  def formatphone(phone)
    @phone = phone.gsub("(", "").gsub(")", "").gsub("-", "").gsub(".", "").gsub(" ", "")
    if @phone[0..0] != '1'
      @phone = '1' + @phone
    end
    return @phone
  end
end

Now for the drum roll! Setup a cron job to call http://localhost:3000/api/check every 5 minutes, run rails server, and open your web browser to http://localhost:3000!  Oh, one last thing…Go ask one of those “super angels” for some cash-money :)

Send a Fax with your Voice!

Monday, February 21st, 2011

Tropo just recently partnered with PamFax to deliver faxing capabilities via an API.  Jason Goecke wrapped their API with a very simple Ruby gem called pamfaxr available at GitHub and installable using a “gem install pamfaxr” from your command line.  Using the PamFaxr Ruby gem, I will demonstrate how to send a simple fax as well as how to build a Tropo Voice to Fax transcription application using our Scripting API!

Getting Started

Before you can start sending faxes, you need to head over to the PamFax site and sign up for a PamFax account. After you fill out and submit the form, you’ll get an email with your login credentials and how to get started.

You also need to install the Ruby gem called pamfaxr on to the system where you are going to run the application that will send the fax. The Ruby gem is available at GitHub and should install simply by typing “gem install pamfaxr” from your command line. You will need to edit the code to have your PamFax username and password.

Sending A Fax From The Command Line

Before we involve Tropo, here is the Ruby/Sinatra code for simply sending a fax from the command line using the PamFaxr gem:

require 'rubygems'
require 'pamfaxr'

# Pass user name and password
pamfaxr = PamFaxr.new :username => 'your_username',
                      :password => 'secret'

# Create a new FaxJob
faxjob = pamfaxr.create_fax_job

# Add the cover sheet
covers = pamfaxr.list_available_covers
pamfaxr.set_cover(covers['Covers']['content'][1]['id'], 'Chris was here 2!')

# Add files
# pamfaxr.add_remote_file('https://s3.amazonaws.com/pamfax-test/R-intro.pdf')
# pamfaxr.add_file('examples/R-intro.pdf')

# Add a recipient
pamfaxr.add_recipient('+14802191300')

# Loop until the fax is ready to send
loop do
  fax_state = pamfaxr.get_state
  break if fax_state['FaxContainer']['state'] == 'ready_to_send'
  sleep 5
end

# Send the fax
pamfaxr.send_fax

Just copy that code into a text file, edit it to have your information in it and then run it with ruby from your command line. In a short bit you should have a fax waiting for you.

Sending Faxes From Tropo

Now for the fun Tropo Voice to Fax application code! The first code snippet is written in Ruby runs on the Tropo cloud. It greets the caller, asks for your fax number, records your voice/fax message and sends the transcription via a callback to the Ruby/Sinatra application that sends the actual fax.  Here’s the Tropo code:

say "Welcome to the Tropo fax demo.", :voice => 'dave'

result = ask "What's your fax number? Please include your country code.", {
   :choices => "[11 DIGITS]", :voice => 'dave'}

record "Please say what you would like for me to fax.", {
    :beep => false,
    :voice => 'dave',
    :maxTIme => 60,
    :silenceTimeout  => 2,
    :transcriptionOutURI => "http://web1.tunnlr.com:11053/transcribe?fax=" + result.value
    }

say "Your voice is being converted to a facsimily!  Go check your fax machine!  Goodbye.", :voice => 'dave'

hangup

Here is the complimentary Ruby/Sinatra code that catches the Tropo transcription callback and sends the fax of the transcription to the number specified in the Tropo script using the PamFaxr gem as demonstrated above. This code needs to be run on a publicly-accessible web server to which Tropo can connect and send the data. You have several options including:

  • Running the code on your own publicly-available webserver
  • Running the code on a hosting service like Heroku
  • Running the code on your local machine and use a service like Tunnlr to make the service available

Once you have the Ruby/Sinatra code below running in one of those locations, you’ll just update the Tropo code above with the correct URL (on line 11).

The code is here:

require "rubygems"
require "sinatra"
require 'json'
require 'pamfaxr'

pamfaxr = PamFaxr.new :username => 'your_username',
                      :password => 'secret'

post "/transcribe" do

  transcript_json = JSON.parse(request.body.read)
  identifier = transcript_json['result']['identifier']
  transcript = transcript_json['result']['transcription']

  # Create a new FaxJob
  faxjob = pamfaxr.create_fax_job

  # Add the cover sheet
  covers = pamfaxr.list_available_covers
  pamfaxr.set_cover(covers['Covers']['content'][1]['id'], transcript)

  # Add a recipient
  pamfaxr.add_recipient('+' + params[:fax])

  # Loop until the fax is ready to send
  loop do
    fax_state = pamfaxr.get_state
    break if fax_state['FaxContainer']['state'] == 'ready_to_send'
    sleep 5
  end

  # Send the fax
  pamfaxr.send_fax

end

Wow, that was fun!  I hope that you enjoyed this demonstration and I hope that you find both our PamFaxr gem and our Tropo Scripting API useful and powerful.

Handling regular users vs casual users via the text channel

Tuesday, February 15th, 2011

Typically you will find that your applications have two types of users, the regular user and the casual user.  The difference is based on experience, some users know how to interact with the application because they are regular users, others need some instructions.  This is especially evident in a Text channel application, such as an Instant Message or SMS, where the regular user might message with the expected value right away – for example, providing the answer to the expected question before you actually asked the question, such as a zip code:

In this scenario we can save ourselves, and the user, the trouble of sending them instructions. However, the uneducated user may send a “hi” or “hello” or any number of initial responses to your application; you will need to handle each type of user appropriately in your application.

Doing so is pretty simple, you just need to use the $currentCall object’s initalText parameter, and check the value to see if it’s what your looking for. I fashioned a quick example below that can help get you started!

fruit_list = "apples, oranges, pears"

log "@"*10 + " " + $currentCall.initialText

    if fruit_list.include?($currentCall.initialText)
        result = ask "What's your favorite fruit? apples, oranges, or pears?", {:choices => fruit_list}
    else
        ask "",{:choices=>'[ANY]'}
        say "Hello and welcome to the fruit guessing game"
        result = ask "What's your favorite fruit? apples, oranges, or pears?", {:choices => fruit_list}
    end
        say "I like #{result.value} to"
        say "see ya later!"

All we do here is check the value in initialText to determine if we need to handle it as an acceptable utterance against our choice / grammar. If it’s a zipcode, you could just check to see if its numeric. You can get as complicated or as simple as you want, the choice is really entirely up to you.

I do hope this helps!

-John

Command Line SMS

Sunday, January 30th, 2011

Ever have the desire to send an SMS message from the command line?  We’ll with bash functions its quite simple, and I’ll show you how!

First lets deploy the Tropo code, we’ll use Ruby for this example:

message($messageToSend, { 
    :to => $numberToMessage, 
    :network=>'SMS',
    :callerID=>$callerID.to_s
    }) 

Please note that you will want to ensure that you have an SMS enable number associated with the application, as this is a requirement in order to send an SMS on Tropo. You will also want to make note of the messaging token once you create the application, as this will be important for the next part:

Below you’ll see an easy function you can add to your .bash_profile. (non *nix based operating systems need not apply). You will need to set the callerID and the TOKEN_ID variables to the correct values specific to the application you created in the previous step. Setting the callerID to the number is critical, as the app will not function without it!

function sms(){  
    TOKEN_ID='your_token_id_goes_here'
    APP_CALLER_ID='4075551234'      #This needs to be a valid callerID associated with your application
    ENCODED=$(echo -n ${*:2:100} | \
    perl -pe's/([^-_.~A-Za-z0-9])/sprintf("%%%02X", ord($1))/seg');
    curl "http://api.tropo.com/1.0/sessions?action=create\
          &token=$TOKEN_ID&numberToMessage=$1\
          &messageToSend=$ENCODED&callerID=$APP_CALLER_ID\
          " > /dev/null 2>&1
}     

The function takes two sets of parameters, the first is your 10 digit phone number, and second is the message to send. Since we are doing a HTTP get request we will need to make sure we property URL encode the data, which I have used Perl here to take care of for us! This URL encoded value is placed into the messageToSend parameter in our resulting HTTP request.

So all we have to do now is drop to Terminal, and then issue our command:

Then check out your phone:

Pretty cool, huh? -John

$40,000 in prizes up for grabs. Win with your source code.

Saturday, January 29th, 2011

Binpress is a new startup that’s built a marketplace for code. Sell your code, buy code from others. Whether you have a content management system, a plugin for WordPress or Drupal, or a great new UI widget built with jQuery, Binpress helps you market and sell your code. They take care of the license agreements, the ecommerce, and all the hassles associated with selling software.

To kick off their marketplace, they’re running a developer contest with $40,000 in prizes. They came to Tropo, wondering if we might be interested in providing a prize for the best code in one of the languages they support: PHP, Ruby, Javascript, Java, Python, or ASP.net.

Hmm, that list of languages looks pretty familiar. Tropo lets you host your code in PHP, Ruby, Javascript, Groovy (a Java-based scripting language), or Python. We have code libraries for our REST and WebAPI platforms using .Net, PHP, Ruby, Python, and Node.js.

We jumped right in and offered to sponsor not one language, but all of them. While we’re at it, we’re kicking in prizes for the rest of the contest, too.

Build the best app in one of Binpress’s languages and Binpress will give you $350 and a $100 Tropo credit for production usage. Win the Grand Prize — the best of show, as it were — and they’ll give you $1000 in Tropo credit. The second and third place winners will get $500 and $250 in Tropo credit, respectively.

There’s a whole lot of prizes totaling over $40,000, including service vouchers from Amazon Web Services, Media Temple, Sendgrid, Github, and Zencoder, cash from Conduit and Microsoft, and books from O’Reilly and Wrox.

Go jump in and build something awesome. You’ve got a month to create your masterpiece and win.

Join Tropo at MagicRuby 11 Orlando Feb 4-5

Thursday, January 20th, 2011

Ruby Developers take note:  Tropo is sponsoring  MagicRuby 11!   MagicRuby is a free Ruby conference produced by Jeremy McAnally taking place February 4th and 5th at the Contemporary Resort in Disney World in Orlando, Florida.

Conference organizers have assembled an amazing lineup of speakers including keynoter and Ruby luminary Chad Fowler of InfoEther. Other speakers include guys from GithubRed HatEngine YardEnvy Labs and Intridea.

One example of the amazing talks scheduled at MagicRuby 2011: our friends at Envy Labs are giving a talk about lessons they don’t teach in programming classes. It takes more than just technical skills to succeed at being a software developer. You may also need to communicate effectively, manage projects, train your clients, and mainly just play well with others. We developers are an anti-social breed who enjoy being left to our own devices, so many of these skills don’t come naturally.

Gregg Pollack and Caike Souza will give some tips to help software developers improve their craft and increase the odds of succeeding at our chosen field. They’ll also share some of the core principles that they hold dear at Envy Labs, and show how they implement them on a daily basis.

QR Code Fun with Tropo!

Friday, January 14th, 2011

qrcode Have you seen one of these codes before?  They’re called QR Codes and can be used on mobile phones to direct your browser to a specific web page or even display more information (4,000 characters) about a product or event.  They can also be used to dial phone numbers and send SMS messages too!

Some mobile phones ship with pre-installed QR Code readers on them but more often than not, you will need to go into your phone’s AppStore and download one for your device.  Once your your scanner is loaded – point it at this code – I DOUBLE DOG DARE YA!

This code was generated to call a phone number associated with the following Tropo script:

say "http://hosting.tropo.com/13539/www/audio/rickroll.wav"
say "http://the-ppole.com/audio/Hotlinkers.mp3"

This Tropo script is running on our Scripting API and basically announces that you are about to be “Rick Rolled” and then proceeds to play to famous Rick Astley song “Never Gonna Give You Up” from some random MP3 link on the Internet.  Imagine the fun that you could have with combining QR Codes with Tropo numbers to route mobile phones to your new killer Tropo application!

I used a QR Code generator from Kaywa to create the image you see above.  Here’s an example of how easy it is to create:

Have Fun!

Scotty, We Need More Power!

Tuesday, January 11th, 2011

Captain Kirk was always demanding more out of his Chief Engineer on Star Trek by saying, “Scotty, we need more power.”

While there is no limit on the number of inbound SMS messages your application can receive, Tropo’s 10 digit numbers are limited by the SMS carriers to sending 10 outbound messages per minute per number (UPDATE – this limit has been improved to 1 message per second, 60 messages per minute as of July 22, 2011).  All 10 digit US SMS numbers have such a rate limit but it’s up to each API provider to adhere to their request.

Our SMS Shortcodes, on the other hand, have no limit on outbound SMS messages but there is a leasing fee to acquire these “Warp Speed” numbers.  Contact sales@tropo.com if you are interested!

If you feel like Captain Kirk when using 10 digit numbers and you want more power but you are not ready to move up to our SMS Shortcodes, here’s a trick!  You can attach an unlimited number of 10 digit voice/sms numbers to your Tropo application.  Each number is capable of sending 10 messages per minute per number.  Simply spread your outbound SMS messages over a larger pool of 10 digit Tropo numbers!

Here is an example of how I was able to help a customer do this using Ruby:

rate = 10 #per minute
totalmessages = 30
numbers = ["15123330824", "15713575541"]
count = 0
total = 0
starttime = Time.new

while total <  totalmessages do
  if Time.now - starttime < 60 and count < rate
    numbers.each do |number|
      # Send SMS
      message "hello " + count.to_s, {
        :to => "tel:+14803194368",
        :callerID => "tel:+" + number,
        :network => "SMS"}
    end
    count = count + 1
    total = total + 1

  elsif Time.now - starttime > 60
    # Reseting counters
    starttime = Time.new
    count = 0
  end
end

In this example, we set the rate limit and the totalmessages that we would like to send out. We attached multiple phone numbers to our Tropo application and list them in the numbers array. Next, we loop through the numbers sending an SMS message for each number until we hit our rate limit for the minute. Finally, we wait for the rest of the minute and reset the timer and counters and loop through the rest of next batch of numbers until our totalmessages are hit.

Tropo Sponsors MountainWest RubyConf

Tuesday, January 11th, 2011

Tropo is now a proud sponsor of the 2011 MountainWest RubyConf!

MWRC is a two-day single-track conference for just $100. Come rub elbows with some of the smartest Rubyists in the world.

March 17-18, 2011
Salt Lake City Public Library
210 E 400 S
Salt Lake City, UT 84111

This conference is in a great venue (the public library’s auditorium) and it typically gets over 100300 Rubyists in attendance.  They are currently overwhelmed with the number and quality of proposals submitted this year and their Board of Advisors has a difficult task to pare them down.

Registration will opeon on (or before) January 17th.  Get your ticket and come hang out for two days of Ruby fun.  We’ll be on-site with Tropo schwag and ready to lend a hand with your Voice, SMS, IM, or Twitter hacking!