Channels
Our channels enable developers to implement different types of chat messaging capabilities into their applications easily
Users can create and join channels where they will be able to participate and chat with other users. A channel can support up to 300,000 members and can contain an unlimited number of messages. Any message exchanged in the channels will be pushed to all other members of the channel in real-time.

Channel Model

When you are observing channels, it will always appear in this format.
1
{
2
"channelId": "string",
3
"isDistinct": true,
4
"metadata": {},
5
"type": "standard",
6
"tags": [
7
"string"
8
],
9
"isMuted": true,
10
"isRateLimited": true,
11
"muteTimeout": "2021-08-26T06:05:25.996Z",
12
"rateLimit": 0,
13
"rateLimitWindow": 0,
14
"rateLimitTimeout": "2021-08-26T06:05:25.996Z",
15
"displayName": "string",
16
"messageAutoDeleteEnabled": true,
17
"autoDeleteMessageByFlagLimit": 0,
18
"memberCount": 0,
19
"messageCount": 0,
20
"lastActivity": "2021-08-26T06:05:25.996Z",
21
"createdAt": "2021-08-26T06:05:25.996Z",
22
"updatedAt": "2021-08-26T06:05:25.996Z",
23
"avatar": {}
24
}
Copied!

Channel Description

Name
Data Type
Description
Attributes
channelId
String
ID of the channel
isDistinct
Boolean
Is channel distinct?
metadata
Object
Additional properties to support custom fields
type
String
Type of channel
Enum:[standard, private, conversation, broadcast, community, live]
tags
Array.<String>
Tags used for searching
isMuted
Boolean
Is this channel muted?
Computed by using muteTimeout
isRateLimited
Boolean
This channel has limited sending rate?
Computed by using muteTimeout
muteTimeout
string($date-time)
Date/time to disable mute
rateLimit
Integer
Number of messages within rate limit
rateLimitWindow
Integer
Waiting time interval before reseting rateLimit to 0
rateLimitTimeout
string($date-time)
Date/time to suppress limitation of sending rate
displayName
String
Channel name for displaying
messageAutoDeleteEnabled
Boolean
Will message in this channel be deleted when the user will flag until flag limit?
autoDeleteMessageByFlagLimit
Number
Number of flags that will force a message to be deleted automatically
memberCount
Integer
Number of members in channel
messageCount
Integer
Number of messages in channel
lastActivity
string($date-time)
Date/time of user's last activity related to the channel (E.g. add/remove member)
createdAt
string($date-time)
Date/time the channel was created
updatedAt
string($date-time)
Date/time the channel was last updated
avatar
Object
Data of the avatar

Channel Types

Amity's Chat SDK supports the creations of 4 types of chat channels. Each type is designed to match a particular use-case for chat channels. Here's a table showing what features each channel offers:
Channel Type
Discoverable by
Message sending privileges
Moderation access
Community
All users and admins
Users and admins
All Moderation tools
Live
Only members and admins
Users and admins
All Moderation tools
Broadcast
All users and admins
Admins
Admin Moderation tools
Conversation
Only members
Users
No Moderation tools

Community

All community channels are visible on the Amity Social Cloud Console.

The community channel is our default channel type and can be discovered by all users and admins. It acts as a public chat channel that showcases all of the features that our SDK's have to offer.
Typical use cases:
    Team collaboration
    Online gaming
    Celebrity fan club
    Live streaming
    Any type of public chat

Live

All live channels are visible on the Amity Social Cloud Console.

Live channels offers the ability for users and admins to create channels with exclusive memberships. The live channel is identical to our Community channel in features with the caveat that users will not be able to discover the channel when querying for all channels unless they are already a member of it. However users and admins can still invite other users to join the channel.
Typical use cases:
    Healthcare
    Project Discussion
    Any type of private chat
Community and Live channel types can use our SDK moderation tools:
    Message and user flagging
    Muting/Unmuting users
    Banning/Unbanning users from channel
    Profanity filters
    Whitelisted URLs
    User rate-limiting

Broadcast

All broadcast channels are visible on the Amity Social Cloud Console.
The Broadcast channel is heavily adopted by corporate users who constantly promote or advertise their products, or make the announcement to drive awareness. Unlike other channel types, broadcast channels only allow admin users to send messages from Console, and everyone else in the channel will be under read-only mode.
Since this is a one-way communication channel, a tailored moderation tools are provided as well, for instance, users won't be able to flag message / user in the channel.
Typical use cases:
    Marketing & Advertising
    School / Government Announcements

Conversation

Conversation channels are NOT visible on the Amity Social Cloud Console.
The Conversation channel is our solution to 1-on-1 messaging. Unlike the other channel types, a Conversation channel can be created simply by knowing the userId of the user we want to converse with. Users can start conversations with any other user and only they will be able to see their conversation.
There are no moderation tools for Conversation channels, users will be able to converse freely with no oversight!
Typical use cases:
    Hospitality
    Financial Consultancy
    Customer Support
