Twilio chat client channels list - twilio

I am trying to create a simple chat app between 2 users, using twilio js api.
The idea is that I know that two users will have to chat with each other, and I want to create a channel specifically for the chat between them both.
So when a user logs in, I want to search the channel by it's name:
if it exist already, it means that the other user is already logged, and I want to join this channel.
else, I want to create a channel by this specific name, and wait for the other user.
I tried 2 alternatives:
1. chat client.
2. IPMessaging client.
I am trying to user this function:
chatClient.getChannels().then(function (channels){ // search for the channel I need // }
But for chat channel I get the following error:
twilio TypeError: chatClient.getChannels is not a function
So with an IPMessaging client it all works well, but I can't trigger events of user typing, which are important for my app:
chatChannel.on('typingStarted', function(){
console.log('user started typing')
});
chatChannel.on('typingEnded', function(){
console.log('user stopped typing')
});
Should this events be possible to trigger for IPMessaging Client?
If not, how can I get the channels list for a chat client?
Thank you

You can trigger typing indicators with IPMessaging (Programmable chat):
https://www.twilio.com/docs/api/chat/guides/typing-indicator
//intercept the keydown event
inputBox.on('keydown', function(e) {
//if the RETURN/ENTER key is pressed, send the message
if (e.keyCode === 13) {
sendButton.click();
}
//else send the Typing Indicator signal
else {
activeChannel.typing();
}
});
That same event can be triggered for members, and not only channels.
https://media.twiliocdn.com/sdk/js/chat/releases/0.11.1/docs/Member.html

Related

Twilio Send & Wait for Reply widget

I'm using an incoming call flow that starts call recording, asks a bunch of questions, gathers responses, at the end of the call: stops recording and sends a sms to caller using send/wait for reply widget. A response is expected and based on what's in the body of the incoming call, it calls a function.
All this works, except, I am not receiving a response back from the caller.
My concurrent call setting =off
incoming trigger = incoming call
the flow is tied to a phone number (voice)
I'm not sure how to get a reply back into the same flow. Do I need to attach something to the message section of the phone number?
Any guidance would be appreciated
A Studio flow execution represents one call, one SMS, or the incoming call trigger from the REST Trigger. As the call initiates your flow, it will terminate when the call ends.
But you can work around this by using a function that gets invoked when the recording is done. This function can then use the Twilio APIs to fetch contextual information from the call and trigger the REST API interface of the same flow (but with a different trigger).
I created a small example that does something similar:
The flow is triggered by a call, starts a recording, and gathers data
There is a recording callback URL that points to my function
// This is your new function. To start, set the name and path on the left.
exports.handler = function (context, event, callback) {
console.log(`Recording ${event.RecordingSid} state changed to ${event.RecordingStatus}.`)
if (event.RecordingStatus === "completed") {
const client = context.getTwilioClient();
return client.calls(event.CallSid).fetch()
.then(call => {
client.studio.v2.flows(<Flow ID>)
.executions
.create({
to: call.from,
from: <YOUR NUMBER>,
parameters: {
RecordingUrl: event.RecordingUrl,
}
})
.then(execution => {
console.log(`Triggered execution ${execution.sid}`)
return callback(null, "OK");
});
})
.catch(callback)
}
return callback(null, "OK");
};
You can find the ID of your flow in the console (or when you click on the root element and check the Flow Configuration):
The REST API triggers a second flow execution that reads the parameter and uses them to send a text message:

Twilio SWIFT API get consumed messages always returns 0

I want to display next to a chat channel the number of messages a channel has that have been unconsumed or unread (I assume this is what unconsumed means?)
Currently I send messages to a channel that two users are subscribed to , a private chat. Then before opening up the chat window I check the channel for unconsumed messages, but it always say 0 messages even if I call setNoMessagesConsumedWithCompletion.
I am using the Swift API...What do I need to do to find out how many messages in my channel have not been read yet? At what point do they become read? (when the user opens up a chat channel and requests to getLastWithCount?)
I read in the docs you have to set something called the consumption horizon to get unconsumed message, but I don't know how you do that in SWIFT API https://www.twilio.com/docs/chat/consumption-horizon also this was for Javascript API so perhaps it is easier with Swift Api?
I figured out the solution. As per the documentation you need to update the last consumed message index. So for example if the user has a chat window open you need to record for that user (or instance of the Chat Client) what was the last message they saw before they close their chat. I am storing all the messages in a message array and update the last consumed message index with the length of the array of messages:
generalChannel?.messages?.setLastConsumedMessageIndex(NSNumber.init(value: self.messages.count), completion: { (result, count) in
if !result.isSuccessful() {
print(result.error.debugDescription)
}
})
Then if you send messages to that channel when the user is not in the channel these will be recorded as unconsumed, you can get the number by calling:
channel.getUnconsumedMessagesCount(completion: { (results, numberUnconsumed) in
print(numberUnconsumed)
})

Zendesk Chat widget status check

I am using the Zendesk chat widget on my web portal. My requirement is whenever the widget goes down from server "Zendesk site" check the status and send notification to site owner.
On the research I found the $zopim.livechat.setOnStatus(callback); method. But the disadvantage of this gives only the offline and online status.
The "Status" that is checked with the callback function setOnStatus will only ever refer to the actual chat status rather than a technical health check status.
It's a little clunky, but if you're expecting the widget to load, but it doesn't due to the service being down, you could do a manual check after a given time, and have a reporting callback (Dummy function your_error_callback):
// Check Zopim (Zendesk Chat) status after 10 seconds
var ZopimHealthCheck = setInterval(function () {
if (window.$zopim === undefined || window.$zopim.livechat === undefined) {
your_error_callback("Zendesk Chat not available");
}
clearInterval(ZopimHealthCheck);
}, 10000);

Twilio Video - How to get current number of participants in a room?

I would like to know how many people are currently connected to a room when using Twilio Video.
Twilio has a REST API to get a room resource, but it does not return current number of participants.
https://www.twilio.com/docs/api/video/rooms-resource#get-by-sid
Only way i see is to subscribe to status callback to "participant connected" and disconnected events and manually keep track of how many participants are connected or left the room.
Is there a better way to do this ?
You can use twilio server side sdk, Let me share NodeJS example so you get better idea on implementation.
First lets define function that init twilio client and fetch connected participants of room.
async function getConnectedParticipants(roomName) {
var Twilio = require('twilio');
var apiKeySid = "YOUR_TWILIO_API_KEY_SID_HERE";
var apiKeySecret = "YOUR_TWILIO_API_SECRET_HERE";
var accountSid = "YOUR_TWILIO_ACCOUNT_SID_HERE";
var client = new Twilio(apiKeySid, apiKeySecret, {accountSid: accountSid});
var list = await client.video.rooms(roomName)
.participants
.list({status: 'connected'});
return list;
}
Now let's use our function that return you connected participants.
var connectedParticipants = await getConnectedParticipants("YourRoomName");
// print all connected participants
console.log('connectedParticipants', connectedParticipants);
Note: I have used async and await in this example, please check more on that before implementation.
Twilio developer evangelist here.
Keeping a server side list of the participants' identities based on the participant connected and disconnected events is probably the best way to work this out right now.
One alternative is to get this information from the front end. The JavaScript library allows you to query the participants in a room. You could periodically, or based on events, query that property and send it to your server via Ajax too.
Let me know if that helps.
Update
The Rooms API now allows you to retrieve information on participants that have connected to a room. To get the currently connected users in a room using Node.js, for example, the code would look like:
var client = new Twilio(apiKeySid, apiKeySecret, {accountSid: accountSid});
client.video.rooms(roomSid).participants
.list({status: 'connected'}, (err, participants) => {
if (err) { console.error(err); return; }
console.log(participants.length);
});

KIK Card - sending message directly

I'm building new KIK Card and i would like to create button which will send messages to 5 people selected from kik.pickUsers Is there any command that allow me to send messages directly, without pressing button "send"? This is my code:
cards.kik.pickUsers({
minResults: 5, // number >= 5
maxResults: 99 // number < 99
}, function (users) {
if (!users) {
return;
}
users.forEach(function (user) {
cards.kik.send(user.username, {
title: 'Message',
text: 'Text!!!'
});
});
});
Messages cannot be sent directly without user consent (via pressing the "send" button) - this is a tactic to avoid apps spamming content messages on behalf of the user.
Regarding sending to multiple people, as of this writing you can only send a message to a group if the conversation already exists in Kik.
Iterating over the array of users returned from the picker and trying to use kik.send() for each will only work for the first user in the array.
The Pop app on Kik has a good implementation to overcome this for inviting friends to use the app. This may or may not be relevant depending on what you are developing.

Resources