Skip to contentSkip to navigationSkip to topbar
Rate this Page:

Channels and Messages


(error)

Danger

Programmable Chat has been deprecated and is no longer supported. Instead, we'll be focusing on the next generation of chat: Twilio Conversations. Find out more about the EOL process here(link takes you to an external page).

If you're starting a new project, please visit the Conversations Docs to begin. If you've already built on Programmable Chat, please visit our Migration Guide to learn about how to switch.

In a Programmable Chat application, a Channel is where all the action happens. Whether a chat is between two users or two hundred, a Channel is where messages are sent, received, and archived for later viewing by offline clients.

Programmable Chat has two objects for working with channels - Channel Descriptors and Channels. A Channel Descriptor is a lightweight representation of the key attributes of a public or private channel. When requesting a list of channels, you will receive Channel Descriptors that serve as a snapshot in time for each channel. These channel attributes will not update if modified remotely, so you should use the descriptors only to assist your user in discovering and joining a channel.

Channel Descriptors can be used to obtain a full channel object or view the following information:

  • Channel SID
  • Friendly Name
  • Unique Name
  • Date Created
  • Created By
  • Date Updated
  • Channel Attributes
  • Messages and Members Count
  • Last Consumed Message Index (if available)
  • Status (if available)
  • Type (private or public)

A full Channel object allows you to join and interact with the channel. Let's dive into a few of the key techniques you'll need to employ while working with channels and messages in your application.


List Public Channel Descriptors

list-public-channel-descriptors page anchor

If your programmable chat instance has public channels that are discoverable by a user, you can fetch a list of Channel Descriptors for all public channels in the system:

List Public Channels

list-public-channels page anchor
Node.js
Java
Objective-C
Swift

_10
chatClient.getPublicChannelDescriptors().then(function(paginator) {
_10
for (i = 0; i < paginator.items.length; i++) {
_10
const channel = paginator.items[i];
_10
console.log('Channel: ' + channel.friendlyName);
_10
}
_10
});


List User Channel Descriptors

list-user-channel-descriptors page anchor

If your programmable chat instance has user channels that the current user belongs to, you can fetch a list of User Channel Descriptors for this user. To list public channels that have not yet been joined, see list public channels above.

List the Channels for a User

Node.js
Java
Objective-C
Swift

_10
chatClient.getUserChannelDescriptors().then(function(paginator) {
_10
for (i=0; i<paginator.items.length; i++) {
_10
var channel = paginator.items[i];
_10
console.log('Channel: ' + channel.friendlyName);
_10
}
_10
});


Get A Channel from a Channel Descriptor

channel-from-channel-descriptor page anchor

After you have retrieved a list of channel descriptors, you will typically want to get a specific Channel and interact with it directly. In the following example, you can see how. Note that this is not necessary for the Javascript Chat SDK as the client.getChannel() gets the channel descriptor and instantiates the channel internally for you.

Get A Channel from a Channel Descriptor

get-a-channel-from-a-channel-descriptor page anchor
Java
Objective-C
Swift

_10
channelDescriptor.getChannel(new CallbackListener<Channel>() {
_10
@Override
_10
public void onSuccess(Channel channel) {
_10
Log.d(TAG, "Channel Status: " + channel.getStatus());
_10
}
_10
});


Before you can start sending messages, you first need a Channel that can receive messages. Here is how you create a channel.

Node.js
Java
Objective-C
Swift

_10
// Create a Channel
_10
chatClient
_10
.createChannel({
_10
uniqueName: 'general',
_10
friendlyName: 'General Chat Channel',
_10
})
_10
.then(function(channel) {
_10
console.log('Created general channel:');
_10
console.log(channel);
_10
});


Once you've created a channel, a user must join it to begin receiving or sending messages on that channel.

Node.js
Java
Objective-C
Swift

_10
// Join a previously created channel
_10
client.on('channelJoined', function(channel) {
_10
console.log('Joined channel ' + channel.friendlyName);
_10
});
_10
_10
myChannel.join().catch(function(err) {
_10
console.error(
_10
"Couldn't join channel " + channel.friendlyName + ' because ' + err
_10
);
_10
});


Send Messages to a Channel

send-messages-to-a-channel page anchor

Once you're a member of a channel, you can send a message to it.

A message is a bit of data that is sent first to the Twilio backend where it is stored for later access by members of the channel. The message is then pushed out in real time to all channel members currently online. Only users subscribed to your channel will receive your messages.

Node.js
Java
Objective-C
Swift

_10
// Send a message to a previously created Channel
_10
const msg = $('#chat-input').val();
_10
myChannel.sendMessage(msg);

Today, a message is just a string of text. Available in beta you can also send other media types, like images and binary data.


Get the Most Recent Messages from a Channel

get-the-most-recent-messages-from-a-channel page anchor

With a channel object in hand, you can fetch the most recent messages from the channel. Use this to provide history within the channel. You can choose how many messages you want to retrieve.

(information)

Info