Since this is similar to 1-on-1 messaging, Conversation channels have some limitations. The following are not allowed:
    Join and leave channel
    Ban and unban channel members
    Add and remove channel members

Channel Members

When a user joins a channel, they are able to observe and chat with other users in that channel. They are also automatically considered a member of that channel. The Chat SDK provides the ability to view which users are currently in the channel as well as invite other users to join the channel.
Channel Type
Discoverable by
Message sending privileges
Moderation access
Community
All users and admins
Users and admins
All Moderation tools
Live
Only members and admins
Users and admins
All Moderation tools
Broadcast
All users and admins
Admins
Admin Moderation tools
Conversation
Only members
Users
No Moderation tools
Each channel is identified by an unique channelId, which is any string that uniquely identifies the channel and is immutable through its lifetime. When creating channels, you can specify your own channelId, or leave it to Amity's Chat SDK to automatically generate one for you.
There can be only one and one only channel with a given channelId: an error will be thrown when trying to generate two channels with the same channelId.
There are three ways of obtaining a channel: via create, join, or get. They all return a LiveObject with the complete channel model. However, createChannel: guarantees that the requested channel is a new channel, whereas joinChannel: will attempt to join an existing channel. If there is a requirement to create a new channel, then use of createChannel: then call joinChannel:. Lastly calling getChannel: only gives you back the channel LiveObject, but it won't make the current user join said channel.
Channel management methods are contained in a ChannelRepository class. Before being able to call any channel method, you must initialize a repository instance using the ASCClient instance you created on setup:
1
import { ChannelRepository } from '@amityco/js-sdk';
2
const channelRepo = new ChannelRepository();
Copied!

Create Channel

ChannelRepository provides createChannel() method to create a new channel. It supports creating of 3 types of channels Community, Live and Conversation. Each channel type has specific builder classes which helps you to create that particular channel. Build your channel information first and then create the particular channel.
1
import { ChannelType } from '@amityco/js-sdk';
2
3
const liveChannel = channelRepo.createChannel({
4
channelId: 'channel1',
5
type: ChannelType.Standard,
6
userIds: [ 'user1', 'user2' ],
7
})
8
.catch(err => {
9
// Handle channel create error (non-unique channelID)
10
});
11
12
liveChannel.once('dataUpdated', model => {
13
console.log(`Channel created: ${model.channelId}`);
14
});
Copied!
The above code creates a channel and notifies you through observer block. It first instantiates the ChannelRepository, a class that contain all channel related methods. Then it calls createChannel: to obtain the LiveObject and observe it in order to obtain the final channel model.
The NotificationToken returned by the observe: is saved in self.channelToken, a strongly referenced property. This is needed in order to prevent the observe block to be released. Observe block can get called multiple time, when the underlying data for the channel updates. If you don't want to get notified, you can call channelToken.invalidate(). As soon as the token gets invalidated, observer is automatically removed from that channel.
In the case that there is already an existing channel with the same channelID, the LiveObject will notify you with an error object.
The channelId parameter in createChannel: can be nil: when this happens, the SDK will generate an unique channelId for this channel, ensuring no unique ID conflicts.
3 channel types can be created through SDK i.e Community, Live and Conversation. Creation of Private and Standard type has been removed. Creation of Broadcast channel type is not supported through the SDK. But for query, channelCollection: method supports all channel types including Broadcast, Private and Standard.

Create Conversation:

The Chat SDK provides a convenient method which creates a conversation channel type.
1
import { ChannelType } from "@amityco/js-sdk"
2
3
createChannel({ type: ChannelType.Conversation })
Copied!
Conversation channel is unique based on its membership. When creating conversation the system will check if channel with the same membership already exists, if such channel already exists the system will return existing channel instead of creating a new one.

Join Channel

1
const liveChannel = channelRepo.joinChannel({
2
channelId: 'channel2',
3
type: ChannelType.Standard,
4
});
5
6
liveChannel.once('dataUpdated', data => {
7
...
8
});
Copied!
joinChannel: is an idempotent method, this means it can be called multiple times throughout the lifecycle of the application, and you can expect this method to always return the same channel. Because of this, you can also use joinChannel: any time you need to fetch a channel, even if you know the user may already be in the channel.

Get Channel

In the case where you'd like to fetch a channel's data without joining, the getChannel: method can be used:
1
const liveChannel = channelRepo.channelForId('channel3');
2
3
liveChannel.once('dataUpdated', data => {
4
...
5
});
Copied!

Channel Query

