Twilio Voice Agent in Node.js with Media Streams
TwilioTransport runs a Micdrop call on a bidirectional
Twilio Media Stream. The
caller arrives in μ-law at 8 kHz, and the assistant goes back the same way.
Read phone calls first for what every provider shares.
Answer the call
Point the voice webhook of your Twilio number to a route that answers with the
TwiML of twilioStreamTwiml. It connects the call to the WebSocket of your
server, and passes the parameters of the call along:
import Fastify from 'fastify'import formbody from '@fastify/formbody'import websocket from '@fastify/websocket'import { twilioStreamTwiml } from '@micdrop/telephony'
const app = Fastify()await app.register(formbody) // Twilio posts its webhooks as a formawait app.register(websocket)
app.post('/twilio/voice', async (request, reply) => { const { From } = request.body as { From: string } reply.type('text/xml') return twilioStreamTwiml({ url: 'wss://example.com/twilio/stream', parameters: { caller: From }, })})Twilio accepts no query string in the address of a stream, so the parameters
travel as <Parameter> elements, which the transport hands to
waitForParams. Each name and value together stay under 500 characters.
Run the stream
import { MicdropServer, waitForParams } from '@micdrop/server'import { TwilioTransport } from '@micdrop/telephony'import '@micdrop/vad/node'
app.get('/twilio/stream', { websocket: true }, async (socket) => { const transport = new TwilioTransport(socket) const { caller } = await waitForParams(transport, (params) => params)
new MicdropServer(transport, { vad: 'silero', firstMessage: 'Hello, thanks for calling. How can I help?', agent, stt, tts, })})transport.call.callId holds the Call SID, to act on the call with the Twilio
API, and transport.call.streamId the Stream SID.
Hanging up
Closing the WebSocket ends the <Connect> verb, and Twilio moves on to the
next verb of the TwiML. With nothing after it, the call ends. When the agent
ends the call, the transport sends a mark after the goodbye and closes once
Twilio confirms it played. To say something after the agent, such as a survey,
add the verbs after the stream, or set the action of <Connect>.
twilioStreamTwiml takes before, TwiML said before the stream starts, a
recording notice for instance:
twilioStreamTwiml({ url: 'wss://example.com/twilio/stream', before: '<Say>This call may be recorded.</Say>',})Security
Twilio signs the WebSocket request with an X-Twilio-Signature header. Check
it with the validateRequest function of the Twilio SDK before accepting the
stream, so only Twilio can open a call on your server.
SignalWire
SignalWire speaks the same protocol in its cXML <Connect><Stream>, so
TwilioTransport and twilioStreamTwiml work with it, on its default PCMU
codec.