Note: The Message index property may increment by more than 1 between messages. These indices will be ordered by when the message was received and you should use the index property to order them in your UI.

Get Most Recent Messages

get-most-recent-messages page anchor
Node.js
Java
Objective-C
Swift

_10
// Get Messages for a previously created channel
_10
channel.getMessages().then(function(messages) {
_10
const totalMessages = messages.items.length;
_10
for (i = 0; i < totalMessages; i++) {
_10
const message = messages.items[i];
_10
console.log('Author:' + message.author);
_10
}
_10
console.log('Total Messages:' + totalMessages);
_10
});

You can also be notified of any new incoming messages with an event handler. Use this handler to update your user interface to display new messages.

Listening for New Messages

listening-for-new-messages page anchor
Node.js
Java
Objective-C
Swift

_10
// Listen for new messages sent to a channel
_10
myChannel.on('messageAdded', function(message) {
_10
console.log(message.author, message.body);
_10
});


Invite other Users to a Channel

invite-other-users-to-a-channel page anchor

Sometimes you might feel lonely in a channel. Rather than sending messages to yourself, invite a friend to come and chat! It doesn't matter if the channel is public or private - you are always able to invite another user to any channel you own.

Node.js
Java
Objective-C
Swift

_10
// Invite another member to your channel
_10
myChannel.invite('elmo').then(function() {
_10
console.log('Your friend has been invited!');
_10
});


Accept an Invitation to a Channel

accept-an-invitation-to-a-channel page anchor

Social acceptance is a great feeling. Accepting an invite to a channel means you too can partake in banter with other channel members.

Node.js
Java
Objective-C
Swift

_10
// Listen for new invitations to your Client
_10
chatClient.on('channelInvited', function(channel) {
_10
console.log('Invited to channel ' + channel.friendlyName);
_10
// Join the channel that you were invited to
_10
channel.join();
_10
});


Get a List of Subscribed Channels

get-a-list-of-subscribed-channels page anchor

Listing subscribed channels lets you perform actions on them as a channel member (e.g., invite or display). This method only shows the channels where the current programmable chat user is a member. To list public channels that have not yet been joined, see list public channels above.

Node.js
Java
Objective-C
Swift

_10
chatClient.getSubscribedChannels().then(function(paginator) {
_10
for (i = 0; i < paginator.items.length; i++) {
_10
const channel = paginator.items[i];
_10
console.log('Channel: ' + channel.friendlyName);
_10
}
_10
});


Subscribe for Channel Events

subscribe-for-channel-events page anchor

Channels are a flurry of activity. Members join and leave, messages are sent and received, and channel states change. As a member of a channel, you'll want to know the status of the channel. You may want to receive a notification when the channel is deleted or changed. Channel event listeners help you do just that.

These event listeners will notify your app when a channel's state changes. Once you receive the notification, you can perform the necessary actions in your app to react to it.

Node.js
Java
Objective-C
Swift

_12
// A channel has become visible to the Client
_12
chatClient.on('channelAdded', function(channel) {
_12
console.log('Channel added: ' + channel.friendlyName);
_12
});
_12
// A channel is no longer visible to the Client
_12
chatClient.on('channelRemoved', function(channel) {
_12
console.log('Channel removed: ' + channel.friendlyName);
_12
});
_12
// A channel's attributes or metadata have changed.
_12
chatClient.on('channelUpdated', function(channel) {
_12
console.log('Channel updates: ' + channel.sid);
_12
});

Your event listeners will also notify your app when channel members perform some action (including when they leave, join, change, or start/stop typing). Using these listeners, you can provide real-time updates to your application users.

Node.js
Java
Objective-C
Swift

_20
// Listen for members joining a channel
_20
myChannel.on('memberJoined', function(member) {
_20
console.log(member.identity + 'has joined the channel.');
_20
});
_20
// Listen for members user info changing
_20
myChannel.on('memberInfoUpdated', function(member) {
_20
console.log(member.identity + 'updated their info.');
_20
});
_20
// Listen for members leaving a channel
_20
myChannel.on('memberLeft', function(member) {
_20
console.log(member.identity + 'has left the channel.');
_20
});
_20
// Listen for members typing
_20
myChannel.on('typingStarted', function(member) {
_20
console.log(member.identity + 'is currently typing.');
_20
});
_20
// Listen for members typing
_20
myChannel.on('typingEnded', function(member) {
_20
console.log(member.identity + 'has stopped typing.');
_20
});


Deleting a channel both deletes the message history and removes all members from it.

Node.js
Java
Objective-C
Swift

_10
// Delete a previously created Channel
_10
myChannel.delete().then(function(channel) {
_10
console.log('Deleted channel: ' + channel.sid);
_10
});

You can only delete channels that you have permissions to delete. Deleting a channel means it cannot be retrieved at a later date for any reason. Delete with caution!

Now that you know all there is to know about channels, might we suggest learning more about the REST API? With the REST API, you can execute many of these same actions from your server-side code.

Next: Media Support in Chat


Rate this Page: