Skip to content

Instantly share code, notes, and snippets.

@alisha
Created January 12, 2016 01:07
Show Gist options
  • Save alisha/689df22ca1e976b49572 to your computer and use it in GitHub Desktop.
Save alisha/689df22ca1e976b49572 to your computer and use it in GitHub Desktop.
Use Twilio to let two friends communicate when one is texting and the other is calling
require 'twilio-ruby'
require 'sinatra'
# user 1 is texting
# user 2 is calling
ACCOUNT_SID = "..."
AUTH_TOKEN = "..."
TWILIO_PHONE_NUM = "+1..."
user1num = ""
# wait for starting text
get '/speaxter' do
@client = Twilio::REST::Client.new ACCOUNT_SID, AUTH_TOKEN
user1num = params[:From]
# validate format
message = params[:Body]
if /CALL \+[0-9]{11,} .+/.match(message).nil?
Twilio::TwiML::Response.new do |r|
r.Message "Start conversation with \"CALL [phone number] [message]\". You put \"" + message + "\""
end.text
# start call
else
# add spaces to User 1's phone number so it's read as digits
user1numLen = user1num.length
numberIndex = 0
user1numWithSpaces = String.new(user1num)
for i in 0..user1numLen-1
user1numWithSpaces.insert(numberIndex+1, ' ')
numberIndex += 2
end
# prepare call message
messageBodyIndex = message.index(/[0-9] /) + 2
messageLength = message.length
messageBody = "Message from " + user1numWithSpaces + ". " + message[messageBodyIndex..messageLength-1] + ". Please respond after the beep. Press any key to end your message."
# figure out who to call
user2numIndex = message.index(/\+[0-9]{11,}/)
user2num = message[user2numIndex..messageBodyIndex-2]
# change spaces to %20 for twimlet URL
messageBody = messageBody.gsub(/ /, "%20")
# create twimlet
# creates a response that says a message (messageBody) and records
twimletURL = "http://twimlets.com/echo?Twiml=%3CResponse%3E%0A%20%20%3CSay%3E" + messageBody + "%3C%2FSay%3E%0A%20%20%3CRecord%20action%3D%22http%3A%2F%2Ftwimlbin.com%2Fexternal%2Ff5f936c3db24c6d4%22%20method%3D%22get%22%20transcribe%3D%22true%22%20%2F%3E%0A%3C%2FResponse%3E"
@client.account.calls.create({
:from => TWILIO_PHONE_NUM,
:to => user2num,
:url => twimletURL,
:status_callback => "https://fathomless-scrubland-4992.herokuapp.com/handle-call"
})
end
end
# reply to User 1 with User 2's message
post '/handle-call' do
@client = Twilio::REST::Client.new ACCOUNT_SID, AUTH_TOKEN
text = ""
text = @client.account.transcriptions.list[0].transcription_text
if defined? text || text == ""
text = "no message :("
end
@client.messages.create(
from: TWILIO_PHONE_NUM,
to: user1num,
body: text
)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment