这里是 Twilio 开发者宣传员。
好的,您正在使用 Node.js 构建,我知道我已经在其他问题中看到过您的代码,但我将从头开始。
使用 Twilio,您描述的流程应如下所示。
- 有人拨打您的 Twilio 号码
- Twilio 向号码的语音请求 URL(指向您的应用程序)发出 HTTP 请求
- 您的应用程序现在需要做两件事
- 拨打您的手机号码
- 将呼叫者置于会议中并播放保留音乐
- 首先您需要确定会议的名称
- 然后,要呼叫您的号码,您的应用程序需要调用 Twilio REST API 以启动对您的手机的呼叫
- 您需要在此呼叫中提供一个回调 URL,以便您也加入会议,您可以通过在 URL 中包含会议名称作为参数来做到这一点
- 您的应用程序还需要返回 TwiML 以使用相同的会议名称将呼叫者加入会议
- 最后,当您接听电话时,Twilio 将向您在发起呼叫时提供的 URL 发出 HTTP 请求
- 这将请求您的 URL,该 URL 应使用 TwiML 进行响应,以将您置于同一个电话会议中
让我们看看如何在 Node.js Express 应用程序中做到这一点:
您需要两条路线,一条接收初始请求,一条响应您接听电话时提出的请求。查看下面的代码和 cmets。
var express = require("express");
var bodyParser = require("body-parser");
var twilio = require("twilio");
var app = express();
app.use(bodyParser.urlencoded({ extended: true }));
var client = twilio(YOUR_ACCOUNT_SID, YOUR_AUTH_TOKEN);
// This is the endpoint your Twilio number's Voice Request URL should point at
app.post('/calls', function(req, res, next) {
// conference name will be a random number between 0 and 10000
var conferenceName = Math.floor(Math.random() * 10000).toString();
// Create a call to your mobile and add the conference name as a parameter to
// the URL.
client.calls.create({
from: YOUR_TWILIO_NUMBER,
to: YOUR_MOBILE_NUMBER,
url: "/join_conference?id=" + conferenceName
});
// Now return TwiML to the caller to put them in the conference, using the
// same name.
var twiml = new twilio.TwimlResponse();
twiml.dial(function(node) {
node.conference(conferenceName, {
waitUrl: "http://twimlets.com/holdmusic?Bucket=com.twilio.music.rock",
startConferenceOnEnter: false
});
});
res.set('Content-Type', 'text/xml');
res.send(twiml.toString());
});
// This is the endpoint that Twilio will call when you answer the phone
app.post("/join_conference", function(req, res, next) {
var conferenceName = req.query.id;
// We return TwiML to enter the same conference
var twiml = new twilio.TwimlResponse();
twiml.dial(function(node) {
node.conference(conferenceName, {
startConferenceOnEnter: true
});
});
res.set('Content-Type', 'text/xml');
res.send(twiml.toString());
});
让我知道这是否有帮助。
更新
在最新版本的 Twilio Node.js 库中,您不能使用 twilio.TwimlResponse。相反,有用于语音和消息传递的单独类。在本例中,行
var twiml = new twilio.TwimlResponse();
应更新为:
var twiml = new twilio.twiml.VoiceResponse();