CometChat Pro Documentation

You'll find comprehensive guides and documentation to help you start working with CometChat as quickly as possible. Let's jump right in!

Messaging

Send a Text Message

To send a text message to any particular user or group, you need to use the sendMessage() method provided by the CometChat class.

var receiverID = "UID";
var messageText = "Hello world!";
var messageType = CometChat.MESSAGE_TYPE.TEXT;
var receiverType = CometChat.RECEIVER_TYPE.USER;

var textMessage = new CometChat.TextMessage(receiverID, messageText, messageType, receiverType);

CometChat.sendMessage(textMessage).then(
  message => {
    console.log("Message sent successfully:", message);
    // Text Message Sent Successfully
  },
  error => {
    console.log("Message sending failed with error:", error);
  }
);
var receiverID = "GUID";
var messageText = "Hello world!";
var messageType = CometChat.MESSAGE_TYPE.TEXT;
var receiverType = CometChat.RECEIVER_TYPE.GROUP;

var textMessage = new CometChat.TextMessage(receiverID, messageText, messageType, receiverType);

CometChat.sendMessage(textMessage).then(
  message => {
    console.log("Message sent successfully:", message);
    // Text Message Sent Successfully
  },
  error => {
    console.log("Message sending failed with error:", error);
  }
);

To send a message you need to create an object of the TextMessage class. The constructor of the TextMessage class takes the following mandatory parameters:

Parameter
Description

receiverID

The UID or GUID of the recipient

messageText

The text message to be sent

messageType

The type of the message that needs to be sent which in this case is MESSAGE_TYPE.TEXT (text)

receiverType

The type of the receiver to whom the message is to be sent i.e RECEIVER_TYPE.USER (user) or RECEIVER_TYPE.GROUP (group)

On success, you will receive an object of the TextMessage class containing all the information related to the sent text message.

Send Media Message

To send a media message to any user or group, you need to use the sendMediaMessage() method.

Getting file object.

<body>
    <input type="file" name="img_file" id="img_file" />
    <script>
      var mediaMessage=new MediaMessage("SUPERHERO2", document.getElementById('img_file').files[0], MESSAGE_TYPE.IMAGE, RECEIVER_TYPE.USER);
    </script>
</body>
  
var receiverID = "UID";
var messageType = CometChat.MESSAGE_TYPE.FILE;
var receiverType = CometChat.RECEIVER_TYPE.USER;

var mediaMessage = new CometChat.MediaMessage(receiverID, `INPUT FILE OBJECT`, messageType, receiverType);

CometChat.sendMediaMessage(mediaMessage).then(
 message => {
  // Message sent successfully.
  console.log("Media message sent successfully", message);
 },
 error => {
  console.log("Media message sending failed with error", error);
  // Handle exception.
 }
);
var receiverID = "GUID";
var messageType = CometChat.MESSAGE_TYPE.FILE;
var receiverType = CometChat.RECEIVER_TYPE.GROUP;

var mediaMessage = new CometChat.MediaMessage(receiverID, `INPUT FILE OBJECT`, messageType, receiverType);

CometChat.sendMediaMessage(mediaMessage).then(
 message => {
  // Message sent successfully.
  console.log("Media message sent successfully", message);
 },
 error => {
  console.log("Media message sending failed with error", error);
  // Handle exception.
 }
);

To send a media message you need to create an object of the MediaMessage class. The constructor of the MediaMessage class takes the following mandatory parameters:

Parameter
Description

receiveID

The UID or GUID of the recipient

messageType

The message types can be one of the below values and can be obtained from

  • CometChat.MESSAGE_TYPE.IMAGE

  • CometChat.MESSAGE_TYPE.VIDEO

  • CometChat.MESSAGE_TYPE.AUDIO

  • CometChat.MESSAGE_TYPE.FILE

receiverType

The type of the receiver to whom the message is to be sent i.e

  • CometChat.RECEIVER_TYPE.USER

  • CometChat.RECEIVER_TYPE.GROUP

file

The file object to be sent

On success, you will receive an object of the MediaMessage class containing all the information related to the sent media message.

Send Custom Message

CometChat SDK allows you to send a completely custom message across. You can use this feature to send messages that do not fit in any default categories provided. In order to send a custom message, you need to use the sendCustomMessage() method.

The sendCustomMessage() methods takes an object of the CustomMessage class which can be created using the constructor which takes the following parameters:

Parameter
Information

receiverId

Unique identifier of the user or the group to which the message is to be sent.

receiverType

