I have created a outbound sms from flex using this sms plugin . I can successfully send an outbound sms,and flex create a session and chat window for doing two way chat. While replying from this chat window its creating an out of session call to given webhook.
What is missing in the below function related to session while sending sms?
Question 2: is Channels API available in twilio-node yet?
the code that initiate the chat is as below , 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.ACCOUNT_SID,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 developer evangelist here.
The Flex Channels API is available in the Twilio Node library now. Make sure you install the latest twilio
package to your package.json and you can call it like:
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));
Perhaps try updating to the latest Twilio Node package, updating to use the above code and see if it still works. Also, double check you have the correct Sids set up for your CHAT_SERVICE_SID
and FLEX_FLOW_SID
in the environment variables for your Twilio Function.