Message

Prev Next

Available in Classic and VPC

Message

The message function provided by Ncloud Chat includes various services supporting efficient communication between users. This platform is suitable for group chat as well as personal chat, and it enables a simple, fast process of sending and receiving messages. The following describes Ncloud Chat's main message functions and their features.

1. Instant messaging

  • Real-time communication: you can send and receive messages in real time, which minimizes communication delay.
  • Supporting multiple devices: you can send and receive messages on various devices such as smartphones, tablets, PCs, and so on.

2. Group chat

  • Multiple participants: you can create a group chat that many people can participate in to share information and enhance communication within the team.
  • Manage channel: the admin can add or delete members through the group chat, and adjust the group settings.

3. File sharing

  • Supporting various file formats: you can easily share files in diverse formats such as texts, images, videos, and documents through the chat.
  • Safe file storage: Ncloud Chat saves and manages files in your Object Storage, preventing any information leaks.

4. Message search

  • Keywords search: you can use a specific keyword to search for the past conversation content in the chat.
  • Advanced filter options: you can quickly find the messages you want to search for by applying various filters, such as date, participant, and file format.

5. Notification adjustments

  • Push notifications: when a new message or an important update occurs, a notification is sent to the user to prevent information omission.
  • Notification setting: you can adjust the type and frequency of notification to receive the information in a desired way.

6. Security and personal information protection

  • Data encryption: all messages are encrypted during transmission and storage to prevent data leaks from the outside.
  • Protecting personal information: personal information and dialogs of the user are strictly protected, and are not disclosed to any third party without the consent of the user.

The message function of Ncloud Chat promotes easy and efficient communication of the user, and has an important role in business and daily life. These functions promote easy user communication and enhance teamwork.

Forward message

If you have created and joined a channel, you can send a new message by calling the following:

Javascript/Typescript

const message = 'Hello !!!';
await nc.sendMessage([CHANNEL_ID], {
      type: "text", 
      message: message
});

// When mentioning a specific user
await nc.sendMessage(CHANNEL_ID, {
      type: "text", 
      mentions: [USER_ID, USER_ID]
      message: message
});
// Another method to mention someone is to enter "@[ID]" in a message to automatically mention someone.

// When replying to a message
await nc.sendMessage(CHANNEL_ID, {
      type: "text", 
      parent_message_id: MESSAGE_ID
      message: message
});

// In a new message, the contents of the parent message are supplemented and sent with parent_message as shown below.
{
    "id": "message_id",
    "text": "Message",
    "parent_message_id": "first_message_id",
    "parent_message": { 
        "id": "message_id", 
        "text": "message_name",
        "sender" : {
            "id" : "Sender",
             "name" : "Sender Nickname",
             "profile" : "profile url",
        }
    }
}

Android(Kotlin)

NChat.sendMessage([CHANNEL_ID], messageText) { message, e ->
    if (e != null) {
        // Error
    } else {
        // Succeeded
    }
}

iOS(Swift)

NChat.sendMessage(channelId: [CHANNEL_ID], message: messageText) { result in
    switch(result)
    {
    case .success(let message) :
        // Succeeded
        break;
    case .failure(let error) :
        // Failed
        break;
    }
}

iOS(Objective-C)

[NChatBridge.shared sendMessageWithChannelId:[CHANNEL_ID] message:[MESSAGE] type:@"TEXT" parentMessageId:@"" translate:NO :^(NSDictionary * _Nullable result, NSError * _Nullable error) {
    if (error) {
        // Handles error
    } else {
        // Handles success
    }
}];

Unity

const message = 'Hello !!!';
await nc.sendMessage(
        channelId: CHANNEL_ID, 
        type:"text", 
        content: message
);


// When replying to a message
await nc.sendMessage(
        channelId: CHANNEL_ID, 
        type:"text", 
        content: message, 
        parentMessageId: [MESSAGE_ID]
        );

// When an automatic translation is required for a message
await nc.sendMessage(
        channelId: CHANNEL_ID, 
        type:"text", 
        content: message, 
        translate: true
        );

// In a new message, the contents of the parent message are supplemented and sent with parent_message as shown below.
{
    "id": "message_id",
    "text": "Message",
    "parent_message_id": "first_message_id",
    "parent_message": { 
        "id": "message_id", 
        "text": "message_name",
        "sender" : {
            "id" : "Sender",
             "name" : "Sender Nickname",
             "profile" : "profile url"
        }
    }
}
Note

If you send/receive messages in JSON format, you can use various user-defined values.

Javascript/Typescript

const message = {
    { "text", "Text" },
    { "state", 1 },
    { "desc" , "Desc" }
};
// Converts the message to a string.
const jsonString = JSON.stringify(message);
// Converts the received message to an Array.
const messageArray = JSON.parse(jsonString);

