Skip to content

Commit

Permalink
SMS Support. Readme file
Browse files Browse the repository at this point in the history
  • Loading branch information
Dag Liodden committed Dec 5, 2010
1 parent 75f83cb commit 27c7906
Show file tree
Hide file tree
Showing 7 changed files with 193 additions and 6 deletions.
131 changes: 131 additions & 0 deletions README.markdown
Original file line number Diff line number Diff line change
@@ -0,0 +1,131 @@
# Scwilio

Scwilio is a Scala API for Twilio. It is currently under heavy development, but most of the major Twilio functionality
is supported. The API aims to deliver Twilio functionality in several layers of abstraction:

1. Basic Twilio methods and TwiML generation
2. Higher level "phone devices" where all HTTP and URL plumbing is abstracted away and replace with plain functions
3. An Actor API

1 works well (although a few API methods are missing), 2 is working well but might still be refactored quite a bit.
3 should be easy once 2 is done. :)

## Basic Twilio methods and TwiML generation

To invoke Twilio methods, get an `TwilioClient` instance:

import scwilio._
val client = Twilio(ACCOUNT_SID, AUTH_TOKEN)

Then, invoke a method, e.g. for dialing a number or send an SMS:

client.dial(from = "+13477078794", to = "+4790055383", onConnect = Some("http://url.to.some.twiml"))
client.sendSms("+13152273664", "+4790055383", "Hello, there!")

To generate some TwiML, put this in a handler of whatever web framework your're using:

import scwilio.twiml._

val response = VoiceResponse(
Say("Hello, world"),
Pause(10),
Play("http://foo.com/cowbell.mp3"),
Say("Dialing 8 8 8 8"),
Dial(from = Phonenumber("+1999"), to = Phonenumber("+1888"), onConnect = Some("http://test"))
)
val stringResponse = TwiML(response).toString
// Write the response

## Phone devices

Making stateful Twilio services can be a pain. Using `Phone` instances, the HTTP plumbing can
can be removed completely. This allows for code like this:

val phone = DemoPhone()

// Import to enable function references to be implicitly converted into
// Unfiltered HTTP callbacks.
import phone.URLMaker._

val client = new TwilioClient(new RestClient(DemoConfig.accountSid, DemoConfig.authToken))

client.dial(from = "+13477078794", to = "+4790055383",
onConnect = (call: ActiveCall) => call.answeredBy match {
case Some(Machine) =>
println("Argh! Machine! Hanging up.")
VoiceResponse(Hangup)
case _ =>
VoiceResponse(
Say("This is an automated call. Nothing to hear here."),
Pause(10),
Say("Really!"),
Hangup
)
},
onEnd = (outcome : DialOutcome) =>
println("Call " + outcome + " ended after " + outcome.duration + " seconds")
)

Pretty neat, right?

This is still work in progress, but here's a more involved example of creating a basic conference
service using a `Phone` implementation using the Unfiltered web framework (see StatefulDemos example):

object ConferenceDemo extends Application with Logging {

val phone = DemoPhone()

// Import to enable function references to be implicitly converted into
// Unfiltered HTTP callbacks.
import phone.URLMaker._

// Prompt the user for a conference pin. This is really just
// a conference ID and any four digit pin will do.
def selectConference(call: ActiveCall) : VoiceResponse = {
VoiceResponse(
Say("Welcome. Please enter your four digit conference pin, followed by hash."),
Gather(4, onGathered = connectToConference _ )
)
}

// Validate the pin and connect the user to a conference.
def connectToConference(call: ActiveCall) : VoiceResponse = {

call.digits match {
case Some(confId) if confId.length != 4 =>
VoiceResponse(
Say("Pin should be four digits. Please enter four digits followed by hash."),
Gather(4, onGathered = connectToConference _)
)
case Some(confId) =>
VoiceResponse(
Say("Connecting you to conference " + confId.mkString(", ")),
ConnectToConference(confId,
onLeave = (call : DialOutcome) => println("Caller " + call + " left the conference"),
onWait = { pleaseWait }
)
)
case None => VoiceResponse(Say("Sorry, dunno how you got here"), Hangup)
}
}

// Say something to the user while waiting for the conference to begin.
// Demonstrates stateful callbacks.
def pleaseWait: () => VoiceResponse = {
var redirects = 0
def waitInfo() : VoiceResponse = {
redirects += 1
VoiceResponse(
Say("Please wait for others to join. You have waited " + redirects + " times", voice = Voice.Woman),
Redirect(waitInfo _)
)
}
waitInfo _
}

phone.incomingCallHandler = Some(selectConference _)

}

## Actor API
TBD
29 changes: 29 additions & 0 deletions core/src/main/scala/scwilio/op/operations.scala
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,35 @@ object DialOperation {
}
}

case class SendSms(from: Phonenumber, to: Phonenumber, body: String) extends TwilioOperation[SmsInfo] {
def request(conf: HttpConfig) = {
val params = Map(
"From" -> from.toStandardFormat,
"To" -> to.toStandardFormat,
"Body" -> body
)
conf.API_BASE / "SMS" / "Messages" << params
}

def parser = SendSms.parse
}