The type of the receiver to whom the message is to be sent i.e

  • CometChat.RECEIVER_TYPE.USER

  • CometChat.RECEIVER_TYPE.GROUP

customData

This parameter is a JSON object where you can put in all the data that needs to be shared.

var receiverID = "UID";
var messageType = CometChat.MESSAGE_TYPE.CUSTOM;
var customData= {
  customField:YOUR_CUSTOM_VALUE"
}
var receiverType = CometChat.RECEIVER_TYPE.USER;

var customMessage = new CometChat.CustomMessage(receiverID, receiverType,customData);

CometChat.sendCustomMessage(customMessage).then(
 message => {
  // Message sent successfully.
  console.log("custom message sent successfully", message);
 },
 error => {
  console.log("custom message sending failed with error", error);
  // Handle exception.
 }
);
var receiverID = "GUID";
var messageType = CometChat.MESSAGE_TYPE.CUSTOM;
var customData= {
  yourCustomFiled:YOUR_CUSTOM_VALUE"
}
var receiverType = CometChat.RECEIVER_TYPE.GROUP;

var cutomMessage = new CometChat.CustomMessage(receiverID, customData, receiverType);

CometChat.sendCustomMessage(cutomMessage).then(
 message => {
  // Message sent successfully.
  console.log("custom message sent successfully", message);
 },
 error => {
  console.log("custom message sending failed with error", error);
  // Handle exception.
 }
);

The above sample explains how custom messages can be used to share the location with a user. The same can be achieved for groups.

In success, you will receive an object of the CustomMessage class

Send Custom Data along with a Message

To send custom data along with either a text or a media message, you can use the metadata field provided in both TextMessage and MediaMessage class. The metadata field is a JSONObject which will be received as it was sent without any processing from the CometChat. It can be used to send any additional data that needs to be sent along with a message.

var receiverID = "UID";
var messageText = "Hello World!";
var messageType = CometChat.MESSAGE_TYPE.TEXT;
var receiverType = CometChat.RECEIVER_TYPE.USER;

var textMessage = new CometChat.TextMessage(receiverID, messageText, messageType, receiverType);

var metadata = {
 latitude: "50.6192171633316",
 longitude: "-72.68182268750002"
};

textMessage.setMetadata(metadata);

CometChat.sendMessage(textMessage).then(
 message => {
  console.log("Message sent successfully:", message);
  // Message sent successfully
 },
 error => {
  console.log("Message sending failed with error:", error);
  // Handle any error
 }
);

Custom data can be sent similarly for media messages (as well as to groups).

Receive Messages

To receive real-time incoming messages, need to register the MessageListener wherever you wish to receive the incoming messages.
You can use the addMessageListener() method to do so.

var listenerID = "UNIQUE_LISTENER_ID";

CometChat.addMessageListener(
 listenerID,
 new CometChat.MessageListener({
  onTextMessageReceived: textMessage => {
   console.log("Text message received successfully", textMessage);
   // Handle text message
  },
  onMediaMessageReceived: mediaMessage => {
   console.log("Media message received successfully",  mediaMessage);
   // Handle media message
  },
   onCustomMessageReceived: customMessage => {
   console.log("Custom message received successfully",  customMessage);
   // Handle custom message
  }
   
 })
);
Parameter
Description

listenerID

An ID that uniquely identifies that listener. We recommend using the activity or fragment name

We recommend you remove the listener once you don't want to receive a message for particular listener.

var listenerID = "UNIQUE_LISTENER_ID";

CometChat.removeMessageListener(listenerID);

Edit Message

In order to edit a message, you can use the editMessage() method. This method takes an object of the BaseMessage class. At the moment, you are only allowed to edit TextMessage and CustomMessage. Thus, the BaseMessage object must either be a Text or a Custom Message.

let receiverID = "RECEIVER_UID";
let messageText = "Hello world!";
let messageType = CometChat.MESSAGE_TYPE.TEXT;
let receiverType = CometChat.RECEIVER_TYPE.USER

let messageId = "MESSAGE_ID_OF_THE_MESSAGE_TO_BE_EDITED";
let textMessage = new CometChat.TextMessage(receiverID, messageText, messageType, receiverType);

textMessage.setId(messageId);
CometChat.editMessage(textMessage).then(
    message => {
        console.log("Message Edited", message);
    },
    error => {
        console.log("Message editing failed with error:", error);
    }
);

The object of the edited message will be returned in the Promise resolved callback method of the listener. The message object will contain the editedAt field set with the timestamp of the time the message was edited. This will help you identify if the message was edited while iterating through the list of messages. The editedBy field is also set to the UID of the user who edited the message.

In order to receive real-time events for message being edited, you need to override the onMessageEdited() method of the MessageListener class.

var listenerID = "UNIQUE_LISTENER_ID";

CometChat.addMessageListener(
    listenerID,
    new CometChat.MessageListener({
        onMessageEdited: message => {
            console.log("Edited Message", message);            
        }
    })
);

Delete Message

In case you have to delete a message, you can use the deleteMessage() method. This method takes the message ID of the message to be deleted.

let messageId="ID_OF_THE_MESSAGE_YOU_WANT_TO_DELETE";

CometChat.deleteMessage(messageId).then(
    message => {
        console.log("Message deleted", message);
    },
    error => {
        console.log("Message delete failed with error:", error);
    }
);

Once the message is deleted, In the Promise resolved callback, you get an object of the BaseMessage class, with the deletedAt field set with the timestamp of the time the message was deleted. Also, the deletedBy field is set. These two fields can be used to identify if the message is deleted while iterating through a list of messages.

In order to receive real-time events for a message being deleted, you need to override the onMessageDeleted() method of the MessageListener class.

var listenerID = "UNIQUE_LISTENER_ID";

CometChat.addMessageListener(
    listenerID,
    new CometChat.MessageListener({
        onMessageDeleted: message => {
            console.log("Deleted Message", message);            
        }
    })
);

Also, while fetching the list of messages, if the message with ID of 100 was edited or deleted and the total number of messages in the conversation are 110, the 111st message fetched will be an Action message informing the user that the message with the ID 100 has been edited/deleted. To get the message object from the Action message object, you can use the action.getActionOn() method which can be cast to the BaseMessage object.

IMPORTANT

The listeners only help you receive the real-time messages i.e when the user is online in the app and the listeners are added to receive the messages. To fetch previous messages for a user/group please refer to the next section.

Fetch Messages

In order to fetch messages in bulk, the CometChat SDK provides the MessagesRequest class. To use this class i.e to create an object of the MessagesRequest class, you need to use the MessagesRequestBuilder class. The MessagesRequestBuilder class allows you to set the parameters based on which the messages are to be fetched.

The MessagesRequestBuilder class allows you to set the below parameters :

1.setUID( UID : string) - This method sets the UID of the user for which the messages are to be fetched i.e. The messages fetched will be a part of the conversation between the logged in user and the UID set using the setUID() method.

let messagesRequest = new CometChat.MessagesRequestBuilder().setUID("uid").build();

2.setGUID( GUID :string) - This method sets the GUID of the group for which the messages are to be fetched.

let  messagesRequest = new CometChat.MessagesRequestBuilder().setGUID("guid").build();
  1. setMessageId(messageId:number) - This method sets the messageID before or after which the messages are to be fetched.
let messagesRequest = new CometChat.MessagesRequestBuilder().setMessageId(100).build();
  1. setTimestamp(timestamp:number) - This method sets the timestamp before or after which the messages are to be fetched.
let messagesRequest = new CometChat.MessagesRequestBuilder().setTimestamp(1517221231).build();
  1. setUnread(unread :boolean) - This method sets the unread parameter which determines if only the unread messages need to be fetched.
let messagesRequest = new CometChat.MessagesRequestBuilder().setUnread(true).build();
  1. setUndelivered( undelivered:boolean) - This method sets the undelivered parameter which determines if only the undelivered messages need to be fetched.
let messagesRequest = new CometChat.MessagesRequestBuilder().setUndelivered(true).build();
  1. setLimit( limit :number) - This method sets the limit i.e. the number of messages that should be fetched in a single iteration.
let messagesRequest = new CometChat.MessagesRequestBuilder().setLimit(30).build();
  1. hideMessagesFromBlockedUsers( block :boolean) - This parameter determines if the messages from blocked users are to be hidden in the list of messages fetched.
let messagesRequest = new CometChat.MessagesRequestBuilder().hideMessagesFromBlockedUsers(true).build();
  1. setSearchKeyword() - This parameter helps you get messages with the keyword specified. Once this parameter is set, the request will return messages containing the keyword.
let messagesRequest = new CometChat.MessagesRequestBuilder().setSearchKeyword("SEARCH_KEYWORD").build();

Finally, once all the parameters are set to the builder class, you need to call the build() method to get the object of the MessagesRequest class.