Unity

Hashtable messageArray = new Hashtable
{
    { "channel_id", "channelId" },
    { "state", 1 },
    { "desc" , "Desc" }
};
// Converts the message to plain text.
const jsonString = JsonConvert.SerializeObject(messageArray);
// Converts the received message to an Array.
Hashtable hashtable = JsonConvert.DeserializeObject<Hashtable>(jsonString);
ID Type Description
CHANNEL_ID string Channel ID
type string Type of the message to send (text or image)
MESSAGE string You can use them in various ways with the message texts to send and JSON String.
MENTIONS array ID of the user to mention
  • Use Express Message: this function is only for sending messages at high speed. By skipping all parts that may cause a delay, messages can be transferred 10 times faster than with the previous method. The differences from normal sendMessage are as follows:
Function Description Filtering Block Translate
sendMessage Send normal messages O O O
sendExpressMessage Send express messages X X X

Available to use for any service that requires real-time PvP production or high-speed broadcasting within the game.

Upload files

  • You can transfer files to a specific channel.
  • You can only upload allowed file types. See Dashboard > Settings > Security > Allowed file types.

Javascript/Typescript

await nc.sendFile([CHANNEL_ID], file);

Android (Kotlin)

import android.app.Activity
import android.content.Intent
import android.net.Uri
...

private val PICK_FILE_REQUEST_CODE = 1009

fun fileUpload() {
    val intent = Intent(Intent.ACTION_GET_CONTENT)
    intent.type = "*/*"
    startActivityForResult(intent, PICK_FILE_REQUEST_CODE)
}

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
    if (requestCode == PICK_FILE_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
        val fileUri: Uri? = data?.data
        fileUri?.let {
            // Upload files using selected file URI
            NChat.sendFile(this, [CHANNEL_ID], it) { response,e ->
                if (e != null) {
                    // Error
                } else {
                    // Succeeded
                }
            }
        }
    }
}

iOS (Swift)

Add DocumentPicker as in the following example to use the file upload function:

import SwiftUI
import UniformTypeIdentifiers

struct DocumentPicker: UIViewControllerRepresentable {
    class Coordinator: NSObject, UIDocumentPickerDelegate {
        var parent: DocumentPicker

        init(parent: DocumentPicker) {
            self.parent = parent
        }

        func documentPicker(_ controller: UIDocumentPickerViewController, didPickDocumentsAt urls: [URL]) {
            guard let selectedFileURL = urls.first, selectedFileURL.startAccessingSecurityScopedResource() else { return }
            parent.selectedFileURL = selectedFileURL
            parent.isPresented = false
        }
    }

    @Binding var selectedFileURL: URL?
    @Binding var isPresented: Bool

    func makeCoordinator() -> Coordinator {
        return Coordinator(parent: self)
    }

    func makeUIViewController(context: Context) -> UIDocumentPickerViewController {
        let picker = UIDocumentPickerViewController(forOpeningContentTypes: [UTType.item])
        picker.delegate = context.coordinator
        return picker
    }

    func updateUIViewController(_ uiViewController: UIDocumentPickerViewController, context: Context) {
    }
}

Implements the file upload function within the View, as in the following example:

@State private var selectedFileURL: URL?
@State private var isDocumentPickerPresented = false

if let selectedFileURL = selectedFileURL {
    Text ("Selected file: \(selectedFileURL.lastPathComponent)")
    Button(action: {
        NChat.sendFile(channelId: channelId, fileUrl: selectedFileURL) { result in
            switch(result) {
                case .success(let result):
                    // Succeeded
                case .failure(let error):
                    // Failed
            }
        }
    }) {
        Text ("Upload file")
    }
} else {
        Text ("Select file")
} 
// Call after completing file uploading.
selectedFileURL?.stopAccessingSecurityScopedResource()                

var body: some View {
        VStack {

Button(action: {
    isDocumentPickerPresented = true
}) {
    Text ("Select file")
}
.sheet(isPresented: $isDocumentPickerPresented) {
    DocumentPicker(selectedFileURL: $selectedFileURL, isPresented: $isDocumentPickerPresented)
}
Note
  • If you want to implement image upload other than files, use UIImagePickerController.
  • To upload images, define Privacy - Photo Library Usage Description within Targets > Info > Custom iOS Target Properties.

iOS(Objective-C)

In order to use the file upload function, implement UIImagePickerController or UIDocumentPickerViewController, then upload the file with the file URL.

NSURL *fileUrl = [NSURL URLWithString:[FILEURL]];

if (fileUrl) {
    [NChatBridge.shared sendFileWithChannelId:channelId fileUrl:fileUrl :^(NSDictionary * _Nullable result, NSError * _Nullable error) {
        if (error) {
            [self inAppLog:[NSString stringWithFormat:@"Send File Error: %@", error.localizedDescription]];
        } else {
            [self inAppLog:[NSString stringWithFormat:@"Send File succeeded with result: %@", result]];
        }
        [self.tableView reloadData];
    }];
}

Unity

await nc.sendFile([CHANNEL_ID],file);
ID Type Description
CHANNEL_ID string Channel ID
file string File information
Note
  • Object Storage must be enabled.
  • You can use it after integrating with the Object Storage product.
  • When uploading, set the upload type and upload size, and so on in Set project > Security settings in the dashboard.
  • Supported file types: all general types such as images, videos, documents, and zips are supported. For an extension that needs to be supported additionally, send inquiries through Contact us, and we will add it after reviewing its security.
  • When using the file link, the Endpoint address is https://apps.ncloudchat.naverncp.com.
    For example, https://apps.ncloudchat.naverncp.com/archive/[archiveId]

Message information

  • Message Data Class
ID Type Description
id string Message sending ID (unique)
message_id string Message ID
sort_id string Identifier for sorting messages
message_type string Message type
sender.id string Sender ID
sender.name string Sender username
sender.profile string Sender profile image
attachment_filenames string Attachment
parent_message_id string Reply message ID
parent_message Message Reply message
isExpress boolean Express message status
metions string Mentioned list
content string Message content
sended_at string Sent date
created_at string Creation date

Individual message information

You can get information about individual messages.

Javascript/Typescript

var message = await nc.getMessage(channel_id, message_id);

Android (Kotlin)

NChat.getMessage([MESSAGE_ID]) {  message, e -> {
    if (e != null) {
        // Error
    } else {
       // Succeeded
    }
}

iOS (Swift)

NChat.getMessage(channelId: [CHANNEL_ID], messageId: [MESSAGE_ID]) { result in
    switch(result)
    {
    case .success(let message) :
        // Succeeded
        break;
    case .failure(let error) :
        // Failed
        break;
    }
}

iOS(Objective-C)

[NChatBridge.shared getMessageWithChannelId:[CHANNEL_ID] messageId:[MESSAGE_ID] :^(NSDictionary * _Nullable result, NSError * _Nullable error) {
    if (error) {
        // Handles error
    } else {
        // Handles success
    }
}];

Unity

NBaseSDK.Message message = await nc.getMessage([CHANNEL_ID], [MESSAGE_ID]);

All messages information

You can get information on all messages.

  • MessageData data class
ID Type Description
totalCount Int Number of all messages
messages Message Message data list

Javascript/Typescript

const filter = { channel_id: channelId };
const sort = { created_at: -1 };
const option = { offset: 0, per_page: 100 };
const messages = nc.getMessages(filter, sort, option);

Android (Kotlin)

  • Filter settings
val filter: Map<String, Any?> = mapOf(
    "channel_id" to [CHANNEL_ID],
)
  • Sorting settings
val sort: Map<String, Any?> = mapOf(
    "created_at" to -1
)
  • Option settings
val options: Map<String, Any?> = mapOf(
    "per_page" to 10,
    "offset" to 0
)
NChat.getMessages(filter, sort, options) { data, e ->
    if (e != null) {
    // Error
    } else {
    // Succeeded
    }
}

iOS (Swift)

let filter: [String: Any] = ["channel_id": [CHANNEL_ID]]
let option: [String: Any] = ["per_page": 10, "offset": 0]
let sort: [String: Any] = ["created_at": "-1"]
NChat.getMessages(filter: filter, option: option, sort: sort) { result in
    switch(result)
    {
    case .success(let messagesData) :
        // Succeeded
        break;
    case .failure(let error) :
        // Failed
        break;
    }
}

iOS(Objective-C)

NSMutableDictionary *filter = [NSMutableDictionary dictionary];
NSMutableDictionary *option = [NSMutableDictionary dictionary];
NSMutableDictionary *sort = [NSMutableDictionary dictionary];

filter[@"channel_id"] = @"[CHANNEL_ID]";

[NChatBridge.shared getMessagesWithChannelId:[CHANNEL_ID] filter:filter option:option sort:sort :^(NSDictionary * _Nullable result, NSError * _Nullable error) {
    if (error) {
        // Handles error
    } else {
        // Handles success
    }
}];

Unity

Hashtable filter = new Hashtable
{
    { "channel_id", [CHANNEL_ID] }
};
Hashtable sort = new Hashtable
{
    { "sort_id", -1 }
};
Hashtable option = new Hashtable
{
    { "offset", 0 },
    { "per_page", 10 }
};
var messages = await nc.getMessages(filter, sort, option);
if (messages != null)
    {
            foreach (var message in messages.edges)
        {
            string id = message.Node.message_id.ToString();
            Console.WriteLine("[CloudChatSample] id={0}", id);
        }
    }
  • Parameters
ID Type Description Required
filter object Search is available for all fields of a query through filtering O
sort object Define a filter for the fields you want to sort X
option object See the following when there are options X
  • Filter
ID Type Description
message_id String Message ID
channel_id String Channel ID
sort_id String Sorting ID
message_type String Message type
embedProviders String Embed provider
isExpress Boolean Instant message status
bytes Int Message byte size
content String Message content
sended_at String Message transmission time
created_at String Message creation time
  • Sort
ID Type Description
created_at number Creation date ("1" for ascending, "-1" for descending order)
  • Options
ID Type Description
offset number Start offset
per_page number Number of items returned (up to 100)

Unread messages

Returns the number of unread messages. Sends the information of the last read message through markRead first.

Javascript/Typescript

nc.markRead(channelId, {
      user_id: message.sender.id,
      message_id: message.message_id,
      sort_id: message.sort_id
});
const unread = await nc.unreadCount([CHANNEL_ID]);

Android (Kotlin)

NChat.unreadCount([CHANNEL_ID]) { data, e ->
    if (e != null) {
        // Error
    } else {
        // Succeeded
    }
}

iOS (Swift)

NChat.unreadCount(channelId: [CHANNEL_ID]) { result in
    switch(result)
    {
    case .success(let mark) :
        // Succeeded
        break;
    case .failure(let error) :
        // Failed
        break;
    }
}

Unity

nc.markRead([CHANNEL_ID], new NBaseSDK.MarkInput 
{
    user_id = USER_ID, 
    message_id = MESSAGE_ID,
    sort_id = SORT_ID
});
// Returns the number of unread messages after being marked.
var unread = nc.unreadCount([CHANNEL_ID]);
ID Type Description
USER_ID string Enter the user_id contained in the message
MESSAGE_ID string Enter the message_id contained in the message
SORT_ID string Enter the sort_id contained in the message

Delete message

You can delete messages you sent within the channel.

Javascript/Typescript

await nc.deleteMessage([CHANNEL_ID], [MESSAGE_ID]);

Android (Kotlin)

NChat.deleteMessage([CHANNEL_ID], [MESSAGE_ID]) { data, e ->
    if (e != null) {
        // Error
    } else {
        // Succeeded
    }
}

iOS (Swift)

NChat.deleteMessage(channelId: [CHANNEL_ID], messageId: [MESSAGE_ID]) { result in
    switch(result)
    {
    case .success(let message) :
        // Succeeded
        break;
    case .failure(let error) :
        // Failed
        break;
    }
}

iOS(Objective-C)

[NChatBridge.shared deleteMessageWithChannelId:[CHANNEL_ID] messageId:[MESSAGE_ID] :^(NSDictionary * _Nullable result, NSError * _Nullable error) {
    if (error) {
        // Handles error
    } else {
        // Handles success
    }
}];

Unity

await nc.deleteMessage([CHANNEL_ID], [MESSAGE_ID]);
  • Parameters
ID Type Description
CHANNEL_ID string Channel ID
MESSAGE_ID string Message ID

Number of users who did not read certain message

The remaining users by excluding the list of users who read the message from the list of all participating users of the channel are considered unread users.

Javascript/Typescript

await nc.getMessageReadCount([CHANNEL_ID], [MESSAGE_ID]);
  • Parameters
ID Type Description
CHANNEL_ID string Channel ID
MESSAGE_ID string Message ID

Number of users who did not read certain message

This method returns the number of users who did not read certain messages within a specified channel.

Javascript/Typescript

await nc.getMessageUnreadCount(CHANNEL_ID, MESSAGE_ID);
  • Parameters
Parameter Type Description
CHANNEL_ID string Channel's unique identifier. You can specify a certain channel with this value.
MESSAGE_ID string Message's unique identifier. It defines the message for which you want to view the number of unread users.
  • Returns

getMessageUnreadCount method returns the object of the following format:

{
    "totalCount": 34,
    "count": 34
}
Parameter Type Description
totalCount number Displays the number of all users participating in a specified channel.
count number Displays the number of users who did not read a specified message.
  • Usage example
const result = await nc.getMessageUnreadCount("123456789", "987654321");

console.log(result.totalCount); // Example: number of all users participating in the channel: 34
console.log(result.count);      // Example: number of users who did not read the message: 10

In the previous example, it views the number of users who did not read the message for the channel ID "123456789" and message ID "987654321". result.totalCount represents the number of all users participating in the channel, and result.count represents the number of users who did not read the specified message yet.

With this function, you can find out how many users did not read a certain message within a channel easily.