You can use the callback pattern to connect to the Asterisk REST Interface (ARI). The client.connect method accepts the ARI URL, username, and password, and takes a callback function that receives an error and the ari instance. Once connected, you can listen for events like StasisStart and perform operations on channels, such as answering calls or playing media.
var client = require('ari-client'),
util = require('util');
client.connect('http://localhost:8088', 'user', 'secret', client_loaded);
function client_loaded (err, ari) {
if (err) {
throw err; // program will crash if it fails to connect
}
ari.once('StasisStart', channel_joined);
function channel_joined (event, incoming) {
incoming.on('ChannelDtmfReceived', dtmf_received);
incoming.answer(function (err) {
play(incoming, 'sound:hello-world');
});
}
function dtmf_received (event, channel) {
var digit = event.digit;
switch (digit) {
case '#':
play(channel, 'sound:vm-goodbye', function (err) {
channel.hangup(function (err) {
process.exit(0);
});
});
break;
case '*':
play(channel, 'sound:tt-monkeys');
break;
default:
play(channel, util.format('sound:digits/%s', digit));
}
}
function play (channel, sound, callback) {
var playback = ari.Playback();
playback.on('PlaybackFinished', function (event, playback) {
if (callback) {
callback(null);
}
});
channel.play({media: sound}, playback, function (err, playback) {});
}
ari.start('hello');
}