The object of the MessagesRequest class can be used to call one of the two below methods:

  1. fetchPrevious() - this method fetches the messages prior to the parameters set.

  2. fetchNext() - this method fetches the messages after the parameters set.

Calling the fetchPrevious() and fetchNext() on the same object of the MessagesRequest class, you can get the paginated list of messages till all the messages for the combination of the parameters set are fetched.

1. Fetch all messages:

Using the same MessagesRequest class discussed above, you can fetch all the messages for a logged in user which involve his messages for all the User and Group conversations. Applying the filters using the MessagesRequestBuilder class, you can fetch messages either before or after a particular messageId or timestamp.

The below code snippet shows how to fetch the latest 50 messages for the logged in user which include messages to and from the logged in user as a part of any User or Group conversations.

var UID = "UID";
var limit = 30;

var messagesRequest = new CometChat.MessagesRequestBuilder().setLimit(limit).build();

messagesRequest.fetchPrevious().then(
	messages => {
		console.log("Message list fetched:", messages);
		// Handle the list of messages
	},
	error => {
		console.log("Message fetching failed with error:", error);
	}
);

Calling the fetchPrevious() method on the same object repeatedly allows you to fetch all the previous messages in a paginated way.

2. Fetch Messages when User was offline.

Using the same MessagesRequest class and the filters provided by the MessagesRequestBuilder class, you can fetch the message that we sent to the logged in user but were not delivered to him as he was offline. For this, you will require the Id of the last message received. You can either maintain it at your end or use the getLastDeliveredMessageId() method provided by the CometChat class. This Id needs to be passed to the setMessageId() method of the builder class.

Now using the fetchNext() method, you can fetch all the messages that were sent to the user when he/she was offline.

Below code snippet demonstrates how this can be achieved.

var UID = "UID";
var limit = 30;
var getLastId=CometChat.getLastDeliveredMessageId();

getLastId.then(lastId=>{
  var messagesRequest = new CometChat.MessagesRequestBuilder().setMessageId(lastId).setLimit(limit).build();

messagesRequest.fetchNext().then(
	messages => {
		console.log("Message list fetched:", messages);
		// Handle the list of messages
	},
	error => {
		console.log("Message fetching failed with error:", error);
	}
);
});

Using additional filters you can also fetch the offline messages for a particular User or a Group conversation too.

Calling the fetchNext() method on the same object repeatedly allows you to fetch all the offline messages for the logged in user.

3. Fetch messages for a User conversation

Using the MessagesRequest class and the filters for the MessagesRequestBuilder class as shown in the below code snippet, you can fetch the entire conversation between the logged in user and any particular user. For this use case, it is mandatory to set the UID parameter using the setUID() method of the builder. This UID is the unique id of the user for which the conversation needs to be fetched.

var UID = "UID";
var limit = 30;

var messagesRequest = new CometChat.MessagesRequestBuilder().setUID(UID).setLimit(limit).build();

messagesRequest.fetchPrevious().then(
	messages => {
		console.log("Message list fetched:", messages);
		// Handle the list of messages
	},
	error => {
		console.log("Message fetching failed with error:", error);
	}
);

Calling the fetchPrevious() method on the same object repeatedly allows you to fetch the entire conversation between the logged in user and the specified user. This can be implemented with upward scrolling to display the entire conversation.

4. Fetch Messages for a Group Conversation:

Using the MessagesRequest class and the filters for the MessagesRequestBuilder class as shown in the below code snippet, you can fetch the entire conversation for any group provided you have joined the group. For this use case, it is mandatory to set the GUID parameter using the setGUID() method of the builder. This GUID is the unique identifier of the Group for which the messages are to be fetched.

var GUID = "GUID";
var limit = 30;

var messagesRequest = new CometChat.MessagesRequestBuilder().setGUID(GUID).setLimit(limit).build();

messagesRequest.fetchPrevious().then(
	messages => {
		console.log("Message list fetched:", messages);
		//Handle the list of messages
	},
	error => {
		console.log("Message fetching failed with error:", error);
	}
);

Calling the fetchPrevious() method on the same object repeatedly allows you to fetch the entire conversation for the group. This can be implemented with upward scrolling to display the entire conversation.

Message List

The list of messages can have the following possible types

1. TextMessage
2. MediaMessage

you will have to check for all the four types to segregate the messages and act on the same accordingly.

This can be done using the instanceof operator in javascript. or using type attribute or message.


What's Next

Users

Messaging


Suggested Edits are limited on API Reference Pages

You can only suggest edits to Markdown body content, but not to the API spec.