Created
April 30, 2024 11:22
-
-
Save rajneeshksoni/e8c1dda12925e17ace11ecf8988c6135 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import twilio from "twilio"; | |
async function wait(second) { | |
return new Promise((resolve) => { | |
setTimeout(resolve, second * 1000); | |
}); | |
} | |
async function makeCall(event) { | |
const accountSid = ""; | |
const authToken = ""; | |
const client = twilio(accountSid, authToken); | |
const twimlRes = ` | |
<Response> | |
<Dial callerId="VERIFIED_PHONE_NUMBER">${event.phoneNumber}</Dial> | |
</Response>`; | |
// First dial sip with retry | |
let sipResp; | |
let try_count = 0; | |
while (true) { | |
try_count++; | |
sipResp = await client.calls.create({ | |
twiml: twimlRes, | |
method: "POST", | |
to: event.sipUri, | |
from: "TWILIO_VERIFIED_PHONE_NUMBER", | |
}); | |
console.log(`sipResp.sid: ${sipResp.sid} status: ${sipResp.status}`); | |
// wait for 10 second | |
await wait(10); | |
let resp = await client.calls(sipResp.sid).fetch(); | |
console.log(`sip call status after 10 sec wait: status: ${resp.status}`); | |
if ( | |
resp.status == "in-progress" || | |
resp.status == "completed" || | |
resp.status == "canceled" | |
) { | |
return { sid: resp.sid, status: resp.status }; | |
} else { | |
// close the current call and re-dial | |
await client.calls(sipResp.sid).update({ status: "completed" }); | |
if (try_count >= 3) { | |
return { status: "call-failed" }; | |
} | |
} | |
} | |
} | |
export const handler = async (event) => { | |
let body; | |
try { | |
body = JSON.parse(event.body); | |
console.log(body); | |
if (body.sipUri && body.phoneNumber) { | |
const resp = await makeCall(body); | |
const response = { | |
statusCode: 200, | |
body: JSON.stringify(resp), | |
}; | |
return response; | |
} else { | |
const response = { | |
statusCode: 400, | |
body: JSON.stringify( | |
`call with {sipUri: "sip:...", phoneNumber: "+157373"} }` | |
), | |
}; | |
return response; | |
} | |
} catch (e) { | |
console.log("failed with error:", e); | |
return { | |
statusCode: 400, | |
body: e.message, | |
}; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment