Messaging

This page highlights the steps you will need to follow to begin integrating chat messaging into your products

The message payload is always the same regardless of which Development Kit the user is using. Users also have a choice on what type of message they want to send.‌

Message Types

Amity supports the sending and receiving of 5 types of messages. They are Text, Image, Audio, File, and Custom.

Image

Amity will automatically optimize the image and when queried, will return the image in small, medium and large sizes. If the image is marked as isFull on upload, the original size of the image can also be returned.

Specifications on image size

When an image is uploaded, it is automatically resized into multiple sizing options. The size of the image is determined by its longest dimension (in pixels) with the aspect ratios being unchanged.

The maximum file size of an image cannot exceed 1 GB.‌

Message Format

When a user is observing messages, the message will always appear in this format.

{
  "status": "string",
  "data": {
    "messages": [
      {
        "messageId": "string",
        "parentId": "string",
        "childrenNumber": 0,
        "channelId": "string",
        "userId": "string",
        "type": "string",
        "tags": [
          "string"
        ],
        "data": {
            "text": "string"
        },
        "isDeleted": true,
        "channelSegment": 0,
        "createdAt": "2020-01-02T06:54:59.244Z",
        "updatedAt": "2020-01-02T06:54:59.244Z",
        "editedAt": "2020-01-02T06:54:59.244Z",
        "flagCount": 0,
        "hashFlag": {
          "bits": 0,
          "hashes": 0,
          "hash": [
            0
          ]
        },
        "reactions": {
            "reactionName": 1,
        },
        "reactionsCount": 0,
        "myReactions": [
          "string"
        ]
      }
    ],
    "users": [
      {
        "userId": "string",
        "roles": [
          "string"
        ],
        "displayName": "string",
        "flagCount": 0,
        "metadata": {},
        "hashFlag": {
          "bits": 0,
          "hashes": 0,
          "hash": [
            0
          ]
        },
        "createdAt": "2020-01-02T06:54:59.244Z",
        "updatedAt": "2020-01-02T06:54:59.244Z"
      }
    ]
  }
}

Messages Description

Name

Data Type

Description

Attributes

messageId

string

The id of this message

​Content

parentId

string

The messageId of the parent of this message

​Content

childrenNumber

integer

The number of messages with parentId of this message

​Content

channelId

string

The name of the channel this message was created in

​Content

userId

string

The name of the user this message was created by

​Content

type

string

The message type

enum*: text custom image file

tags

Array.<string>

The message tags

​Content

data

Object

The message data (any text will be stored in text key)

text: Text message

isDeleted

boolean

The message has been marked as deleted

​Content

channelSegment

integer

The sequence number of a message in channel

​Content

createdAt

date

The date/time the message was created at

​Content

updatedAt

date

The date/time the message was updated at

​Content

editedAt

date

The date/time the message was edited at

​Content

flagCount

integer

The number of users that have flagged this message

​Content

hashFlah

Object

A hash for checking internally if this message was flagged by the user

​Content

reactions

Object

The reaction data (stored as a reactionName and counter key/value pair)

Example: { like: 1, dislike: 2 }

reactionsCount

integer

The total number of reactions on this message

​Content

myReactions

Array.<string>

A list of user's reactions on this message

​Content

Messages are JSON content containers that can weigh up to 100KB and will be synchronized among all channel users in real-time. If a message requires larger binary data (such as when sending files), we recommend to upload the data to another cloud storage service, such as AWS S3, and store the URL to the content in the message data.

In addition the JSON message type, the SDK also provides support for common text and image message types. These additional types are built on top of the standard JSON message layer.

In case of image messages, the SDK freely provides a cloud storage service that will process and store all images uploaded: you don't need to setup and manage a separate cloud storage service for this common case.

All messaging methods are contained in a EkoMessageRepository class. Before calling any messaging methods, you must ensure to first instantiate a repository instance using the EkoClient instance you created on setup.

import { MessageRepository } from 'eko-sdk';
const messageRepo = new MessageRepository();

Sending Messages

All message sending methods are designed to be robust enough to work under any network conditions. When you send any message, that message will automatically be put into a queue incase of any unforeseen unstable network conditions. Once the SDK reconnects to the server, it will automatically resend all the queued messages.

Additionally, sent messages are always returned in message queries, even before they have been delivered to the server. This provides the user with a fluid messaging flow: when a user sends a message, that sent message will appear in the message stream right away (instead of waiting until it has been confirmed by the server). To check or display the current status of message delivery for your application, use the syncState property in the message model; for web you should useEkoMessage.getState() method in the EkoMessage object.

Text Messages

Initiate the messaging with the following scripts, depending on your platform of choice

const messageLiveObject = messageRepo.createTextMessage({
  channelId: 'channel1',
  text: 'Hello World!',
});

Message Query

To query for a list of all messages in a channel:

import { MessageRepository } from 'eko-sdk';

const messageRepo = new MessageRepository();
const messages = messageRepo.messagesForChannel({ channelId: 'channel1' });

messages.on('dataUpdated', data => {
  // reload messages table
});

messages.on('dataError', error => {
  console.log('Message LiveCollections can not query/get/sync data from server');
});

// unobserve data changes once you are finished
messages.removeAllListeners('dataUpdated');
messages.removeAllListeners('dataError');

This method will return a LiveCollection of all messages in the specified channel. You can observe the LiveCollection in order to update your view whenever you receive new messages.

Since v1.3.0, messages can be organized in threads thanks to the parentId property.

Threaded Messages

A message can be the root for a thread. To query the children of a message thread, you can add the parentId parameter in a message query, along with the filterByParentId flag.

import { MessageRepository } from 'eko-sdk';

const messageRepo = new MessageRepository();
const messages = messageRepo.messagesForChannel({
  channelId: 'channel1',
  parentId: 'exampleParentMessageId',
  filterByParentId: true,
});

When creating a message, we can also pass the parentId to make it appear under a parent.

const messageLiveObject = messageRepo.createTextMessage({
  channelId: 'channel1',
  text: 'Hello World!',
  parentId: 'exampleParentMessageId,
});

Flag & Unflag Messages

Users can flag messages and unflag messages that they have flagged using the MessageFlagRepository class.

import { MessageFlagRepository } from 'eko-sdk';
const flagRepo = new MessageFlagRepository('message1');

To flag a message, call the following method:

flagRepo.flag()

To unflag a message, call the following method:

flagRepo.unflag()

The User can also check if they have previously flagged the message before by calling the following asynchronous method:

const result = await flagRepo.isFlaggedByMe()

If this method has been called before in the current session, the user can also check the cached result on the message payload itself.

// Note. If the value is undefined, it means the data has not been cached
message.isFlaggedByMeCache

Editing Messages

A special MessageEditorRepository class is also provided for you to perform actions on messages you've sent or received. These actions include editing and deleting an existing message, as well as marking a message as being read by you.

To start, first instantiate a MessageEditor instance with the EkoClient instance you created on setup, as well as a valid messageId.

import { MessageEditorRepository } from 'eko-sdk';
const editor = new MessageEditorRepository('message1');

Edit and Delete

You can only perform edit and delete operations on your own messages. Once the operation is complete, the message's editedAtDate will be set to the current time. This allows you to provide UI to the user to inform the user of specific messages that has been edited, if needed. An optional completion block can be provided to notify you of operation success.

// edit current message with new text
editor.editText('New edited text').catch(error => {
  ...
});

// delete current message
editor.delete().catch(error => {
  ...
});

Mark Message as Read

To mark a message as being read by you, simply call the following method with an optional completion block:

editor.markRead().catch(error => {
  ...
});

Marking a message as read will also retroactively mark all previous messages as read by you as well. You will only need to call this method once on the latest message.

Last updated