Relay SDK for Go Lang
Getting Started
The Relay SDK for Go enables Go developers to connect and use SignalWire's Relay APIs within their own Go code. Our Relay SDK allows developers to build or add robust and innovative communication services to their applications.
The Relay SDK for Go is easy to use and only takes a few minute to setup and get running.
Source Code: signalwire/signalwire-golang
Support: SignalWire Community Slack Channel
Installation
Install the package using "go get".
go get github.com/signalwire/signalwire-golang
Minimum Requirements
The Go SDK requires Go 1.11
or greater installed on your system.
Using the SDK
The Go SDK can be used to get up and running with Relay quickly and easily. In order to use the Go client, you must get your project and token from your SignalWire dashboard.
There are a few ways to get started, depending on your needs: Relay.Consumer
, Relay.Task
, and Relay.Client
.
Relay Consumer
A Relay.Consumer
creates a long running process, allowing you to respond to incoming requests and events in realtime. Relay Consumers abstract all the setup of connecting to Relay and automatically dispatches workers to handle requests; so you can concentrate on writing your code without having to worry about multi-threading or blocking, everything just works. Think of Relay Consumers like a background worker system for all your calling and messaging needs.
Relay Consumers can scale easily, simply by running multiple instances of your Relay.Consumer
process. Each event will only be delivered to a single consumer, so as your volume increases, just scale up! This process works well whether you are using Docker Swarm, a Procfile on Heroku, your own webserver, and most other environments.
Setting up a new consumer is the easiest way to get up and running.
consumer := new(signalwire.Consumer)
// setup the Client
consumer.Setup(PProjectID, PTokenID, Contexts)
// register callback
consumer.Ready = MyReady
// start
if err := consumer.Run(); err != nil {
signalwire.Log.Error("Error occurred while starting Signalwire Consumer\n")
}
Learn more about Relay Consumers
Contexts
Relay uses Contexts as a simple way to separate events to specific consumers, allowing you to write consumers for specific types of calls or messages or scale them independently. A Context is simply a named string, that allows you to categorize requests. When creating outbound requests, or configuring phone numbers for inbound requests, you can specify the context; Relay will then deliver that call or event to Consumers that are configured to listen for that context.
For example, you could have a customer support phone number configured to send to Relay with the support
context, and a personal number configured with personal
context. Relay would deliver these events to any Consumer listening for those contexts. This gives you a lot of control in how messages are delivered to your Consumers, allowing you to write Consumer classes specific to the context, scale them independently, or separate traffic based on your own business rules.
API Reference
Relay.Consumer
A Relay Consumer is a Go object that runs Go routines in the background along side your application to handle calling and messaging events in realtime. Relay Consumers abstract all the setup of connecting to Relay and automatically dispatch workers to handle requests. Consumers will receive requests and delegate them to their own worker thread, allowing you to focus on your business logic without having to worry about multi-threading or blocking, everything just works. Think of Relay Consumers like a background worker system for all your calling and messaging needs.
Creating Consumers
A Relay Consumer is an object, customized by specifying contexts and event handlers to respond to incoming events.
A consumer has 2 required properties: project
, token
, and usually requires at least one contexts
for incoming events. Project and Token are used to authenticate your Consumer to your SignalWire account. Contexts are a list of contexts you want this Consumer to listen for. Learn more about Contexts.
Contexts = append(Contexts, PContext)
consumer := new(signalwire.Consumer)
// setup the Client
consumer.Setup(ProjectID, PTokenID, Contexts)
// register callback
consumer.OnIncomingCall = MyOnIncomingCall
log.Info("Wait incoming call..")
// start
if err := consumer.Run(); err != nil {
log.Errorf("Error occurred while starting Signalwire Consumer")
}
Initializing Consumers
You can optionally add an setup
method if you need to do any initialization work before processing messages. This is useful to do any one-off work that you wouldn't want to do for each and every event, such as setting up logging or connecting to a datastore.
Properties
client |
Relay.Client |
The underlying Relay client object. |
Event Handlers
Event handlers are where you will write most of your code. They are executed when your consumer receives a matching event for the contexts specified by your Consumer.
onReady
Executed once your Consumer is connected to Relay and the session has been established.
Available In:
func MyReady(consumer *signalwire.Consumer) {
resultDial := consumer.Client.Calling.DialPhone(fromNumber, toNumber)
if !resultDial.Successful {
if err := consumer.Stop(); err != nil {
log.Errorf("Error occurred while trying to stop Consumer")
}
return
}
}
func main() {
consumer := new(signalwire.Consumer)
// setup the Client
consumer.Setup(PProjectID, PTokenID, Contexts)
// register callback
consumer.Ready = MyReady
// start
if err := consumer.Run(); err != nil {
log.Errorf("Error occurred while starting Signalwire Consumer")
}
}
onIncomingCall
Executed when you receive an inbound call, passes in the inbound Call
object.
Available In:
// MyOnIncomingCall - gets executed when we receive an incoming call
func MyOnIncomingCall(consumer *signalwire.Consumer, call *signalwire.CallObj) {
resultAnswer := call.Answer()
if !resultAnswer.Successful {
if err := consumer.Stop(); err != nil {
log.Errorf("Error occurred while trying to stop Consumer")
}
return
}
log.Info("Playing audio on call..")
if _, err := call.PlayAudio("https://cdn.signalwire.com/default-music/welcome.mp3"); err != nil {
log.Errorf("Error occurred while trying to play audio")
}
if err := call.Hangup(); err != nil {
log.Errorf("Error occurred while trying to hangup call")
}
if err := consumer.Stop(); err != nil {
log.Errorf("Error occurred while trying to stop Consumer")
}
}
Cleaning Up on Exit
When a Relay Consumer shuts down, you have the opportunity to clean up any resources held by the consumer. For example, you could close any open files, network connections, or send a notification to your monitoring service.
Implement an Teardown
method in your consumer and it will be called during the shutdown procedure.
func MyTeardown(consumer *signalwire.Consumer) {
file.Close()
}
consumer.Teardown = MyTeardown
Running Consumers
if err := consumer.Run(); err != nil {
og.Errorf("Error occurred while starting Signalwire Consumer")
}
Shutting Down Consumers
if err := consumer.Stop(); err != nil {
log.Errorf("Error occurred while trying to stop Consumer")
}
Relay.Client
Relay.Client
is the basic connection to Relay, allowing you send commands to Relay and setup handlers for inbound events.
Constructor
Constructs a client object to interact with Relay.
Parameters
Project |
string | required | Project ID from your SignalWire Space |
Token |
string | required | Token from your SignalWire Space |
Host |
string | optional | The endpoint URI to send requests to. The SignalWire Space URL, should be a string similar {your-space}.signalwire.com . |
signalwireContexts |
string | optional | List of Contexts for inbound |
Examples
Create a Client to interact with the Relay API.
signalwireContexts := []string{DefaultContext}
client := signalwire.Client(PProjectID, PTokenID, "" /*host, empty for default*/, signalwireContexts)
Properties
calling |
Relay.Calling | Returns a Relay.Calling instance associated with the client. |
messaging |
Relay.Messaging | Returns a Relay.Messaging instance associated with the client. |
tasking |
Relay.Messaging | Returns a Relay.Tasking instance associated with the client. |
Methods
Connect()
Activates the connection to the Relay API. The connection to Relay does not happen automatically so that you can setup handlers to events that might occur before the connection is successfully established.
Available In:
Returns
error
Examples
signalwireContexts := []string{DefaultContext}
client := signalwire.Client(PProjectID, PTokenID, "" /*host, empty for default*/, signalwireContexts)
// register callback, anonymous function
client.OnReady = func (client *signalwire.ClientSession) {
signalwire.Log.Info("Client connected\n")
}
// start
err := client.Connect()
if err != nil {
signalwire.Log.Error("Error occurred while starting Signalwire Client\n")
}
Disconnect()
Disconnect the client from Relay.
Available In:
Returns
error
Examples
if err := client.Disconnect(); err != nil {
signalwire.Log.Error("Error occurred while trying to disconnect Client\n")
}
Events
All available events you can attach a listener on.
OnReady |
The session has been established and all other methods can now be used. |
Relay.Calling
This represents the API interface for the Calling Relay Service. This object is used to make requests related to managing end to end calls.
Methods
Dial
Make an outbound Call and waits until it has been answered or hung up.
Available In:
Parameters
newCall |
string | required | A Call Object created with NewCall() |
Returns
Examples
Make an outbound Call
resultDial := consumer.Client.Calling.Dial(newCall)
if !resultDial.Successful {
return
}
DialPhone
Make an outbound Phone Call and return when it has been answered,hung up or timed out.
Available In:
Parameters
from |
string | required | The party the call is coming from. Must be a SignalWire number or SIP endpoint that you own. |
to |
string | required | The party you are attempting to call. |
Returns
Examples
Make an outbound Call
resultDial := consumer.Client.Calling.DialPhone(fromNumber, toNumber)
if !resultDial.Successful {
return
}
playAction, err := resultDial.Call.PlayAudioAsync("https://cdn.signalwire.com/default-music/welcome.mp3")
if err != nil {
signalwire.Log.Error("Error occurred while trying to play audio\n")
}
NewCall
Create a new Call
object. The call has not started yet allowing you to attach event listeners on it.
Available In:
Parameters
See Relay.Calling.Dial
for the parameter list.
Returns
Call
- A new Relay.Calling.Call
object.
Examples
Create a new Call object.
newCall := consumer.Client.Calling.NewCall(fromNumber, toNumber)
resultDial := consumer.Client.Calling.Dial(newCall)
if !resultDial.Successful {
if err := consumer.Stop(); err != nil {
signalwire.Log.Error("Error occurred while trying to stop Consumer")
}
return
}
Relay.Calling.Call
All calls in SignalWire have a common generic interface, Call
. A Call
is a connection between SignalWire and another device.
Properties
Id |
string | The unique identifier of the call. |
Type |
string | The type of call. Only phone is currently supported. |
From |
string | The phone number that the call is coming from. |
To |
string | The phone number you are attempting to call. |
Timeout |
number | The seconds the call rings before being transferred to voicemail. |
State |
string | The current state of the call. See Relay.Calling.Call State Events for all the possible call states. |
PrevState |
string | The previous state of the call. |
Context |
string | The context the call belongs to. |
Peer |
Relay.Calling.Call |
The call your original call is connected to. |
Active |
boolean | Whether the call is active. |
Ended |
boolean | Whether the call has ended. |
Answered |
boolean | Whether the call has been answered. |
Failed |
boolean | Whether the call has failed. |
Busy |
boolean | Whether the call was busy. |
Methods
Answer
Answer an inbound call.
Available In:
Parameters
None
Returns
Examples
Answer an inbound call and check if it was successful.
resultAnswer := call.Answer()
if !resultAnswer.Successful {
if err := consumer.Stop(); err != nil {
log.Errorf("Error occurred while trying to stop Consumer")
return
}
}
Detect
Start a detector on the call and waits until it has finished or failed.
The Detect
method is a generic method for all types of detecting, see DetectAnsweringMachine
, DetectDigit
or DetectFax
for more specific usage.
Available In:
DetectMachineAsync, DetectFaxAsync, DetectDigitAsync
Asynchronous version of detect
. It does not wait the detector ends but returns a Relay.Calling.DetectAction
you can interact with.
Available In:
Parameters
See detect
for the parameter list.
Returns
pointer to DetectAction, error
Examples
Detect digits using default parameters.
var det signalwire.DetectDigitParams
detectDigitAction, err := resultDial.Call.DetectDigitAsync(&det)
Detect digits using filter.
var det signalwire.DetectDigitParams
det.Digits = "789"
detectDigitAction, err := resultDial.Call.DetectDigitAsync(&det)
DetectMachine
Parameters
DetectMachineParams |
array | optional | Struct with the following properties: |
InitialTimeout |
number | optional | Number of seconds to wait for initial voice before giving up. Defaults to 4.5. |
EndSilenceTimeout |
number | optional | Number of seconds to wait for voice to finish. Defaults to 1.0. |
MachineVoiceThreshold |
number | optional | How many seconds of voice to decide is a machine. Defaults to 1.25. |
MachineWordsThreshold |
number | optional | How many words to count to decide is a machine. Defaults to 6. |
Returns
DetectResult
Examples
Perform an AMD and wait until the machine is ready.
// MyOnDetectUpdate ran on Detector update
func MyOnDetectUpdate(det interface{}) {
signalwire.Log.Info("Detect update.\n")
detectAction, ok := det.(*signalwire.DetectMachineAction)
if ok {
signalwire.Log.Info("Machine Detect Action.\n")
if detectAction.GetDetectorEvent() == signalwire.DetectMachineReady {
signalwire.Log.Info("Machine READY.\n")
detectAction.Stop()
}
}
}
var det signalwire.DetectMachineParams
detectMachineAction, err := resultDial.Call.DetectMachineAsync(&det)
if err != nil {
signalwire.Log.Error("Error occurred while trying to start answering machine detector")
}
DetectMachineAsync
Asynchronous version of DetectAnsweringMachine
. It does not wait the detector ends but returns a Relay.Calling.DetectAction
you can interact with.
Available In:
Parameters
See DetectAnsweringMachine
for the parameter list.
Returns
pointer to DetectAction, error
Examples
Perform an asynchronous AMD on the call. Then stop the action if not completed yet.
detectMachineAction, err := resultDial.Call.DetectMachineAsync(&det)
if err != nil {
signalwire.Log.Error("Error occurred while trying to start answering machine detector")
}
time.Sleep(10 * time.Second)
if !detectMachineAction.GetCompleted() {
detectMachineAction.Stop()
}
DetectDigit
Available In:
Parameters
DetectDigitParams |
array | optional | Struct with the following properties: |
timeout |
number | optional | Number of seconds to run the detector. Defaults to 30.0. |
digits |
string | optional | The digits to detect. Defaults to "0123456789#*". |
Returns
DetectResult
Examples
Detect digits and then write a log with the result.
// MyOnDetectUpdate ran on Detector update
func MyOnDetectUpdate(det interface{}) {
// type assertion to infer the type of detector that just called our callback.
detectAction, ok := det.(*signalwire.DetectDigitAction)
if ok {
signalwire.Log.Info("Detected DTMF: %s\n", detectAction.GetDetectorEvent().String())
}
}
func MyReady(consumer *signalwire.Consumer) {
[...]
resultDial.Call.OnDetectUpdate = MyOnDetectUpdate
var det signalwire.DetectDigitParams
detectDigitAction, err := resultDial.Call.DetectDigitAsync(&det)
if err != nil {
signalwire.Log.Error("Error occurred while trying to start digit detector")
}
}
DetectDigitAsync
Asynchronous version of detectDigit
. It does not wait the detector ends but returns a Relay.Calling.DetectAction
you can interact with.
Available In:
Parameters
See detectDigit
for the parameter list.
Returns
pointer to DetectAction, error
Examples
Detect only
1-3
digits asynchronously.
resultDial.Call.OnDetectUpdate = MyOnDetectUpdate
var det signalwire.DetectDigitParams
det.Digits = "123"
detectDigitAction, err := resultDial.Call.DetectDigitAsync(&det)
if err != nil {
signalwire.Log.Error("Error occurred while trying to start digit detector")
}
DetectFax
This is a helper function that refines the use of detect
. This simplifies detecting a fax.
Available In:
Parameters
DetectFaxParams |
array | optional | Struct with the following properties: |
timeout |
number | optional | Number of seconds to run the detector. Defaults to 30.0. |
tone |
string | optional | The fax tone to detect: CED or CNG .Defaults to "CED". |
Returns
DetectResult
Examples
Detect fax on the current call.
var det signalwire.DetectFaxParams
det.Tone = "CED"
detectFaxAction, err := resultDial.Call.DetectFax(&det)
if err != nil {
signalwire.Log.Error("Error occurred while trying to start fax detector")
}
DetectFaxAsync
Asynchronous version of DetectFax
. It does not wait the detector ends but returns a Relay.Calling.DetectAction
you can interact with.
Available In:
Parameters
See detectFax
for the parameter list.
Returns
pointer to DetectAction, error
Examples
Detect fax on the current call. Stop the action immediately.
var det signalwire.DetectFaxParams
det.Tone = "CED"
detectFaxAction, err := resultDial.Call.DetectFaxAsync(&det)
if err != nil {
signalwire.Log.Error("Error occurred while trying to start fax detector")
}
Dial
This will start a call that was created with NewCall
and waits until the Call has been answered or hung up.
Available In:
Parameters
None
Returns
ResultDial
Examples
newCall := consumer.Client.Calling.NewCall(fromNumber, toNumber)
resultDial := consumer.Client.Calling.Dial(newCall)
if !resultDial.Successful {
if err := consumer.Stop(); err != nil {
signalwire.Log.Error("Error occurred while trying to stop Consumer")
}
return
}
ReceiveFax
Prepare the call to receive an inbound fax. It waits until the fax has been received or failed.
Available In:
Parameters
None
Returns
FaxResult
Examples
Receiving a fax on the call and print logs for URL and number of received pages.
faxResult, err := call.ReceiveFax()
if err != nil {
log.Errorf("Error occurred while trying to receive fax")
return
}
log.Infof("Download Document from %s\n Pages #%d\n", faxResult.Document, faxResult.Pages
ReceiveFaxAsync
Asynchronous version of ReceiveFax
. It does not wait the fax to be received but returns Relay.Calling.FaxAction
you can interact with.
Available In:
Parameters
None
Returns
pointer to FaxAction, error
Examples
Trying to receive a fax and then stop it.
faxAction, err := call.ReceiveFaxAsync()
if err != nil {
signalwire.Log.Errorf("Error occurred while trying to receive fax")
return
}
SendFax
Send a fax through the call. It waits until the fax has been sent or failed.
Available In:
Parameters
$document |
string | required | Http(s) URL to the document to send. PDF format only. |
$identity |
string | optional | Identity to display on receiving fax. Defaults to SignalWire DID. |
$header |
string | optional | Custom string to add to header of each fax page. Set to empty string to disable sending any header. |
Returns
FaxResult, error
Examples
Sending a fax on the call
faxAction, err := resultDial.Call.SendFax("https://example.com/fax.pdf", "", "")
if err != nil {
signalwire.Log.Error("Error occurred while trying to send fax\n")
}
SendFaxAsync
Asynchronous version of SendFax
. It does not wait the fax to be sent but returns a Relay.Calling.FaxAction
you can interact with.
Available In:
Parameters
See SendFax
for the parameter list.
Returns
pointer to FaxAction, error
Examples
Trying to send a fax and then stop it.
faxAction, err := resultDial.Call.SendFaxAsync("https://example.com/fax.pdf", "", "")
if err != nil {
signalwire.Log.Error("Error occurred while trying to send fax\n")
}
// do something here, the for loop can be placed in a go routine
for {
time.Sleep(200 * time.Millisecond)
if faxAction.GetCompleted() {
break
}
}
signalwire.Log.Info("Pages #%d\n", faxAction.GetPages())
Hangup
Hangup the call.
Available In:
Parameters
None
Returns
ResultHangup
Examples
Hangup the current call and check if it was successful.
if err := resultDial.Call.Hangup(); err != nil {
signalwire.Log.Error("Error occurred while trying to hangup call. Err: %v\n", err)
}
Play
Play one or multiple media in a call and wait until the playing has ended.
The Play
method is a generic method for all types of playing, see PlayAudio
, PlaySilence
or PlayTTS
for more specific usage.
Available In:
Parameters
[MaxPlay]PlayGenericParams |
array | required | Array of PlayGenericParams Struct. The type PlayGenericParams contains only a var interface{} and the SDK code expects types PlayAudio or PlayTTS or PlaySilence to be assigned to it. See example. |
- To play an audio file use the PlayAudio type to set the URL for the audio file:
URL |
string | required | Http(s) URL to audio resource to play. |
- To play text to speech use the PlayTTS type to set the TTS params:
Text |
string | required | TTS to play. |
Language |
string | optional | Default to en-US . |
Gender |
string | optional | male or female . Default to female . |
- To play silence use the PlaySilence type to set the Duration:
Duration |
number | required | Seconds of silence to play. |
Returns
Array of PlayResult ([]PlayResult)
Examples
Play multiple media elements in the call.
audio := new(signalwire.PlayAudio)
audio.URL = "https://www.phatdrumloops.com/audio/wav/space_funk1.wav"
tts := new(signalwire.PlayTTS)
tts.Text = "Hello from Signalwire!"
tts.Language = "en-US"
tts.Gender = "male"
silence := new(signalwire.PlaySilence)
silence.Duration = 3 /*seconds*/
var playGeneric [signalwire.MaxPlay]signalwire.PlayGenericParams
playGeneric[0].SpecificParams = audio
playGeneric[1].SpecificParams = silence
playGeneric[2].SpecificParams = tts
// will play all three in the order defined in the "playGeneric" array.
// It will stop when all three Play commands end or upon error.
if _, err := resultDial.Call.Play(playGeneric); err != nil {
signalwire.Log.Error("Error occurred while trying to play audio\n")
}
PlayAsync
Asynchronous version of Play
. It does not wait the playing to complete but returns a Relay.Calling.PlayAction
you can interact with. This will run all Play actions in parallel.
Available In:
Parameters
See play
for the parameter list.
Returns
Array of pointers to PlayAction
Examples
Play multiple media elements in the call and then stop it.
audio := new(signalwire.PlayAudio)
audio.URL = "https://www.phatdrumloops.com/audio/wav/space_funk1.wav"
tts := new(signalwire.PlayTTS)
tts.Text = "Hello from Signalwire!"
tts.Language = "en-US"
tts.Gender = "female"
silence := new(signalwire.PlaySilence)
silence.Duration = 3
// MaxPlay is 10
var playGeneric [signalwire.MaxPlay]signalwire.PlayGenericParams
playGeneric[0].SpecificParams = audio
playGeneric[1].SpecificParams = silence
playGeneric[2].SpecificParams = tts
if _, err := resultDial.Call.PlayAsync(playGeneric); err != nil {
signalwire.Log.Error("Error occurred while trying to play audio\n")
}
PlayAudio
This is a helper function that refines the use of Play
. This simplifies playing an audio file and returns a single action.
Available In:
Parameters
URL |
string | required | Http(s) URL to audio resource to play. |
Returns
pointer to PlayResult, error
Examples
Play an Mp3 file.
PlayAction, err := resultDial.Call.PlayAudio("https://www.phatdrumloops.com/audio/wav/space_funk1.wav")
if err != nil {
signalwire.Log.Error("Error occurred while trying to Play audio\n")
}
PlayAudioAsync
Asynchronous version of PlayAudio
. It does not wait the playing to completes but returns a Relay.Calling.PlayAction
you can interact with.
Available In:
Parameters
See playAudio
for the parameter list.
Returns
pointer to PlayAction, error
Examples
Play an Mp3 file and stop it after 5 seconds.
playAction, err := resultDial.Call.PlayAudioAsync("https://cdn.signalwire.com/default-music/welcome.mp3")
if err != nil {
log.Errorf("Error occurred while trying to play audio")
}
time.Sleep(5 * time.Second)
playAction.Stop()
PlaySilence
This is a helper function that refines the use of Play
. This simplifies playing silence.
Available In:
Parameters
duration |
number | required | Seconds of silence to play. |
Returns
pointer to PlayResult, error
Examples
Play silence for 3 seconds.
if _, err := resultDial.Call.PlaySilence(3); err != nil {
log.Errorf("Error occurred while trying to play silence. Err: %v\n", err)
}
PlaySilenceAsync
Asynchronous version of PlaySilence
. It does not wait the playing to completes but returns a Relay.Calling.PlayAction
you can interact with.
Available In:
Parameters
See playSilence
for the parameter list.
Returns
pointer to PlayAction, error
Examples
Play silence for 3 seconds (async).
if _, err := resultDial.Call.PlaySilenceAsync(3); err != nil {
log.Errorf("Error occurred while trying to play silence. Err: %v\n", err)
}
PlayTTS
This is a helper function that refines the use of Play
. This simplifies playing TTS.
Available In:
Parameters
Text |
string | required | TTS to play. |
Language |
string | optional | Default to en-US . |
Gender |
string | optional | male or female . Default to female . |
Returns
pointer to PlayResult, error
Examples
Play TTS.
_, err := resultDial.Call.PlayTTS("Welcome to Signalwire !", "en-US", "female")
if err != nil {
signalwire.Log.Error("Error occurred while trying to Play audio\n")
}
PlayTTSAsync
Asynchronous version of PlayTTS
. It does not wait the playing to completes but returns a Relay.Calling.PlayAction
you can interact with.
Available In:
Parameters
See playTTS
for the parameter list.
Returns
pointer to PlayAction, error
Examples
Play TTS and stop it after 1 second.
playAction, err := resultDial.Call.PlayTTSAsync("Welcome to Signalwire !", "en-US", "female")
if err != nil {
signalwire.Log.Error("Error occurred while trying to Play audio\n")
}
time.Sleep(1 * time.Second)
playAction.Stop()
Record
Start recording the call and waits until the recording ends or fails.
Available In:
Parameters
RecordParams |
array | optional | Struct with the following properties: |
Beep |
boolean | optional | Default to false . |
Stereo |
boolean | optional | Default to false . |
Format |
string | optional | mp3 or wav . Default mp3 . |
Direction |
string | optional | listen , speak or both . Default to speak . |
InitialTimeout |
number | optional | How long to wait in seconds until something is heard in the recording. Disable with 0 . Default 5.0 . |
EndSilenceTimeout |
number | optional | How long to wait in seconds until caller has stopped speaking. Disable with 0 . Default 1.0 . |
Terminators |
string | optional | DTMF digits that will end the recording. Default #* . |
Returns
pointer to RecordResult, error
Examples
Start recording audio in the call for both direction in stereo mode, if successful, grab
url
,duration
andsize
from the RecordResult object.
var rec signalwire.RecordParams
rec.Beep = true
rec.Format = "wav"
rec.Stereo = true
rec.Direction = signalwire.RecordDirectionBoth.String()
rec.InitialTimeout = 10
rec.EndSilenceTimeout = 3
rec.Terminators = "#*"
// blocking
recordResult, err := resultDial.Call.RecordAudio(&rec)
if err != nil {
signalwire.Log.Error("Error occurred while trying to record audio\n")
}
// recording stops on silence
signalwire.Log.Info("Recording is at: %s. Duration is:%d Size is:%d \n", recordResult.URL, recordResult.Duration, recordResult.Size)
RecordAsync
Asynchronous version of record
. It does not wait the end of recording but returns a Relay.Calling.RecordAction
you can interact with.
Available In:
Parameters
See record
for the parameter list.
Returns
pointer to RecordAction, error
Examples
Start recording audio in the call for both direction in stereo mode and then stop it using the RecordAction object.
var rec signalwire.RecordParams
rec.Beep = true
rec.Format = "wav"
rec.Stereo = true
rec.Direction = signalwire.RecordDirectionBoth.String()
rec.InitialTimeout = 10
rec.EndSilenceTimeout = 3
rec.Terminators = "#*"
recordAction, err := resultDial.Call.RecordAudioAsync(&rec)
if err != nil {
signalwire.Log.Error("Error occurred while trying to record audio\n")
}
time.Sleep(3 * time.Second)
signalwire.Log.Info("Stopping recording...\n")
recordAction.Stop()
for {
time.Sleep(1 * time.Second)
if recordAction.GetCompleted() {
break
}
}
// for Actions we use Getters, for Results that we know that are delivered when a blocking action ends
// we can just read the needed vars directly from the Result struct.
signalwire.Log.Info("Recording is at: %s. Duration is:%d Size is:%d \n", recordAction.GetURL(), recordAction.GetDuration(), recordAction.GetSize())
Prompt
Play one or more media while collecting user's input from the call at the same time, such as digits
and speech
.
It waits until the collection succeed or timeout is reached. This is a general method for all types of playing, see PromptAudio
or PromptTTS
for more specific usage.
Available In:
Parameters
| Media
| array | required | List of media elements to play. See play
for the array structure. |
| Collect
| Relay.Calling.CallCollect
| required | The configuration for input collection. |
| Volume
| double? | optional | Controls the volume, between -40dB and +40dB where 0 is unchanged. Default is 0
. |
Returns
Relay.Calling.PromptResult
- The result object to interact with.
Examples
Ask user to enter their PIN and collect the digits.
resultDial.Call.OnPrompt = func(promptaction *signalwire.PromptAction) {
// we could do something here and this gets called when the Prompt Action finishes.
}
playAudioParams := signalwire.PlayAudioParams{
URL: "https://www.pacdv.com/sounds/voices/can-you-keep-a-secret.wav",
}
playTTSParams := signalwire.PlayTTSParams{
Text: "Hello from Signalwire!",
}
playRingtoneParams := signalwire.PlayRingtoneParams{
Duration: 5,
Name: "us",
}
play := []signalwire.PlayStruct{{
Type: "audio",
Params: playAudioParams,
}, {
Type: "tts",
Params: playTTSParams,
}, {
Type: "ringtone",
Params: playRingtoneParams,
}}
collectDigits := new(signalwire.CollectDigits)
collectDigits.Max = 3
collectSpeech := new(signalwire.CollectSpeech)
collectSpeech.EndSilenceTimeout = 1
collectSpeech.SpeechTimeout = 10
collectSpeech.Hints = []string{"top", "well"}
collect := signalwire.CollectStruct{
Speech: collectSpeech,
Digits: collectDigits,
}
promptAction, err := resultDial.Call.PromptAsync(&play, &collect)
if err != nil {
signalwire.Log.Error("Error occurred while trying to start Prompt Action\n")
if err := consumer.Stop(); err != nil {
signalwire.Log.Error("Error occurred while trying to stop Consumer. Err: %v\n", err)
}
return
}
// do something here
time.Sleep(15 * time.Second)
if !promptAction.GetCompleted() {
promptAction.Stop()
}
for {
time.Sleep(1 * time.Second)
if promptAction.GetCompleted() {
break
}
}
myResult := promptAction.GetResultType()
switch myResult {
case signalwire.CollectResultSpeech:
signalwire.Log.Info("Speech text: \"%s\" Confidence: %f\n", promptAction.GetCollectResult(), promptAction.GetConfidence())
case signalwire.CollectResultDigit:
signalwire.Log.Info("Digits: \"%s\" Terminator: %s\n", promptAction.GetCollectResult(), promptAction.GetTerminator())
default:
signalwire.Log.Info("Result was: %s\n", myResult.String())
}
PromptAsync
Asynchronous version of prompt
. It does not wait the collection to completes but returns a Relay.Calling.PromptAction
you can interact with.
Available In:
Parameters
See Prompt
for the parameter list.
Returns
pointer to PromptAction, error
Examples
Ask user to enter their PIN and collect the digits.
Tap
Intercept call media and stream it to the specify endpoint. It waits until the end of the call. Signalwire will send RTP or Websocket audio to the endpoint.
Available In:
Parameters
AudioDirection |
string | required | listen what the caller hears, speak what the caller says or both . |
Tap |
struct | required | Struct with the following properties: |
Type |
string | required | Protocols to use: RTP , WS . Use signalwire.TapRTP.String() or signalwire.TapWS.String() |
Ptime |
number | optional | Packetization time in ms. It will be the same as the tapped media if not set, typically 20 ms. |
Codec |
string | optional | Codec to use. It will be the same as the tapped media if not set. Codecs can be PCMU , PCMA and OPUS . Defaults to PCMU . |
- To
tap
through RTP:
Addr |
string | required | RTP IP v4 address. |
Port |
number | required | RTP port. |
- To
tap
through WS (Websocket audio -ws
orwss
URI):
URI |
string | required | ws or wss URI . To be set with Type signalwire.TapWS.String() |
Returns
TapResult
Examples
Tapping audio from the call, if successful, print both source and destination devices from the
TapResult
object.
TapAsync
Asynchronous version of tap
. It does not wait the end of tapping but returns a Relay.Calling.TapAction
you can interact with.
Available In:
Parameters
See tap
for the parameter list.
Returns
pointer to TapAction, error
Examples
Tapping audio from the call and then stop it using the
TapAction
object.
var tapdevice signalwire.TapDevice
if taptype == "rtp" {
tapdevice.Type = signalwire.TapRTP.String()
tapdevice.Params.Addr = "X.X.X.X"
tapdevice.Params.Port = 1234
tapdevice.Params.Codec = "PCMU"
} else if taptype == "ws" {
tapdevice.Type = signalwire.TapWS.String()
tapdevice.Params.URI = "wss://X.X.X.X:1234"
}
tapAction, err := resultDial.Call.TapAudioAsync(signalwire.TapDirectionListen, &tapdevice)
if err != nil {
signalwire.Log.Fatal("Error occurred while trying to tap audio: %v\n", err)
}
time.Sleep(10 * time.Second)
tapAction.Stop()
signalwire.Log.Info("SourceDevice: %v\n", tapAction.GetSourceDevice()) // comes from the Signalwire platform
signalwire.Log.Info("DestinationDevice: %v\n", tapAction.GetDestinationDevice()) // the device passed above
SendDigits
This method sends DTMF digits to the other party on the call. Allowed digits are 1234567890*#ABCD
and wW
for short and long waits. If any invalid characters are present, the entire operation is rejected.
Available In:
Parameters
$digits |
string | required | String of DTMF digits to send. |
Returns
SendDigitsResult
Examples
Send some digits.
_, err := resultDial.Call.SendDigits("777777890*#")
if err != nil {
signalwire.Log.Error("Error occurred while trying send digits: %v\n", err)
}
SendDigitsAsync
Asynchronous version of sendDigits
. It does not wait for the sending event to complete, and immediately returns a Relay.Calling.SendDigitsAction
object you can interact with.
Available In:
Parameters
See sendDigits
for the parameter list.
Returns
a pointer to SendDigitsAction, error
Examples
Send some digits and then check if the operation is completed using the SendDigitsAction object.
/* use an anonymous function as CB */
resultDial.Call.OnSendDigitsFinished = func(a *signalwire.SendDigitsAction) {
signalwire.Log.Info("SendDigits finished with successful result: [%v]\n", a.GetSuccessful())
}
sendDigitsAction, err := resultDial.Call.SendDigitsAsync("1234567890*#")
if err != nil {
signalwire.Log.Error("Error occurred while trying to send digits\n")
}
WaitFor
Wait for specific events on the Call or returns false
if the Call ends without getting them.
Available In:
Parameters
event |
string or string[] | required | One Relay.Calling.Call State Events |
Returns
Examples
Wait for ending event.
call.WaitFor(Ending, 3) // wait 3 seconds
WaitForAnswered
This is a helper function that refines the use of waitFor
. This simplifies waiting for the answered state.
Available In:
Parameters
None
Returns
Examples
Wait for the answered event.
call.WaitForAnswered(20) // wait 20 seconds
WaitForEnded
This is a helper function that refines the use of waitFor
. This simplifies waiting for the ended state.
Available In:
Parameters
None
Returns
Examples
Wait for the ended event.
call.WaitForEnded(3) // wait 3 seconds
WaitForEnding
This is a helper function that refines the use of waitFor
. This simplifies waiting for the ending state.
Available In:
Parameters
None
Returns
Examples
Wait for the ending event.
call.WaitForEnding(3) // wait 3 seconds
WaitForRinging
This is a helper function that refines the use of waitFor
. This simplifies waiting for the ringing state.
Available In:
Parameters
None
Returns
Examples
Wait for ending or ended events.
call.WaitForRinging(3) // wait 3 seconds
Callbacks
All these callbacks can be used to track the calls lifecycle and instruct SignalWire on what to do for each different state.
State Callbacks
To track the state of a call.
OnStateChange |
Event dispatched when Call state changes. |
OnRinging |
The call has been created in Relay. |
OnRinging |
The call is ringing and has not yet been answered. |
OnAnswered |
The call has been picked up. |
OnEnding |
The call is hanging up. |
OnEnded |
The call has ended. |
Play Callbacks
To track a playback state.
OnPlayStateChange |
Event dispatched when the state of a playing changes. |
OnPlayPlaying |
A playback is playing on the call. |
OnPlayError |
A playback failed to start. |
OnPlayFinished |
The playback has ended. |
OnPlayPaused |
The playback is paused. |
Record Callbacks
To track a recording state.
OnRecordStateChange |
Event dispatched when the state of a recording changes. |
OnRecordRecording |
The call is being recorded. |
OnRecordNoInput |
The recording failed due to no input. |
OnRecordFinished |
The recording has finished. |
Fax Callbacks
To track a fax state.
OnFaxError |
Faxing failed. |
OnFaxFinished |
Faxing has finished. |
OnFaxPage |
A fax page has been sent or received. |
Detect Callbacks
To track a detector state.
OnDetectError |
The detector has failed. |
OnDetectFinished |
The detector has finished. |
OnDetectUpdate |
There is a notification from the detector (eg: a new DTMF tone). |
Connect Events
To track the connect state of a call.
OnConnectStateChange |
The connect state is changing, generalized event for the following events. |
OnConnectFailed |
The last call connection attempt failed. |
OnConnectConnecting |
Currently calling the phone number(s) to connect. |
OnConnectConnected |
The calls are being connected together. |
OnConnectDisconnected |
The call was either never connected or the last call connection completed. |
Send Digits Events
To receive a message when the digits are finished sending.
OnSendDigitsStateChange |
The send digits state is changing, generalized event for the following events. |
OnSendDigitsFinished |
The digits have finished sending. |
Tap Events
To track an active tap.
OnTapStateChange |
The tap state is changing, generalized event for the following events. |
OnTapTapping |
The call is being tapped. |
OnTapFinished |
The tapping has finished. |
Prompt Events
To track a prompt state.
OnPrompt |
The prompt action on the call has ended. |
Relay.Calling.RecordAction
This object returned from recordAsync
method that represents a recording that is currently active on a call.
Methods
GetResult
Returns the final result of the recording.
Available In:
Parameters
None
Returns
Relay.Calling.RecordResult
- Final result of the recording.
Examples
Start recording in stereo mode and grab the result when it's completed.
var rec signalwire.RecordParams
rec.Beep = true
rec.Format = "wav"
rec.Stereo = true
rec.Direction = signalwire.RecordDirectionBoth.String()
rec.InitialTimeout = 10
rec.EndSilenceTimeout = 3
rec.Terminators = "#*"
// use anonymous function as callback
resultDial.Call.OnRecordFinished = func(recordAction *signalwire.RecordAction) {
signalwire.Log.Info("Recording is at: %s\n", recordAction.Result.URL)
signalwire.Log.Info("Recording Duration: %d\n", recordAction.Result.Duration)
signalwire.Log.Info("Recording File Size: %d\n", recordAction.Result.Size)
}
recordAction, err := resultDial.Call.RecordAudioAsync(&rec)
if err != nil {
signalwire.Log.Error("Error occurred while trying to record audio\n")
}
// the recording can stop by itself when detected silence or it can be stopped via command
[do something here]
recordAction.Stop()
GetState
Return the current state of recording.
Available In:
Parameters
None
Returns
string
- Current state of recording.
GetCompleted
Return true
if the recording has finished, false
otherwise.
Available In:
Parameters
None
Returns
Boolean
- True/False accordingly to the state.
Examples
Start recording in stereo mode and check if it has finished.
var rec signalwire.RecordParams
rec.Beep = true
rec.Format = "wav"
rec.Stereo = true
rec.Direction = signalwire.RecordDirectionBoth.String()
rec.InitialTimeout = 10
rec.EndSilenceTimeout = 3
rec.Terminators = "#*"
recordAction, err := resultDial.Call.RecordAudioAsync(&rec)
if err != nil {
signalwire.Log.Error("Error occurred while trying to record audio\n")
}
// we sleep but you can do something else in the main thread
time.Sleep(3 * time.Second)
signalwire.Log.Info("Stopping recording...\n")
recordAction.Stop()
// this can be run in a go routine
for {
time.Sleep(1 * time.Second)
if recordAction.GetCompleted() {
break
}
}
GetControlID
Return the UUID to identify the action.
Available In:
Parameters
None
Returns
string
- UUID to identify the action.
Examples
Start recording and print the controlId.
recordAction, err := resultDial.Call.RecordAudioAsync(&rec)
if err != nil {
signalwire.Log.Error("Error occurred while trying to record audio\n")
}
Signalwire.Log.Info("Recording ControlID: %s\n", recordAction.GetControlID())
Stop
Stop the action immediately.
Available In:
Parameters
None
Returns
Examples
Start recording with default params and stop it upon condition
var rec signalwire.RecordParams
recordAction, err := resultDial.Call.RecordAudioAsync(&rec)
if err != nil {
signalwire.Log.Error("Error occurred while trying to record audio\n")
}
[do something here]
if (cond) {
recordAction.Stop()
}
Relay.Calling.RecordResult
This object returned from record
method that represents the final result of a recording.
Methods
getDuration
Returns the duration of the recording in seconds.
Available In:
Parameters
None
Returns
number
- Duration of the recording in seconds.
Examples
Start recording and use the duration.
GetEvent
Returns the last Relay Event arrived for this operation.
Available In:
Parameters
None
Returns
Relay.Event
- Last Relay Event.
Examples
Start recording in stereo mode and grab the result when it's completed.
GetSize
Returns the size of the recording file.
Available In:
Parameters
None
Returns
number
- Size of the recording file.
Examples
Start recording and use the size of the file.
GetUrl
Returns the HTTPS URL to the recording file.
Available In:
Parameters
None
Returns
string
- HTTPS URL to the file.
Examples
Start recording and use the URL.
GetSuccessful
Return true
if the recording succeeded, false
otherwise.
Available In:
Parameters
None
Returns
boolean
- True/False accordingly to the state.
Examples
Start the recording and then check if it has ended successfully.
Relay.Calling.PlayMediaAction
This object represents a media action
that is currently active on a call.
Properties
call |
Relay.Calling.Call |
This is the call the action is occurring on. |
Methods
stop()
Stop the action immediately.
Available In:
Parameters
None
Returns
Examples
Play an audio file and stop it if
Agent
is not available.
Relay.Calling.PlayAudioAction
This object represents an audio action
that is currently active on a call.
Properties
call |
Relay.Calling.Call |
This is the call the action is occurring on. |
Methods
Stop()
Stop the action immediately.
Available In:
Examples
Play an audio file and stop it upon condition.
playAction, err := resultDial.Call.PlayAudioAsync("https://cdn.signalwire.com/default-music/welcome.mp3")
if err != nil {
log.Errorf("Error occurred while trying to play audio")
}
if condition {
playAction.Stop()
}
Relay.Calling.PlayTTSAction
This object represents a TTS action
that is currently active on a call.
Properties
call |
Relay.Calling.Call |
This is the call the action is occurring on. |
Methods
stop()
Stop the action immediately.
Available In:
Parameters
None
Returns
Examples
Play TTS in the call and stop it if
$agent
is not available.
Relay.Calling.PlaySilenceAction
This object represents a silence action
that is currently active on a call.
Properties
call |
Relay.Calling.Call |
This is the call the action is occurring on. |
Methods
Stop()
Stop the action immediately.
Available In:
Parameters
None
Returns
StopResult
Examples
Play 10 seconds of silence and then stop.
playSilence, err := resultDial.Call.PlaySilenceAsync(10);
if err != nil {
signalwire.Log.Error("Error occurred while trying to play silence. Err: %v\n", err)
}
playSilence.Stop()
Relay.Calling.PlayVolumeResult
This object is returned by volume
method and represents the final result of a volume control operation.
Properties
successful |
boolean | Whether the playing volume has been changed successfully. |
Relay.Calling.DialResult
This object returned from Calling dial
and Call dial
methods.
Methods
GetSuccessful
Return true
if the call was picked up by the remote party, false
otherwise.
Available In:
Parameters
None
Returns
boolean
- Whether the call has been answered.
Examples
Start an outbound Call and then check if the
dial
has completed successfully.
newCall := consumer.Client.Calling.NewCall(fromNumber, toNumber)
resultDial := consumer.Client.Calling.Dial(newCall)
if !resultDial.GetSuccessful() {
if err := consumer.Stop(); err != nil {
signalwire.Log.Error("Error occurred while trying to stop Consumer")
}
return
}
Relay.Calling.AnswerResult
This object returned from the answer
method.
Methods
resultAnswer := call.Answer()
if !resultAnswer.Successful {
if err := consumer.Stop(); err != nil {
log.Errorf("Error occurred while trying to stop Consumer")
}
return
}
Relay.Calling.HangupResult
This object returned from hangup
method.
Methods
hangupResult, err := call.Hangup()
if err != nil {
signalwire.Log.Error("Error occurred while trying to hangup call\n")
}
if hangupResult.GetSuccessful() {
signalwire.Log.Info("Call disconnect result: %s\n", hangupResult.GetReason().String())
}
Relay.Calling.DetectAction
This object returned from one of asynchronous detect methods that represents a running detector on the call.
Methods
GetResult
Returns the final detector result.
Available In:
Parameters
None
Returns
DetectResult
Relay.Calling.DetectResult
- Final detector result.
Examples
Trying detecting DTMF and grab the result when it's completed.
var det signalwire.DetectMachineParams
detectMachineAction, err := resultDial.Call.DetectMachineAsync(&det)
if err != nil {
signalwire.Log.Error("Error occurred while trying to start answering machine detector")
}
time.Sleep(15 * time.Second)
if !detectMachineAction.GetCompleted() {
detectMachineAction.Stop()
}
for {
time.Sleep(1 * time.Second)
if detectMachineAction.GetCompleted() {
signalwire.Log.Info("Machine Detection Successful(%v)\n", detectMachineAction.GetSuccessful())
break
}
signalwire.Log.Info("Last Machine event: %s Result: %v\n", detectMachineAction.GetDetectorEvent().String(), detectMachineAction.GetResult())
}
GetCompleted
Return true
if detector has finished, false
otherwise.
Available In:
Parameters
None
Returns
Boolean
- True/False accordingly to the state.
Examples
Trying detecting DTMF and check if it has finished.
var det signalwire.DetectMachineParams
detectMachineAction, err := resultDial.Call.DetectMachineAsync(&det)
if err != nil {
signalwire.Log.Error("Error occurred while trying to start answering machine detector")
}
if !detectMachineAction.GetCompleted() {
detectMachineAction.Stop()
}
Stop
Stop the action immediately.
Available In:
Parameters
None
Returns
StopResult
Examples
Trying detecting a machine and then stop the action.
var det signalwire.DetectMachineParams
detectMachineAction, err := resultDial.Call.DetectMachineAsync(&det)
if err != nil {
signalwire.Log.Error("Error occurred while trying to start answering machine detector")
}
detectMachineAction.Stop()
GetControlID
Return the UUID to identify the action.
Available In:
Parameters
None
Returns
string
- UUID to identify the action.
Examples
Start a detector and print the controlId.
var det signalwire.DetectMachineParams
detectMachineAction, err := resultDial.Call.DetectMachineAsync(&det)
if err != nil {
signalwire.Log.Error("Error occurred while trying to start answering machine detector")
}
Signalwire.Log.Info("Detector ControlID: %s\n", detectMachineAction.GetControlID())
Relay.Calling.DetectResult
This object returned from one of synchronous detect methods that represents the final result of a detector.
Methods
GetEvent
Returns the last Relay Event arrived for this operation.
Available In:
Parameters
None
Returns
Relay.Event
- Last Relay Event.
Examples
Detect digits and grab the result when it's completed.
GetResult
Returns the result of the detector. It could be the digits or the type (machine
or human
) detected.
Available In:
Parameters
None
Returns
string
- Detector result.
Examples
Detect DTMF and print out the result.
GetType
Returns the type
of detector.
Available In:
Parameters
None
Returns
string
- Detector type: digit
, machine
or fax
.
Examples
Check the type of a detector.
GetSuccessful
Return true
if detector succeeded, false
otherwise.
Available In:
Parameters
None
Returns
Boolean
- True/False accordingly to the state.
Examples
Start detecting a fax, then check if a typical CED fax tone has been detected.
var det signalwire.DetectFaxParams
det.Tone = signalwire.DetectFaxCED.String() // or DetectFaxCNG
detectFaxAction, err := resultDial.Call.DetectFaxAsync(&det)
if err != nil {
signalwire.Log.Error("Error occurred while trying to start fax detector")
}
for {
time.Sleep(1 * time.Second)
if detectFaxAction.GetCompleted() {
signalwire.Log.Info("Fax Detection Success: %v", detectFaxAction.GetSuccessful())
break
}
}
Relay.Calling.FaxAction
This object returned from faxReceiveAsync
and faxSendAsync
methods represents a receiving or sending Fax on the call.
Methods
GetResult
Returns the final result of the faxing.
Available In:
Parameters
None
Returns
Relay.Calling.FaxResult
- Final result of the faxing.
Examples
Trying receiving a Fax and grab the result when it's completed.
call.OnFaxFinished = func(faxAction *signalwire.FaxAction) {
faxResult := faxAction.GetResult()
signalwire.Log.Info("Download Document from %s\n Pages #%d\n", faxResult.Document, faxResult.Pages)
}
_, err := call.ReceiveFaxAsync()
if err != nil {
signalwire.Log.Error("Error occurred while trying to receive fax\n")
}
GetCompleted
Return true
if faxing has finished, false
otherwise.
Available In:
Parameters
None
Returns
Boolean
- True/False accordingly to the state.
Examples
Trying receiving a Fax and check if it has finished.
faxAction, err := call.ReceiveFaxAsync()
if err != nil {
signalwire.Log.Error("Error occurred while trying to receive fax\n")
}
for {
time.Sleep(1 * time.Second)
if faxAction.GetCompleted() {
break
}
}
Stop
Stop the action immediately.
Available In:
Parameters
None
Returns
Examples
Trying to receive a Fax and then stop the attempt.
faxAction, err := call.ReceiveFaxAsync()
if err != nil {
signalwire.Log.Error("Error occurred while trying to receive fax\n")
}
time.Sleep(3 * time.Second)
faxAction.Stop()
Relay.Calling.FaxResult
This object returned from faxReceive
and faxSend
methods that represents the final result of a sent or received Fax.
Methods
GetDirection
Returns the direction of the fax: send
or receive
.
Available In:
Parameters
None
Returns
string
- send or receive.
Examples
Start faxing and then check the direction.
call.OnFaxFinished = func(faxAction *signalwire.FaxAction) {
faxResult := faxAction.GetResult()
signalwire.Log.Info("Direction %d\n", faxResult.Direction)
// same as
signalwire.Log.Info("Direction %d\n", faxAction.GetDirection())
}
_, err := call.ReceiveFaxAsync()
if err != nil {
signalwire.Log.Error("Error occurred while trying to receive fax\n")
}
GetEvent
Returns the last Relay Event arrived for this operation.
Available In:
Parameters
None
Returns
Relay.Event
- Last Relay Event.
Examples
Send a document and then inspect the last received Relay event.
GetDocument
Returns the URL to the document send or received.
Available In:
Parameters
None
Returns
string
- URL to the document.
Examples
Receiving fax and print the URL of the document.
call.OnFaxFinished = func(faxAction *signalwire.FaxAction) {
signalwire.Log.Info("Download Document from %s\n Pages #%d\n", faxAction.GetDocument(), faxAction.GetPages())
}
_, err := call.ReceiveFaxAsync()
if err != nil {
signalwire.Log.Error("Error occurred while trying to receive fax\n")
}
GetIdentity
Returns the identity sending the fax.
Available In:
Parameters
None
Returns
string
- Identity that sent the document.
Examples
Receiving fax and print the identity.
GetPages
Returns the number of pages in the document.
Available In:
Parameters
None
Returns
number
- Number of pages.
Examples
Print the number of received pages.
call.OnFaxFinished = func(faxAction *signalwire.FaxAction) {
signalwire.Log.Info("Download Document from %s\n Pages #%d\n", faxAction.GetDocument(), faxAction.GetPages())
}
GetRemoteIdentity
Returns the remote identity sent or receiving the Fax.
Available In:
Parameters
None
Returns
string
- The remote identity.
Examples
Receiving fax and print the remote identity.
GetSuccessful
Return true
if faxing succeeded, false
otherwise.
Available In:
Parameters
None
Returns
boolean
- True/False accordingly to the state.
Examples
Start sending a document and then check if it has sent successfully.
Relay.Calling.TapAction
This object returned from tapAsync
method that represents the running media tapping active on a call.
Signalwire will send RTP or Websocket Audio (WS or WSS).
Methods
GetResult
Returns the final result of this tapping
action.
Available In:
Parameters
None
Returns
Relay.Calling.TapResult
- Final tap
result.
Examples
Start tapping audio and grab the result when it's completed (RTP).
var tapdevice signalwire.TapDevice
tapdevice.Type = signalwire.TapRTP.String()
tapdevice.Params.Addr = "X.X.X.X"
tapdevice.Params.Port = 1234
tapdevice.Params.Codec = "PCMU"
/* direction can be TapDirectionListen, TapDirectionSpeak or TapDirectionBoth */
tapAction, err := resultDial.Call.TapAudioAsync(signalwire.TapDirectionListen, &tapdevice)
if err != nil {
signalwire.Log.Fatal("Error occurred while trying to tap audio: %v\n", err)
}
// tap for 10 seconds
time.Sleep(10 * time.Second)
tapAction.Stop()
signalwire.Log.Info("Tap: %v Result :%v\n", tapAction.GetTap(), tapAction.GetResult())
signalwire.Log.Info("SourceDevice: %v\n", tapAction.GetSourceDevice()) // comes from the Signalwire platform
signalwire.Log.Info("DestinationDevice: %v\n", tapAction.GetDestinationDevice()) // the device passed above
Start tapping audio and grab the result when it's completed (WS or WSS).
var tapdevice signalwire.TapDevice
tapdevice.Type = signalwire.TapWS.String()
tapdevice.Params.URI = "wss://X.X.X.X:1234" // ws or wss URI
tapdevice.Params.Codec = "PCMU"
/* direction can be TapDirectionListen, TapDirectionSpeak or TapDirectionBoth */
tapAction, err := resultDial.Call.TapAudioAsync(signalwire.TapDirectionListen, &tapdevice)
if err != nil {
signalwire.Log.Fatal("Error occurred while trying to tap audio: %v\n", err)
}
// tap for 10 seconds
time.Sleep(10 * time.Second)
tapAction.Stop()
signalwire.Log.Info("Tap: %v Result :%v\n", tapAction.GetTap(), tapAction.GetResult())
signalwire.Log.Info("SourceDevice: %v\n", tapAction.GetSourceDevice()) // comes from the Signalwire platform
signalwire.Log.Info("DestinationDevice: %v\n", tapAction.GetDestinationDevice()) // the device passed above
GetState
Return the current tapping
state.
Available In:
Parameters
None
Returns
string
- The current state.
Examples
Start tapping audio and print the state.
tapAction, err := resultDial.Call.TapAudioAsync(signalwire.TapDirectionListen, &tapdevice)
if err != nil {
signalwire.Log.Fatal("Error occurred while trying to tap audio: %v\n", err)
}
if !tapAction.GetCompleted() {
// 'while' loop for Go
for ok := true; ok; ok = !(tapAction.GetState() == signalwire.TapFinished) {
signalwire.Log.Info("Completed: %v State: %s\n", tapAction.GetCompleted(), tapAction.GetCompleted().String())
time.Sleep(1 * time.Second)
}
}
GetCompleted
Return true
if tapping has finished, false
otherwise.
Available In:
Parameters
None
Returns
Boolean
- True/False accordingly to the state.
Examples
Start tapping audio and check if it has finished.
tapAction, err := resultDial.Call.TapAudioAsync(signalwire.TapDirectionListen, &tapdevice)
if err != nil {
signalwire.Log.Fatal("Error occurred while trying to tap audio: %v\n", err)
}
if !tapAction.GetCompleted() {
// 'while' loop for Go
for ok := true; ok; ok = !(tapAction.GetState() == signalwire.TapFinished) {
signalwire.Log.Info("Completed: %v State: %s\n", tapAction.GetCompleted(), tapAction.GetCompleted().String())
time.Sleep(1 * time.Second)
}
}
GetSourceDevice
Return the source device sending media.
Available In:
Parameters
None
Returns
Object
- The source device.
Examples
Start tapping audio and then inspect the source device.
var tapdevice signalwire.TapDevice
tapdevice.Type = signalwire.TapRTP.String()
tapdevice.Params.Addr = "X.X.X.X"
tapdevice.Params.Port = 1234
tapdevice.Params.Codec = "PCMU"
tapAction, err := resultDial.Call.TapAudioAsync(signalwire.TapDirectionListen, &tapdevice)
if err != nil {
signalwire.Log.Fatal("Error occurred while trying to tap audio: %v\n", err)
}
// tap for 10 seconds
time.Sleep(10 * time.Second)
tapAction.Stop()
signalwire.Log.Info("SourceDevice: %v\n", tapAction.GetSourceDevice())
Stop
Stop the action immediately.
Available In:
Parameters
None
Returns
error
Examples
Start tapping audio and then stop the action.
tapAction.Stop()
signalwire.Log.Info("Tap: %v Result :%v\n", tapAction.GetTap(), tapAction.GetResult())
signalwire.Log.Info("SourceDevice: %v\n", tapAction.GetSourceDevice()) // comes from the Signalwire platform
signalwire.Log.Info("DestinationDevice: %v\n", tapAction.GetDestinationDevice()) // the device passed above
GetControlID
Return the UUID to identify the action.
Available In:
Parameters
None
Returns
string
- UUID to identify the action.
Relay.Calling.TapResult
This object returned from tap
method that represents the final result of a tapping.
Methods
GetDestinationDevice
Returns the destination
device receiving media.
Available In:
Parameters
None
Returns
Object
- The destination device.
Examples
Tap audio and then inspect the destination device.
var tapdevice signalwire.TapDevice
tapdevice.Type = signalwire.TapRTP.String()
tapdevice.Params.Addr = "82.47.225.162"
tapdevice.Params.Port = 1234
tapdevice.Params.Codec = "PCMU"
tapAction, err := resultDial.Call.TapAudioAsync(signalwire.TapDirectionListen, &tapdevice)
if err != nil {
signalwire.Log.Fatal("Error occurred while trying to tap audio: %v\n", err)
}
time.Sleep(10 * time.Second)
tapAction.Stop()
signalwire.Log.Info("Tap: %v Result: %v\n", tapAction.GetTap(), tapAction.GetResult())
signalwire.Log.Info("SourceDevice: %v\n", tapAction.GetSourceDevice()) // comes from the Signalwire platform
signalwire.Log.Info("DestinationDevice: %v\n", tapAction.GetDestinationDevice()) // the device passed above
GetEvent
Returns the last Relay Event arrived for this operation.
Available In:
Parameters
None
Returns
Relay.Event
- Last Relay Event.
GetSourceDevice
Returns the source
device sending media.
Available In:
Parameters
None
Returns
Object
- The source device.
Examples
Inspect the source device.
signalwire.Log.Info("SourceDevice: %v\n", tapAction.GetSourceDevice()) // comes from the Signalwire platform
GetTap
Returns the params for this tap
action.
Available In:
Parameters
None
Returns
signalwire.Tap
Examples
Inspect the
tap
params.
signalwire.Log.Info("Tap: %v Result: %v\n", tapAction.GetTap(), tapAction.GetResult())
GetSuccessful
Return true
if the tapping succeeded, false
otherwise.
Available In:
Parameters
None
Returns
Boolean
- True/False accordingly to the state.
Relay.Calling.PromptAction
This object returned from one of asynchronous prompt methods that represents a prompt attempt that is currently active on a call.
Methods
GetResult
Returns the final result of the prompt attempt.
Available In:
Parameters
None
Returns
Relay.Calling.PromptResult
- Final result of the prompt attempt.
Examples
Start the attempt and grab the result when it's completed.
resultDial.Call.OnPrompt = func(promptaction *signalwire.PromptAction) {
// we could do something here and this gets called when the Prompt Action finishes.
}
playAudioParams := signalwire.PlayAudioParams{
URL: "https://www.pacdv.com/sounds/voices/can-you-keep-a-secret.wav",
}
playTTSParams := signalwire.PlayTTSParams{
Text: "Hello from Signalwire!",
}
playRingtoneParams := signalwire.PlayRingtoneParams{
Duration: 5,
Name: "us",
}
play := []signalwire.PlayStruct{{
Type: "audio",
Params: playAudioParams,
}, {
Type: "tts",
Params: playTTSParams,
}, {
Type: "ringtone",
Params: playRingtoneParams,
}}
collectDigits := new(signalwire.CollectDigits)
collectDigits.Max = 3
collectSpeech := new(signalwire.CollectSpeech)
collectSpeech.EndSilenceTimeout = 1
collectSpeech.SpeechTimeout = 10
collectSpeech.Hints = []string{"top", "well"}
collect := signalwire.CollectStruct{
Speech: collectSpeech,
Digits: collectDigits,
}
promptAction, err := resultDial.Call.PromptAsync(&play, &collect)
if err != nil {
signalwire.Log.Error("Error occurred while trying to start Prompt Action\n")
if err := consumer.Stop(); err != nil {
signalwire.Log.Error("Error occurred while trying to stop Consumer. Err: %v\n", err)
}
return
}
if !promptAction.GetCompleted() {
promptAction.Stop()
}
for {
time.Sleep(1 * time.Second)
if promptAction.GetCompleted() {
break
}
}
myResult := promptAction.GetResultType()
switch myResult {
case signalwire.CollectResultSpeech:
signalwire.Log.Info("Speech text: \"%s\" Confidence: %f\n", promptAction.GetCollectResult(), promptAction.GetConfidence())
case signalwire.CollectResultDigit:
signalwire.Log.Info("Digits: \"%s\" Terminator: %s\n", promptAction.GetCollectResult(), promptAction.GetTerminator())
default:
signalwire.Log.Info("Result was: %s\n", myResult.String())
}
GetCompleted
Return true
if the prompt attempt has finished, false
otherwise.
Available In:
Parameters
None
Returns
Boolean
- True/False accordingly to the state.
Examples
Start the attempt and check if it has finished.
promptAction, err := resultDial.Call.PromptAsync(&play, &collect)
for {
time.Sleep(1 * time.Second)
if promptAction.GetCompleted() {
break
}
}
Stop
Stop the action immediately.
Available In:
Parameters
None
Returns
error
Examples
Start the attempt and then stop it.
if !promptAction.GetCompleted() {
promptAction.Stop()
}
Volume
Control the volume of the playback.
Available In:
Parameters
volume |
number | required | Volume value between -40dB and +40dB where 0 is unchanged. |
Returns
error
Examples
Start the prompt and increase the playback volume with 5 dB
promptAction, err := resultDial.Call.PromptAsync(&play, &collect)
promptAction.Volume(5)
GetControlID
Return the UUID to identify the action.
Available In:
Parameters
None
Returns
string
- UUID to identify the action.
Relay.Calling.PromptResult
This object returned from one of synchronous prompt methods that represents the final result of a prompting attempt.
Methods
GetConfidence
In a prompt
action of type speech
, it returns the confidence of the result.
Available In:
Parameters
None
Returns
number
- Confidence of the result on a speech
prompt.
Examples
Start prompt and then check the result confidence.
promptAction, err := resultDial.Call.PromptAsync(&play, &collect)
for {
time.Sleep(1 * time.Second)
if promptAction.GetCompleted() {
break
}
}
myResult := promptAction.GetResultType()
switch myResult {
case signalwire.CollectResultSpeech:
signalwire.Log.Info("Speech text: \"%s\" Confidence: %f\n", promptAction.GetCollectResult(), promptAction.GetConfidence())
case signalwire.CollectResultDigit:
signalwire.Log.Info("Digits: \"%s\" Terminator: %s\n", promptAction.GetCollectResult(), promptAction.GetTerminator())
default:
signalwire.Log.Info("Result was: %s\n", myResult.String())
}
GetEvent
Returns the last Relay Event arrived for this operation.
Available In:
Parameters
None
Returns
Relay.Event
- Last Relay Event.
Examples
Stop the prompt and then inspect last Relay event payload.
promptAction.Stop()
lastEvent := promptAction.GetEvent()
ev := struct {
Params *json.RawMessage `json:"params"`
{Params: lastEvent}
b, err := json.MarshalIndent(&ev, "", "\t")
if err != nil {
signalwire.Log.Error("error:", err)
}
signalwire.Log.Info("Last event: %s\n", b)
GetResult
Returns the user's input in a prompt attempt. Could be both from speech
or digits
type.
Available In:
Parameters
None
Returns
signalwire.CollectResult
Examples
Show CollectResult.
myResult := promptAction.GetResultType()
switch myResult {
case signalwire.CollectResultSpeech:
signalwire.Log.Info("Result: \"%v\" Confidence: %f\n", promptAction.GetResult(), promptAction.GetConfidence())
case signalwire.CollectResultDigit:
signalwire.Log.Info("Result: \"%v\" Terminator: %s\n", promptAction.GetResult(), promptAction.GetTerminator())
default:
}
GetTerminator
In a prompt
action of type digits
, it returns the digit that has terminated the attempt.
Available In:
Parameters
None
Returns
string
- Digit that has terminated the prompt attempt.
Examples
Show the terminator digit.
myResult := promptAction.GetResultType()
switch myResult {
case signalwire.CollectResultSpeech:
signalwire.Log.Info("Result: \"%v\" Confidence: %f\n", promptAction.GetResult(), promptAction.GetConfidence())
case signalwire.CollectResultDigit:
signalwire.Log.Info("Result: \"%v\" Terminator: %s\n", promptAction.GetResult(), promptAction.GetTerminator())
default:
}
GetSuccessful
Return true
if the prompt attempt succeeded, false
otherwise.
Available In:
Parameters
None
Returns
boolean
- True/False accordingly to the state.
Examples
Start the prompt and then check if it has ended successfully.
promptAction, err := resultDial.Call.PromptAsync(&play, &collect)
for {
time.Sleep(1 * time.Second)
if promptAction.GetCompleted() {
break
}
}
signalwire.Log.Info("Success: %v\n", promptAction.GetSuccessful())
Relay.Calling.PromptVolumeResult
This object is returned by volume
method and represents the final result of a volume control operation.
Properties
Successful |
boolean | Whether the volume has been changed successfully. |
Relay.Calling.SendDigitsAction
This object is returned by sendDigitsAsync
method that represents a send digits operation currently active on a call.
Methods
GetResult
Returns the final result of the send digits operation.
Available In:
Parameters
None
Returns
Relay.Calling.SendDigitsResult
- Final result of the operation.
Examples
Show the Result.
resultDial.Call.OnSendDigitsFinished = func(a *signalwire.SendDigitsAction) {
signalwire.Log.Info("SendDigits finished with result: [%v]\n", sendDigitsAction.GetResult())
}
GetCompleted
Return true
if the operation has finished, false
otherwise.
Available In:
Parameters
None
Returns
Boolean
- True/False accordingly to the state.
Examples
Send some digits and check if it has finished.
/* use an anonymous function as CB */
resultDial.Call.OnSendDigitsFinished = func(a *signalwire.SendDigitsAction) {
signalwire.Log.Info("SendDigits finished with successful result: [%v]\n", a.GetSuccessful())
}
sendDigitsAction, err := resultDial.Call.SendDigitsAsync("1234567890*#")
if err != nil {
signalwire.Log.Error("Error occurred while trying to play audio\n")
}
// SendDigits does not need a Stop() command.
if sendDigitsAction.GetCompleted() {
// just print this again
signalwire.Log.Info("SendDigits finished with successful result: [%v]\n", sendDigitsAction.GetSuccessful())
}
GetControlID
Return the UUID to identify the action.
Available In:
Parameters
None
Returns
string
- UUID to identify the action.
Relay.Calling.SendDigitsResult
This object is returned by sendDigits
method and represents the final result of a send digits action.
Methods
GetEvent
Returns the last Relay Event arrived for this operation.
Available In:
Parameters
None
Returns
Relay.Event
- Last Relay Event.
GetSuccessful
Return true
if the operation has succeeded, false
otherwise.
Available In:
Parameters
None
Returns
boolean
- Whether the operation has completed successfully.
Examples
Send some digits and then check if it has ended successfully.
/* use an anonymous function as CB */
resultDial.Call.OnSendDigitsFinished = func(a *signalwire.SendDigitsAction) {
signalwire.Log.Info("SendDigits finished with successful result: [%v]\n", a.GetSuccessful())
}
sendDigitsAction, err := resultDial.Call.SendDigitsAsync("1234567890*#")
if err != nil {
signalwire.Log.Error("Error occurred while trying to play audio\n")
}
// do something more here
time.Sleep(2 * time.Second)
if sendDigitsAction.GetCompleted() {
// just print this again
signalwire.Log.Info("SendDigits finished with successful result: [%v]\n", sendDigitsAction.GetSuccessful())
}
Relay.Event
This object represents the last Relay event that completed an operation on the Call.
Properties
Name |
string | The event name. |
Payload |
JObject | Raw JSON object of the Relay event. |
Relay.Messaging
This represents the API interface for the Messaging Relay Service. This object is used to make requests related to managing SMS and MMS messages.
Methods
Send
Send a message to the destination number.
Available In:
Parameters
Context |
string | required | The context to receive inbound events. |
From |
string | required | The phone number to place the message from. Must be a SignalWire phone number or short code that you own. |
To |
string | required | The phone number to send to. |
Body |
string | required | The content of the message. Optional if media is present. |
Media |
string[] | required | Array of URLs to send in the message. Optional if body is present. |
Tags |
string[] | optional | Array of strings to tag the message with for searching in the UI. |
Returns
SendResult
Examples
Send a message in the context office.
text := "Hello from Signalwire !"
context := "office"
from := "+1XXXXXXXXXX"
to := "+15XXXXXXXXX"
message := consumer.Client.Messaging.NewMessage(context, from, to, text)
message.OnMessageQueued = func(_ *signalwire.SendResult) {
Signalwire.Log.Info("Message Queued.\n")
}
message.OnMessageDelivered = func(_ *signalwire.SendResult) {
signalwire.Log.Info("Message Delivered.\n")
}
resultSend := consumer.Client.Messaging.SendMsg(message)
if !resultSend.GetSuccessful() {
signalwire.Log.Error("Could not send message\n")
}
Relay.Messaging.Message
An object representing an SMS or MMS message. It is the parameter of both onIncomingMessage
and onMessageStateChange
Consumer handlers.
Properties
Id |
string | The unique identifier of the message. |
Context |
string | The context of the message. |
From |
string | The phone number the message comes from. |
To |
string | The destination number of the message. |
Direction |
string | The direction of the message: inbound or outbound . |
State |
string | The current state of the message. See Relay.Messaging.Message State Events for all the possible states. |
Body |
string | The content of the message. |
Media |
string[] | Array of URLs media. |
Tags |
string[] | Array of strings with message tags. |
Segments |
number | Number of segments of the message. |
Reason |
string | Reason why the message was not sent. Present only in case of failure. |
Events
State Events
To track the state of a message.
MsgQueued |
The message has been queued in Relay. |
MsgInitiated |
Relay has initiate the process to send the message. |
MsgSent |
Relay has sent the message. |
MsgDelivered |
The message has been successfully delivered. Due to the nature of SMS and MMS, receiving a delivered event is not guaranteed, even if the message is delivered successfully. |
MsgUndelivered |
The message has not been delivered. Due to the nature of SMS and MMS, receiving a undelivered event is not guaranteed, even if the message fails to be delivered. |
MsgFailed |
The call has failed. |
Relay.Messaging.SendResult
This object returned from send
method that represents the result of a send operation.
Properties
Successful |
boolean | Whether the send operation has successfully queued the message. |
MessageId |
string | The ID of the message. |
Methods
GetMsgId
Returns the ID of the queued message (MessageId).
Available In:
Parameters
None
Returns
string
- Message ID.
Examples
Send a message and retrieve the ID.
/* just send a message using Send() with params */
resultSend := consumer.Client.Messaging.Send(from, to, context, "Hello again from Signalwire !")
if resultSend.GetSuccessful() {
signalwire.Log.Info("Msg Id: %s\n", resultSend.GetMsgId())
}
GetSuccessful
Return true
if the message was queued, false
otherwise.
Available In:
Parameters
None
Returns
boolean
- True/False accordingly to the state.
Examples
Send a message and then check if there was an error.
resultSend := consumer.Client.Messaging.Send(from, to, context, "Hello again from Signalwire !")
if !resultSend.GetSuccessful() {
signalwire.Log.Info("error while trying to send message")
}
Relay.TaskingAPI
This represents the API interface for the Tasking Relay Service. A Relay.RelayTask
is simple way to send jobs to your SignalWire.Relay.Consumer
from a short lived process, like a web framework. Relay Tasks allow you to pass commands down to your Consumers without blocking your short lived request. Think of a Relay Task as a way to queue a job for your background workers to processes asynchronously.
For example, if you wanted to make an outbound call and play a message when your user clicks a button on your web application, since Relay is a realtime protocol and relies on you to tell it what to do in realtime, if you did this within your web application, your web server would block until the call was finished... this may take a long time! Instead, simply create a new Relay Task. This task will be handled by a running Relay Consumer process and your web application can respond back to your user immediately.
Methods
Deliver
Deliver the specified message.
Available In:
Parameters
Context |
string | required | The context to receive inbound events. |
Message |
[]byte | required | The message to deliver (Json). |
Returns
bool
- true
if the delivery is successfully started, false
if a problem is encountered.
Examples
Send a message.
Contexts = append(Contexts, PContext)
consumer := new(signalwire.Consumer)
// setup the Client
consumer.Setup(PProjectID, PTokenID, Contexts)
// register callback
consumer.Ready = func(consumer *signalwire.Consumer) {
done := make(chan struct{}, 1)
consumer.OnTask = func(_ *signalwire.Consumer, ev signalwire.ParamsEventTaskingTask) {
signalwire.Log.Info("Task Delivered. %v\n", ev)
go func() {
done <- struct{}{}
}()
}
taskMsg := PassToTask{
Foo: 123,
Bar: "baz",
}
/*
The above would be declared like:
type PassToTask struct {
Foo uint `json:"foo"`
Bar string `json:"bar"`
}
*/
byteArray, err := json.MarshalIndent(taskMsg, "", " ")
if err != nil {
signalwire.Log.Error("%v", err)
return
}
signalwire.Log.Info(string(byteArray))
if result := consumer.Client.Tasking.Deliver(DefaultContext, byteArray); !result {
signalwire.Log.Error("Could not deliver task\n")
go func() {
done <- struct{}{}
}()
}
// stop when task has been delivered or on error
<-done
}
Events
All these events can be used to track a task.
Receive Events
OnTask |
A task has been received. |
Relay.Task
A Relay.Task
is simple way to send jobs to your Relay.Consumers
from a short lived process, like a web framework. Relay Tasks allow you to pass commands down to your Consumers without blocking your short lived request. Think of a Relay Task as a way to queue a job for your background workers to processes asynchronously.
Methods
Deliver
Send a job to your Consumer
in a specific context.
Available In:
Parameters
Context |
string | required | Context where to send the Task. |
Message |
array | required | Array with your custom data that will be sent to your Consumer's onTask handler. |
Returns
boolean
- Whether the Task has been sent successfully.
Examples
Deliver a task to your Consumer with a message to then make an outbound Call.
type PassToTask struct {
Foo uint `json:"foo"`
Bar string `json:"bar"`
}
func main() {
[...]
consumer.OnTask = func(_ *signalwire.Consumer, ev signalwire.ParamsEventTaskingTask) {
signalwire.Log.Info("Task Delivered. %v\n", ev)
go func() {
done <- struct{}{}
}()
}
taskMsg := PassToTask{
Foo: 123,
Bar: "baz",
}
byteArray, err := json.MarshalIndent(taskMsg, "", " ")
if err != nil {
signalwire.Log.Error("%v", err)
return
}
if result := consumer.Client.Tasking.Deliver(DefaultContext, byteArray); !result {
signalwire.Log.Error("Could not deliver task\n")
go func() {
done <- struct{}{}
}()
}
}
// stop when task has been delivered or on error
<-done
}