问题描述
我使用这个 sms plugin 从 flex 创建了一个出站短信。 我可以成功发送出站短信,并灵活创建会话和聊天窗口以进行双向聊天。从这个聊天窗口回复时,它会创建一个对给定 webhook 的会话外调用。
以下与发送短信时会话相关的功能中缺少什么?
问题 2:twilio-node 中是否提供 Channels API?
发起聊天的代码如下,link for detail code
const axios = require('axios');
exports.handler = async function (context,event,callback) {
const response = new Twilio.Response();
const authed = await validatetoken(event.Token,context.ACCOUNT_SID,context.AUTH_TOKEN); //Not showing validatetoken function here,can be found in plugin link above
const client = context.getTwilioClient();
const to = +13...4724 // outbound "To" number to send sms
const from = +128.....834 // Twilio Number i.e "From" number
const channelArgs = {
FlexFlowSid: context.FLEX_FLOW_SID,Identity: event.To,Target: event.To,ChatUserFriendlyName: event.ToFriendlyName || event.To,ChatFriendlyName: event.ChatFriendlyName || `${event.To} chat`,PreEngagementData: JSON.stringify({ targetWorker: authed.data.identity })
};
const channelResponse = await createChannel(channelArgs,context.AUTH_TOKEN);
client.messages.create({
body: event.Message,to: to,from: from
})
.then(() => {
console.log('adding message to',channelResponse.data.sid);
client.chat.services(context.CHAT_SERVICE_SID)
.channels(channelResponse.data.sid)
.messages
.create({
body: event.Message,from: from
}).then(() => callback(null,response));
}).catch(err => {
console.error(err);
callback(err);
});
}
async function createChannel(channelArgs,accountSid,authToken) {
const queryString = Object.keys(channelArgs)
.map(k => `${k}=${encodeURIComponent(channelArgs[k])}`)
.join('&');
console.log('sending',queryString);
try {
// Channels API not in twilio-node yet... so axios
return await axios.post(
'https://flex-api.twilio.com/v1/Channels',queryString,{ auth: { username: accountSid,password: authToken } }
)
} catch (e) {
console.error(e.response.data);
throw e;
}
}
解决方法
这里是 Twilio 开发者布道者。
Flex Channels API is available in the Twilio Node library now。确保将最新的 twilio
包安装到 package.json 中,您可以像这样调用它:
client.flexApi.channel
.create({
flexFlowSid: context.FLEX_FLOW_SID,identity: event.To,chatUserFriendlyName: event.ToFriendlyName || event.To,chatFriendlyName: event.ChatFriendlyName || `${event.To} chat`,preEngagementData: JSON.stringify({ targetWorker: authed.data.identity })
})
.then(channel => console.log(channel.sid));
也许尝试更新到最新的 Twilio Node 包,更新以使用上面的代码,看看它是否仍然有效。此外,请仔细检查您在 Twilio 函数的环境变量中是否为 CHAT_SERVICE_SID
和 FLEX_FLOW_SID
设置了正确的 Sid。