object SendSms {
import XmlPredef._

def parse(res: NodeSeq) = {
val msg = res \ "SMSMessage"
SmsInfo(
msg \ "Sid",
Phonenumber(msg \ "From"),
Phonenumber.parse(msg \ "To"),
msg \ "Uri"
)

}

}

/**
* Update the configuration for an incoming phone number.
*/
Expand Down
1 change: 1 addition & 0 deletions core/src/main/scala/scwilio/resources.scala
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package scwilio

case class CallInfo(callId: String, from: Phonenumber, to: Phonenumber, uri: String)
case class SmsInfo(smsId: String, from: Phonenumber, to: Phonenumber, uri: String)
case class ConferenceState(confId: String, state: String, participants: Seq[Participant])
case class Participant(callId: String, muted: Boolean)

Expand Down
5 changes: 5 additions & 0 deletions core/src/main/scala/scwilio/twilio.scala
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ object Twilio {
lazy val restClient = new RestClient(accountSid, authToken)
lazy val client = new TwilioClient(restClient)
def apply() = client
def apply(accountSid: String, authToken: String) = new TwilioClient(new RestClient(accountSid, authToken))
}

/**
Expand Down Expand Up @@ -73,6 +74,10 @@ class TwilioClient(private val restClient: RestClient) {
machineDetection: Boolean = false
) : CallInfo = restClient.execute(DialOperation(from, to, onConnect, onEnd, timeout, machineDetection))

def sendSms(from: Phonenumber,
to: Phonenumber,
body: String) : SmsInfo = restClient.execute(SendSms(from, to, body))

/**
* List all purchased incoming numbers.
*/
Expand Down
23 changes: 22 additions & 1 deletion core/src/test/scala/scwilio/op/OperationsSpec.scala
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,28 @@ object OperationsSpec extends Specification {
DialOperation.parse(res) must_== CallInfo("CA5161d32bc213aa14b729535850754a07", "+12222222222", "+1111111111", "/2010-04-01/Accounts/ACCOUNT_SID/Calls/CA5161d32bc213aa14b729535850754a07")
}
}

"SendSms" should {
"parse response correctly" in {
val res = <TwilioResponse>
<SMSMessage>
<Sid>SM90c6fc909d8504d45ecdb3a3d5b3556e</Sid>
<DateCreated>Wed, 18 Aug 2010 20:01:40 +0000</DateCreated>
<DateUpdated>Wed, 18 Aug 2010 20:01:40 +0000</DateUpdated>
<DateSent/>
<AccountSid>AC5ef872f6da5a21de157d80997a64bd33</AccountSid>
<To>+14159352345</To>
<From>+14158141829</From>
<Body>Jenny please?!</Body>
<Status>queued</Status>
<Direction>outbound-api</Direction>
<ApiVersion>2010-04-01</ApiVersion>
<Price/>
<Uri>/2010-04-01/Accounts/AC5ef872f6da5a21de157d80997a64bd33/SMS/Messages/SM90c6fc909d8504d45ecdb3a3d5b3556e</Uri>
</SMSMessage>
</TwilioResponse>
SendSms.parse(res) must_== SmsInfo("SM90c6fc909d8504d45ecdb3a3d5b3556e", "+14158141829", "+14159352345", "/2010-04-01/Accounts/AC5ef872f6da5a21de157d80997a64bd33/SMS/Messages/SM90c6fc909d8504d45ecdb3a3d5b3556e")
}
}
"TWGetConferenceState" should {
"parse response correctly" in {
val res = <TwilioResponse>
Expand Down
6 changes: 3 additions & 3 deletions examples/src/main/scala/demo/IncomingEventsDemo.scala
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,13 @@ import unfiltered.request._

object IncomingEventsDemo extends Application {

val tw = new TwilioClient(new RestClient(DemoConfig.accountSid, DemoConfig.authToken))
val client = new TwilioClient(new RestClient(DemoConfig.accountSid, DemoConfig.authToken))

val url = AbsoluteUrl("/incoming/voice")

// Dangerous operation. Commented out for safety.
tw.listIncomingNumbers().foreach { n =>
tw.updateIncomingNumberConfig(n.sid, IncomingNumberConfig(voiceUrl = url))
client.listIncomingNumbers().foreach { n =>
client.updateIncomingNumberConfig(n.sid, IncomingNumberConfig(voiceUrl = url))
println(n.number + " is now routed to " + url.get)
}

Expand Down
4 changes: 2 additions & 2 deletions examples/src/main/scala/demo/StatefulDemos.scala
Original file line number Diff line number Diff line change
Expand Up @@ -78,9 +78,9 @@ object StatefulDialDemo extends Application {
// Unfiltered HTTP callbacks.
import phone.URLMaker._

val tw = new TwilioClient(new RestClient(DemoConfig.accountSid, DemoConfig.authToken))
val client = new TwilioClient(new RestClient(DemoConfig.accountSid, DemoConfig.authToken))

tw.dial("+13477078794", "+4790055383",
client.dial(from = "+13477078794", to = "+4790055383",
onConnect = (call: ActiveCall) => call.answeredBy match {
case Some(Machine) =>
println("Argh! Machine! Hanging up.")
Expand Down

0 comments on commit 27c7906

Please sign in to comment.