twilio-opencode

A lightweight express server to handle Twilio voice and messaging webhooks for prompting Opencode.
git clone https://unitehenry.com/git/twilio-opencode.git
Log | Files | Refs | README | LICENSE

voice.ts (3495B)


      1 import { type Request, type Response } from "express";
      2 import twilio from "twilio";
      3 import prompt from "./prompt.ts";
      4 import whitelist from "./whitelist.ts";
      5 import log from "./log.ts";
      6 
      7 const DEFAULT_GREETING = "Hello";
      8 
      9 const HOLD_MUSIC_URL =
     10   "http://com.twilio.sounds.music.s3.amazonaws.com/MARKOVICHAMP-Borghestral.mp3";
     11 
     12 function buildResponseXml(req: Request, message: string): string {
     13   const origin = `${req.protocol}://${req.get("host")}`;
     14 
     15   return `<?xml version="1.0" encoding="UTF-8"?>
     16     <Response>
     17       <Gather input="speech" action="${origin}/voice" method="POST">
     18         <Say>${message}</Say>
     19       </Gather>
     20     </Response>
     21   `;
     22 }
     23 
     24 function respond(req: Request, res: Response, message: string): void {
     25   const responseXml = buildResponseXml(req, message);
     26 
     27   res.set("Content-Type", "text/xml");
     28 
     29   res.send(responseXml);
     30 }
     31 
     32 function buildHangupXml(message: string) {
     33   return `<?xml version="1.0" encoding="UTF-8"?>
     34       <Response>
     35         <Say>${message}</Say>
     36         <Hangup />
     37       </Response>
     38     `;
     39 }
     40 
     41 function hangup(res: Response, message: string = ""): void {
     42   const hangupXml = buildHangupXml(message);
     43 
     44   res.set("Content-Type", "text/xml");
     45 
     46   res.send(hangupXml);
     47 }
     48 
     49 function buildHoldXml(holdMusicUrl: string) {
     50   return `<?xml version="1.0" encoding="UTF-8"?>
     51     <Response>
     52       <Play loop="0">${holdMusicUrl}</Play>
     53     </Response>`;
     54 }
     55 
     56 function hold(res: Response): void {
     57   const holdXml = buildHoldXml(HOLD_MUSIC_URL);
     58 
     59   res.set("Content-Type", "text/xml");
     60 
     61   res.send(holdXml);
     62 }
     63 
     64 interface UpdateCallParams {
     65   request: Request;
     66   accountSid: string;
     67   callSid: string;
     68   message: string;
     69   twilioAuthToken: string;
     70 }
     71 
     72 async function updateCall(params: UpdateCallParams): Promise<void> {
     73   const twilioClient = twilio(params.accountSid, params.twilioAuthToken);
     74 
     75   const twiml = buildResponseXml(params.request, params.message);
     76 
     77   try {
     78     log("INFO", "Updating twilio call", { callSid: params.callSid });
     79 
     80     await twilioClient.calls(params.callSid).update({ twiml });
     81   } catch (error) {
     82     log("ERROR", "Failed to update call", { error });
     83   }
     84 }
     85 
     86 export default async (req: Request, res: Response): Promise<void> => {
     87   const app = req.app;
     88 
     89   const callSid: string = req.body.CallSid;
     90 
     91   const from: string = req.body.From;
     92 
     93   log("INFO", `Call webhook received`, { callSid, from });
     94 
     95   if (!whitelist(from)) {
     96     log("WARN", "Phone number not whitelisted", { callSid, from });
     97 
     98     hangup(res);
     99 
    100     return;
    101   }
    102 
    103   const speechResult: string = req.body.SpeechResult;
    104 
    105   if (!speechResult) {
    106     log("INFO", "No speech result received");
    107 
    108     respond(req, res, DEFAULT_GREETING);
    109 
    110     return;
    111   }
    112 
    113   log("INFO", "Caller message received", { callSid, speechResult });
    114 
    115   const twilioAuthToken: string | undefined = process.env.TWILIO_AUTH_TOKEN;
    116 
    117   if (twilioAuthToken) {
    118     hold(res);
    119   }
    120 
    121   const { sessionId, text } = await prompt({
    122     message: speechResult,
    123     sessionId: app.get(callSid) as string | null,
    124   });
    125 
    126   log("INFO", "Agent responded", { callSid, sessionId, text });
    127 
    128   app.set(callSid, sessionId);
    129 
    130   log("INFO", "Session cached", { callSid, sessionId });
    131 
    132   if (!twilioAuthToken) {
    133     log("INFO", "No auth token, responding to webhook");
    134 
    135     respond(req, res, text);
    136 
    137     return;
    138   }
    139 
    140   const accountSid: string = req.body.AccountSid;
    141 
    142   log("INFO", "Creating twilio client", { accountSid });
    143 
    144   await updateCall({
    145     accountSid,
    146     callSid,
    147     twilioAuthToken,
    148     request: req,
    149     message: text,
    150   });
    151 };