ChannelRepository provides a way to query list of channels using channelCollection() method. It returns aLiveCollection of all the matching channels available. This live collection returned will automatically update and notify you on any channel modifications.
Deprecated: channelsForFilter(),channelsForFilter(_:includingTags:excludingTags:) method to query channels is now depreciated. SDK now doesnot support creation of Private & Standard channels but still supports query using EkoStandardChannelQueryBuilder EkoPrivateChannelQueryBuilder.
1
const channels = channelRepo.allChannels();
2
3
channels.on('dataUpdated', models => {
4
// reload data
5
});
6
7
// unobserve data changes once you are finished
8
channels.removeAllListeners('dataUpdated');
Copied!
If you use a UITableView or UICollectionView to display channel list data, the ideal location to reload table data is directly in the observe block of the LiveObject that you are displaying, as shown in the example above.

Channel Filtering

You can filter channels by various criteria such as includingTags, excludingTags, includeDeleted channels etc. All these filters are available in QueryBuilder classes for channel.

Metadata

Metadata is a general purpose data store that is automatically synchronized to all the channel members. It is meant as an elegant mechanism to store contextual information about a specific channel. The data can be any number of JSON key value pairs up to 100 kb. Example use cases include:
    Conversation title or cover photo
    Global conversation settings
Metadata is implemented with last writer wins semantics: multiple mutations by independent users to the metadata object will result in a single stored value. No locking, merging, or other coordination is performed across multiple writes on the data.
To set metadata, call the setMetadataForChannel: method:
1
channelRepo.setMetadata({
2
channelId: 'channel1',
3
metadata: { hello: 'world' },
4
})
5
.then(() => {
6
// success
7
}).catch(error => {
8
console.log('Metadata set fail');
9
});
Copied!
The completion block will be triggered with the outcome of the request. The latest metadata of the channel is always exposed as part of the metadata property on the channel model.

Display Name

Every channel contains an optional displayName property. This property is mainly used to identify the channel in push notifications, but it is also exposed to the application via Channel object.
You can set a channel's displayName with the following method:
1
channelRepo.setDisplayName({
2
channelId: 'channel1',
3
displayName: 'Channel Eko',
4
})
5
.then(() => {
6
// success
7
}).catch(error => {
8
// handle error
9
});
Copied!
An optional completion callback is available to inform you on whether the request has succeeded or not.

Participation

All participation related methods in a channel falls under a separate ChannelParticipation class. Before calling any participation methods, you must ensure to first instantiate a repository instance using the ASCClient instance you created on setup and a valid channelId:
1
import { ChannelMembershipRepository } from '@amityco/js-sdk';
2
const channelMembershipRepo = new ChannelMembershipRepository('channel1');
Copied!
Also you can access a ChannelMembershipRepository instance by the membership property of a channel LiveObject model:
1
const channelMembershipRepo = liveChannel.model.membership;
Copied!

Members Query

The participation membership provides a list of all members in the given channel as a LiveObject.
1
const members = channelMembershipRepo.members();
2
members.on('dataUpdated', models => {
3
// reload member table
4
});
5
6
// unobserve data changes once you are finished
7
members.removeAllListeners('dataUpdated');
Copied!

Manage Members

The participation membership also provides classes to add and remove members, as well as removing yourself as a member of the channel (leaving the channel).
1
// add 'user1' and 'user2' to this channel
2
channelMembershipRepo.addMembers({
3
userIds: [ 'user1', 'user2' ],
4
})
5
.then(() => {
6
// success
7
}).catch(error => {
8
// handle error
9
});
10
11
// remove 'user3' from this channel
12
channelMembershipRepo.removeUsers({
13
userIds: [ 'user3' ],
14
})
15
.then(() => {
16
// success
17
}).catch(error => {
18
// handle error
19
});
20
21
// leave this channel
22
channelMembershipRepo.leave().catch(error => { ... });
Copied!

Reading Status And Unread Count

The ChannelRepository object exposes an totalUnreadCount property that reflects the number of messages that the current user has yet to read. This count is the sum of all the unreadCount channels properties where the user is already a member.
1
console.log(channelMembership.unreadCount) // 0
Copied!
To let the server know when the current user is reading one channel, hence resetting that channel unreadCount to zero, the participation membership exposes the startReading and stopReading methods.
You can call both methods as much you want, the SDK takes care of multi-device management: therefore a user can read multiple channels, from one or multiple devices at once. In case of an abrupt disconnection (whether because the app was killed, or the internet went down etc) the SDK backend will automatically call the stopReading on the user behalf.
1
// start reading a channel
2
ChannelMembershipRepository.startReading()
3
4
// stop reading a channel
5
ChannelMembershipRepository.stopReading()
Copied!

Moderation

ChannelModeration class provides various methods to moderate the users present in channel. You can ban/unban/mute users, assign roles or remove it from user.

Permission

You can check your permission in channel using hasPermission(permission:forChannel:_:) method from the ASCClient
Last modified 25d ago