Instant Messaging
Android
Getting Started
Introduction
Overview
Benefits
Features
Features
Account Integration and Login
Group Chat
Chat Room
Chat Room Tags
Multi-device Login
Statistics Monitoring
Limits
Integration
Interface Overview
Integrate and Initialize SDK
Messaging
Basic Messaging
Message History
Message Sending
Message Receiving
Recent Chats
Server Sessions
User Profile
User Relationship
Online Status Subscription
Push and Message Alert
Superteam
Chat Room
Moderation
Chat Extension
Miscellaneous Features
Best Practice
Traffic Control in Chat Rooms
Reference
API Reference
Status Codes

Send and receive message

Update time: 2021/12/06 16:43:10

Overview

  • Peer-to-peer or team messaging includes messages, offline messages, and roaming messages.
    • Offline messages and roaming messages can be received only, but cannot be sent. They can be acquired in the callback of onofflinemsgs/onroamingmsgs during an initialization.
    • A message can be received or sent. The message is received in callback for onmsg during the SDK initialization.
  • Offline messages: The message that is sent from others and not acknowledged at any client by your account is called as offline message. If the offline message is acknowledged at any other clients(including yourself), corresponding messages will not be received.
  • Roaming messages: The message that is sent from others and not acknowledged at current client, but acknowledged at other clients such as iOS/android/pc... Is called as roaming message. Only when being acknowledged at current client, the roaming message will not be pushed.

Initialization parameters

Sample codes

var nim = NIM.getInstance({
    onroamingmsgs: onRoamingMsgs,
    onofflinemsgs: onOfflineMsgs,
    onmsg: onMsg,
});
function onRoamingMsgs(obj) {
    console.log('receive roaming message', obj);
    pushMsg(obj.msgs);
}
function onOfflineMsgs(obj) {
    console.log('receive offline message', obj);
    pushMsg(obj.msgs);
}
function onMsg(msg) {
    console.log('receive message', msg.scene, msg.type, msg);
    pushMsg(msg);
    switch (msg.type) {
    case 'custom':
        onCustomMsg(msg);
        break;
    case 'notification':
        // Manage team notification messages
        onTeamNotificationMsg(msg);
        break;
    // Other cases
    default:
        break;
    }
}
function pushMsg(msgs) {
    if (!Array.isArray(msgs)) { msgs = [msgs]; }
    var sessionId = msg[0].scene + '-' + msgs[0].account;
    data.msgs = data.msgs || {};
    data.msgs[sessionId] = nim.mergeMsgs(data.msgs[sessionId], msgs);
}
function onCustomMsg(msg) {
    // Process custom messages
}

Parameter description

  • shouldIgnoreNotification: It is a function that indicates whether to ignore a certain notification message. The API will filter received notification messages based on upper-defined logics. If "true" is returned, the SDK will neglect the notification message.
  • onroamingmsgs is a callback of synchronizing roaming Message object. Each session object corresponds to a callback which will be input into message array.
  • onofflinemsgs is a callback of synchronizing offline Message object. Each Session object corresponds to a callback which will be input into message array.
  • The multi-tab login is allowed at the operation "Support database". If multiple tab pages are disconnected and then reconnected, only one tab page will store roaming and offline messages. Namely, only one tab page will receive the callback onroamingmsgs and onofflinemsgs, while other tab pages need to call "Get local system notification" to get message history from local cache after the operation "Complete synchronization".
  • onmsg: It is a callback for receiving Message object.
    • If the current login account sends message at other clients, the callback will also be returned. It is noted that the field from under current message object is current login account.
  • nim.mergeMsgs can be invoked to merge data.

Message object

The message object contains fields as below:

  • scene: Message scenarios.
  • from: Message sender, account or team ID
  • fromNick: Nickname of message sender
  • fromClientType: Device types of sender
  • fromDeviceId: Device ID at sending client
  • to: Message receiver, account or team ID
  • time: Timestamp
  • type: Message types
  • sessionId: ID of Session object for a message
  • target: Chat object, account or team ID.
  • flow: Flow of message
    • 'in' means that the message is the received message.
    • 'out' means that the message is the sent message.
  • status: Sending status of message
    • 'sending': The message is being sent.
    • 'success': The message is sent successfully.
    • 'fail': The message is not sent successfully.
  • text: Content of text messages. Please refer to Send text message.
  • file: File object of file message. For detailed fields, see Image object, Audio object, Video object, File object. Please refer to Send file messages.
  • geo: Geographical location object of geographical location message. Please refer to Send geographical location message.
  • tip: Content of tip message. Please refer to Send tip message.
  • content: Content of custom message. Developer can extend it independently. We recommend packing it into JSON character string. Please refer to Send custom message..
  • attach: Attached information of team notification message. Please refer to Team notification message to view corresponding attached information of different team notification messages.
  • idClient: ID of SDK generated message. It will be returned to developers after the message is sent. Developers can determine sending status (successful or failed) of related message in the callback for sending message based on the ID, and then update page UI based on the status. If a message is not sent successfully, you can Resend messages.
  • isMuted: It determines that the message shall be muted by receiver.
  • isInBlackList: It determines that the sender 'from' is added to blocklist of receiver 'to' when this message is sent.
  • resend: It determines whether the message is re-sent or not.
  • custom: Extension field.
    • We recommend creating user profile in JSON format. If it is not JSON format, other clients may abandon the information, although Web client will receive it ordinaryly.
  • nosScene: nos storage scene. It is applicable to send file message, and provided with initial configuration by default.
  • nosSurvivalTime: Survival time of nos storage scene. It is applicable to send file message, and provided with initial configuration by default.
  • pushContent: Custom push text.
  • pushPayload: Custom push attribute.
    • We recommend creating user profile in JSON format. If it is not JSON format, other clients may abandon the information, although Web client will receive it ordinaryly.
  • needPushNick: It determines whether a nickname is pushed
  • apns: Special push option. It is used only in team session.
  • apns.accounts: List of accounts requiring special push. If this field is not available, it means to push to all users in current session.
  • apns.content: Text requiring special push.
  • apns.forcePush: It determines force push. "True" means that current content can be pushed to related users even though users in a push list have blocked current session (e.g. mute).
  • localCustom: Local custom extension field
  • needMsgReceipt: It determines that message is acknowledged (if the field is contained, it means that acknowledged receipt is needed). Only when the acknowledged receipt is configured, The API getTeamMsgReads, getTeamMsgReadAccounts and the like can be invoked.
  • isHistoryable: It determines that storage to cloud history is required.
  • isRoamingable: It determines that roaming support is required.
  • isSyncable: It determines that multi-client synchronization is supported for the sender.
  • cc: It determines that cc is supported.
  • isPushable: It determines whether a message is pushed
  • isOfflinable: It determines that offline storage is required.
  • isUnreadable: It determines that the message is included in unread count.
  • isLocal: It determines that it is a local message, see Send local message.

Message scenarios

The field scene under Message object is used to indicate Message scenarios. The detailed scenes are described as below:

  • 'P2P' (peer-to-peer messages)
  • 'team' (Team message)
  • 'superTeam' (SuperTeam message)

Message types

The field type under Message object is used to indicate type of message. The detailed types are described as below:

  • 'text' (Text message)
  • 'image' (Image message)
  • 'audio' (Audio message)
  • 'video' (Video message)
  • 'file' (File message)
  • 'geo' (Geographical location message)
  • 'custom' (Custom message)
  • 'tip' (Tip message)
    • The tip message is used to remind status in session, for example, welcome message in session, or prompt message when the session contains sensitive.
  • 'notification' (Team notification message)

For receiving and sending different types of messages, see:

Text object

When team members Send text message or receive text message, the field text under Message object indicates content of the text message.

Image object

When team members Send image message or receive image message, the field file under Message object indicates the image object, including attributes as below:

  • name: Name
  • size: Size, unit: byte
  • MD5: MD5
  • url: URL
  • ext: Extension name
  • w: Width, unit: px
  • h: Height, unit: px

Audio object

When team members Send audio message or receive audio message, the field file under Message object indicates the audio object, including attributes as below:

  • name: Name
  • size: Size, unit: byte
  • MD5: MD5
  • url: URL
  • ext: Extension name
  • dur: Length, unit: ms

Video object

When team members Send video message or receive video message, the field file under Message object indicates the video object, including attributes as below:

  • name: Name
  • size: Size, unit: byte
  • MD5: MD5
  • url: URL
  • ext: Extension name
  • dur: Length, unit: ms
  • w: Width, resolution, unit: px
  • h: Height, resolution, unit: px

The cover (first frame image) is taken as video object:

  • vframe is added to acquired video object. For example, if original video address is http://img-sample.nos-eastchina1.126.net/sample.wmv, the cover (first frame) image address will be http://img-sample.nos-eastchina1.126.net/sample.wmv?vframe.

File object

When team members Send file messages or receive file message, the field file under Message object indicates the file object, including attributes as below:

  • name: Name
  • size: Size, unit: byte
  • MD5: MD5
  • url: URL
  • ext: Extension name

Geographical location object

When team members Send Geographical location message or receive Geographical location message, the field geo under Message object indicates the Session object geographical location, including attributes as below:

  • lng: Longitude
  • lat: Latitude
  • title: Address description

Team notification messages

  • The team notification message is one Type of message.
  • After some operations, all team members will receive a related team notification message.
  • The field attach under Message object corresponding to the team notification message contains extra information. The field type under attach is used to indicate team types notification message.
    • 'updateTeam' (Update team)
      • After the operation "Update team", all team members will receive a Team notification message of 'updateTeam' type. For such team notification message, the field from is account of the user who updates team; the field to is the corresponding team ID; the field team under attach is updated Team information.
    • 'addTeamMembers' (Invite a user to team)
      • ordinary team - After the operation "Invite a user to team", all team members will receive a Team notification message of 'addTeamMembers' type. For such team notification message, the field from is account of the team inviter; the field to is the corresponding team ID; the field team under attach is the corresponding Team object; the field accounts under attach is the list of invited accounts; the field members under attach is the list of invited team members.
    • 'removeTeamMembers' (Kick out a team member
      • After the operation "Kick out team member", all team members will receive a Team notification messages of 'removeTeamMembers' type. For such team notification message, the field from is account of the team administrator who kicks members out of the team; the field to is the corresponding team ID; the field team under attach is the corresponding Team object; the field accounts under attach is the list of removed accounts.
    • 'acceptTeamInvite' (Accept team invitation)
      • After team owner and adiministor of an advanced team invite a user to join their team (with Create a team or Invite a user to team), the invited user will receive a System notification of 'teamInvite' type. For such system notification, the field from is account of inviter; the field to is the corresponding team ID; and the field team under attach is the Team that is invited to join in. The invited user can accept or reject an invitation.
        • If the invited user selects to "Accept invitation", all team members will receive a Team notification message of 'acceptTeamInvite' type. For such team notification message, the field from is account that accepts team invitation; the field to is the corresponding team ID; the field team under attach is the corresponding Team object; the field members under attach is the list of team members receiving team invitation.
        • If the invited user selects to "Reject invitation", the inviter will receive a System notification of 'rejectTeamInvite' type. For such system notification, the field from is account rejecting team invitation and the field to is the corresponding team ID.
    • 'passTeamApply' Approve team application
      • A user can Apply for joining advanced team, owner and adiministor of the target team will receive a System notification of 'applyTeam' type. For such system notification, the field from is account of the applicant and field to is the corresponding team ID. After receiving the application for joining team, owner and adiministor of the advanced team can accept or reject the application.
        • If they "Accept team application", all team members will receive a Team notification message of 'passTeamApply' type. For such team notification message, the field from is account that accepts team application; the field to is the corresponding team ID; the field team under attach is the corresponding Team object; the field account under attach is account of the applicant; the field members under attach is the list of team members who are approved for team application.
        • If they "Reject a team application", the applicant will receive a System notification of 'rejectTeamApply' type. For such system notification, the field from is account that rejects team application; the field to is the corresponding team ID; the field team under attach is the corresponding Team.
    • 'addTeamManagers' (Add team administrator)
      • After the operation "Add team administrator", all Team members will receive a Team notification message of 'addTeamManagers' type. For such team notification message, the field from is account of the member who adds team administrator; the field to is the corresponding team ID; the field accounts under attach is the list of accounts added as administrators; the field members under attach is the list of team members added as administrators.
    • 'removeTeamManagers' Remove team administrator
      • After the operation "Remove team administrator", all Team members will receive a Team notification message of 'removeTeamManagers' type. For such team notification message, the field from is account of the administrator who removes team administrator; the field to is the corresponding team ID; the field accounts under attach is the list of accounts of removed administrators; the field members under attach is the list of members in the team where manager is removed.
    • 'leaveTeam' (Actively leave team)
    • 'dismissTeam' (Dismiss team)
      • After the operation "Dismiss team", all Team members will receive a Team notification message of 'dismissTeam' type. For such team notification message, the field from is account of member who dismisses the team; the field to is corresponding team ID.
    • 'transferTeam' (Transfer a team)
      • After the operation "Transfer a team", all Team members will receive a Team notification message of 'transferTeam' type. For such team notification message, the field from is account of the member who transfers team; the field to is corresponding team ID; the field team under attach is corresponding Team object; the field account under attach is account of the new owner; the field members under attach is the list of team members (including original and new owner).
    • 'updateTeamMute' (Update mute status of team members)
      • After the operation "Update mute status of team members", all Team members will receive a Team notification message of 'updateTeamMute' type. For such team notification message, the field from is operator; the field to is the corresponding team ID; the field team under attach is the corresponding Team object; the field account under attach is muted account; the field members under attach is the list of muted team members.
  • If there is a field account or accounts under attach, the field users under attach contains corresponding user profile of these accounts.
  • If a member updates his nickname in team, all other online team members will not receive a team notification message, but the callback onupdateteammember that is input at the operation "Initialize SDK". Please refer to Update my team attribute and Update team nicknames of other members.

Notification message for call event

Once the call is ended, whatever it is hanged up after connection or missed, both parties will receive an IM of notification type. The field type under attach can indicate status of the call.

  • 'netcallBill' (Call bill notification)
    • When the call is connected successfully, any party can hang up. Both parties of the call will receive a message of notification type, with attach.type as netcallBill. For detailed resolution of the message, see Call bill notification.
  • 'netcallRejected'
    • If the call is rejected by the called party, the calling party will receive a message of notification type, with attach.type as netcallRejected.
  • 'rejectNetcall'
    • If the called party receives the call but actively rejects it, the called party will receive a message of notification type, with attach.type as rejectNetcall.
  • 'netcallMiss'
    • Missed call If the called party did not process the call, until the calling party canceled the call, then the called party would receive a message of notification type, with attach.type as netcallMiss.
  • 'cancelNetcallBeforeAccept'
    • If the called party did not connect the call, but actively hanged up, then the calling party would receive a message of notification type, with attach.type as cancelNetcallBeforeAccept.

The above conditions have been summarized to About types of point-to-point audio & video call events.

SuperTeam notification message

After operation for a SuperTeam, all members will receive a notification message. The field attach under Message object corresponding to the Supergroup notification message contains extra information. The field type under attach is used to indicate type of SuperTeam notification message.

  • 'updateSuperTeam' (Update team)
    • After the operation "Update team", all team members will receive a Team notification message of 'updateSuperTeam' type. For such team notification message, the field from is account of the user who updates team; the field to is corresponding team ID; the field team under attach is updated SuperTeam information.
  • 'addSuperTeamMembers' (Invite a user to team)
    • After the operation "Invite a user to team", all SuperTeam members will receive a SuperTeam notification message of 'addSuperTeamMembers' type. For such team notification message, the field from is account of the team inviter; the field to is corresponding team ID; the field team under attach is corresponding SuperTeam object; the field accounts under attach is the list of invited accounts; the field members under attach is the list of invited team members.
  • 'removeSuperTeamMembers' (Kick out team member
    • After the operation "Kick out team member", all SuperTeam members will receive a SuperTeam notification message of 'removeSuperTeamMembers' type. For such team notification message, the fromfield is account of the team administrator who kicks members out of the team; the tofield is the corresponding team ID; the team field under attach is corresponding Object of SuperTeam; the accounts field under attach is the list of kicked-out accounts.
  • 'leaveSuperTeam' (Actively leave team)

Process team notification message

Sample codes

function onTeamNotificationMsg(msg) {
    // Process team notification message
    var type = msg.attach.type,
        from = msg.from,
        teamId = msg.to,
        timetag = msg.time,
        team = msg.attach.team,
        account = msg.attach.account,
        accounts = msg.attach.accounts,
        members = msg.attach.members;
    switch (type) {
    case 'updateTeam':
        team.updateTime = timetag;
        onTeams(team);
        break;
    case 'addTeamMembers':
        onAddTeamMembers(team, accounts, members);
        break;
    case 'removeTeamMembers':
        onRemoveTeamMembers(team, teamId, accounts);
        break;
    case 'acceptTeamInvite':
        onAddTeamMembers(team, [from], members);
        break;
    case 'passTeamApply':
        onAddTeamMembers(team, [account], members);
        break;
    case 'addTeamManagers':
        updateTeamManagers(teamId, members);
        break;
    case 'removeTeamManagers':
        updateTeamManagers(teamId, members);
        break;
    case 'leaveTeam':
        onRemoveTeamMembers(team, teamId, [from]);
        break;
    case 'dismissTeam':
        dismissTeam(teamId);
        break;
    case 'transferTeam':
        transferTeam(team, members);
        break;
    }
}
function onAddTeamMembers(team, accounts, members) {
    var teamId = team.teamId;
    /*
    If other members are invited, then splice the team member list
    If you are invited, then synchronize the team member list
    */
    if (accounts.indexOf(data.account) === -1) {
        onTeamMembers({
            teamId: teamId,
            members: members
        });
    } else {
        nim.getTeamMembers({
            teamId: teamId,
            sync: true,
            done: function(error, obj) {
                if (!error) {
                    onTeamMembers(obj);
                }
            }
        });
    }
    onTeams(team);
}
function onRemoveTeamMembers(team, teamId, accounts) {
    /*
    If others are removed, then remove the team members
    If you are removed, then leave the team
    */
    if (accounts.indexOf(data.account) === -1) {
        if (team) {
            onTeams(team);
        }
        data.teamMembers[teamId] = nim.cutTeamMembersByAccounts(data.teamMembers[teamId], teamId, accounts);
        refreshTeamMembersUI();
    } else {
        leaveTeam(teamId);
    }
}
function updateTeamManagers(teamId, members) {
    onTeamMembers({
        teamId: teamId,
        members: members
    });
};
function leaveTeam(teamId) {
    onInvalidTeams({
        teamId: teamId
    });
    removeAllTeamMembers(teamId);
}
function dismissTeam(teamId) {
    onInvalidTeams({
        teamId: teamId
    });
    removeAllTeamMembers(teamId);
}
function removeAllTeamMembers(teamId) {
    delete data.teamMembers[teamId];
    refreshTeamMembersUI();
}
function transferTeam(team, members) {
    var teamId = team.teamId;
    onTeamMembers({
        teamId: teamId,
        members: members
    });
    onTeams(team);
}

Parameter description

Send message

  • APIs related to message sending include:
  • Several parameters that are used for all APIs of sending message are explained here:
    • The parameter scene is used to designate Scene. for sending message.
    • The parameter to is used to designate message receiver. If a peer-to-peer messages is sent, it is account; if a team message is sent, it is team ID.
    • The API for sending message will return SDK generated ID, with corresponding field idClient. An exception is that the value is got in the callback beforesend for sending file message.
    • In the callback done, sending status of corresponding information can be determined based on the object error and the field idClient under Message object.
      • If error is null, it means that the message corresponding to idClient is sent successfully.
      • If error is not null, it means the message corresponding to idClient is not sent successfully, and error contains detailed error information.
  • For the following codes, sending a peer-to-peer messages (scene is 'P2P') is taken for an example. If you need to send a team message, you shall replace scene with 'team' and replace to with team ID.

Send text message

var msg = nim.sendText({
    scene: 'p2p',
    to: 'account',
    text: 'hello',
    done: sendMsgDone
});
console.log('sending p2p text message, id=' + msg.idClient);
pushMsg(msg);
function sendMsgDone(error, msg) {
    console.log(error);
    console.log(msg);
    console.log('send' + msg.scene + ' ' + msg.type + 'message' + (!error?'succeeded':'failed') + ', id=' + msg.idClient);
    pushMsg(msg);
}

Preview file

  • Developers can preview the file. Several scenes are available:
    • A file is input with the parameter fileInput to select dom node or node ID.
    • Blob object is input with the parameter blob.
    • The data URL that contains MIME type and base64 is input with the parameter dataURL. This method requires that explorer supports window.Blob.
    • The path of file object in WeChat applet is input with the parameter wxFilePath and to be abandoned. (The path is specially designed for WeChat applet. It is recommended to use filePath for v5.1.0+.)
    • The file path (cross-platform serial) is input with the parameter filePath which is available for applet (5.1.0+), nodejs (5.4.0+ beta test), and react-native(5.3.0+). Any file is input with the parameter which does not support explorer environment.
  • The file MD5 and related information (image width (w) and height (h), audio duration (dur), video width (w), height (h) and duration (dur)) can be input with the parameter fastPass. The feature of accelerated uploading for repeated large file is enabled.
  • v6.3.0 and later can limit file size with the parameter maxSize.
  • The parameter commonUpload (with default value false) can be used for v6.3.0 and later to indicate that common uploading is enabled (maximum file size 100M). By default, false is direct uploading by fragment (with size 4M per fragment, max. 10000 fragments) and "true" is common uploading. If value of the file MD5 shall be returned, common uploading shall be enabled.
  • SDK will upload the file to file server and then transfer acquired file object to developers in the callback done. There are several file objects as below:
  • After getting the file object, developers can invoke "Send file message" to send file message.
  • The limit of file size is max. 100M.
    • The advanced explorer will check file size before the file is uploaded.
    • IE8/IE9 will check file size after the file is uploaded (v5.0.0 and below support IE8).
nim.previewFile({
    type: 'image',
    fileInput: fileInput,
    fastPass '{"w":200,"h":110,"MD5":"xxxxxxxxx"}',
    uploadprogress: function(obj) {
        console.log('total file size: ' + obj.total + 'bytes');
        console.log('uploaded size: ' + obj.loaded + 'bytes');
        console.log('upload progress: ' + obj.percentage);
        console.log('upload progress text: ' + obj.percentageText);
    },
    done: function(error, file) {
        console.log('upload image' + (!error?'succeeded:'failed'));
        // show file to the user
        if (!error) {
            var msg = nim.sendFile({
                scene: 'p2p',
                to: 'account',
                file: file,
                done: sendMsgDone
            });
            console.log('sending p2p image mesage, id=' + msg.idClient);
            pushMsg(msg);
        }
    }
});

Send file message

  • File message is one type under "Send and receive message".
  • Developers can send file message.
    • Several scenes are available:
      • A file is input with the parameter fileInput to select dom node or node ID.
      • Blob object is input with the parameter blob.
      • The data URL that contains MIME type and base64 is input with the parameter dataURL. This method requires that explorer supports window.Blob.
      • The path of file object in WeChat applet is input with the parameter wxFilePath. (The path is specially designed for WeChat applet. It is recommended to use filePath for v5.1.0+.)
      • The file path can be input with the parameter filePath. V5.1.0 supports applet and will support nodejs and react-native in the future.
    • The file MD5 and related information (image width (w) and height (h), audio duration (dur), video width (w), height (h) and duration (dur)) can be input with the parameter fastPass. The feature of accelerated uploading for repeated large file is enabled.
    • v6.3.0 and later can limit file size with the parameter maxSize.
    • The parameter commonUpload (with default value false) can be used for v6.3.0 and later to indicate that common uploading is enabled (maximum file size 100M). By default, false is direct uploading by fragment (with size 4M per fragment, max. 10000 fragments) and "true" is common uploading. If value of the file MD5 shall be returned, common uploading shall be enabled.
    • SDK will upload the file to file server and then transfer acquired file object to users in the callback uploaddone, and edit it into file message to send out.
  • Developers can also Preview files to get file object and then invoke The API to send file message.
  • If the file message is sent, SDK generated idClient will be input in the callback beforesend. If you preview the file and then send it out, The API will return idClient.
  • The parameter type designates file type to be sent, including image, audio file, video and common file, with corresponding value 'image', 'audio', 'video' and 'file' respectively. If it is not input, the value is 'file' by default.
  • The difference among image, audio file, video and common file is that detailed file information is different. For detailed fields, see:
  • The limit of file size is max. 100M.
    • The advanced explorer will check file size before the file is uploaded.
    • IE8/IE9 will check file size after the file is uploaded (v5.0.0 and below support IE8).
nim.sendFile({
    scene: 'p2p',
    to: 'account',
    type: 'image',
    fileInput: fileInput,
    fastPass '{"w":200,"h":110,"MD5":"xxxxxxxxx"}',
    beginupload: function(upload) {
        // - If the developer input fileInput, the fileInput cannot be modified before this callback
        // - After this callback, you can cancel the image upload, and this callback will receive the parameter `upload` and call `upload.abort();` to cancel the file upload
    },
    uploadprogress: function(obj) {
        console.log('total file size: ' + obj.total + 'bytes');
        console.log('uploaded size: ' + obj.loaded + 'bytes');
        console.log('upload progress: ' + obj.percentage);
        console.log('upload progress text: ' + obj.percentageText);
    },
    uploaddone: function(error, file) {
        console.log(error);
        console.log(file);
        console.log('upload' + (!error?'succeeded':'failed'));
    },
    beforesend: function(msg) {
        console.log('sending p2p image mesage, id=' + msg.idClient);
        pushMsg(msg);
    },
    done: sendMsgDone
});

Send geographical location message

var msg = nim.sendGeo({
    scene: 'p2p',
    to: 'account',
    geo: {
        lng: 116.3833,
        lat: 39.9167,
        title: 'Beijing'
    },
    done: sendMsgDone
});
console.log('sending p2p geo message, id=' + msg.idClient);
pushMsg(msg);

Send tip message

  • Tip message is one type under "Send and receive message".
  • The tip message is used to remind status in session, for example, welcome message in session, or prompt message when the session contains sensitive.
var msg = nim.sendTipMsg({
    scene: 'p2p',
    to: 'account',
    tip: 'tip content',
    done: sendMsgDone
});
console.log('sending p2p tip message, id=' + msg.idClient);
pushMsg(msg);

Send custom message

  • Custom message is one type under "Send and receive message".
  • Among the open web-demo source codes of CommsEase, type-1 is "Rock Paper Scissors"; type-2 is "Burn after Reading"; type-3 is "Map Expression"; type-4 is "White Board Teaching".
  • The following codes implement the game rock-paper-scissors by custom message.
var value = Math.ceil(Math.random()*3);
var content = {
    type: 1,
    data: {
        value: value
    }
};
var msg = nim.sendCustomMsg({
    scene: 'p2p',
    to: 'account',
    content: JSON.stringify(content),
    done: sendMsgDone
});
console.log('sending p2p custom message, id=' + msg.idClient);
pushMsg(msg);

Configuration options for sending message

  • The above APIs for sending message can be configured with extra options to meet developers' custom demands for server.
    • custom: Extension field.

      • We recommend creating user profile in JSON format. If it is not JSON format, other clients may abandon the information, although Web client will receive it ordinaryly.
    • pushContent: Custom push text., limited to 500 characters

    • pushPayload: Custom push attribute.

      • We recommend creating user profile in JSON format. If it is not JSON format, other clients may abandon the information, although Web client will receive it ordinaryly.
    • needPushNick: It determines whether a nickname is pushed

    • apns: Special push option. It is used only in team session.

    • apns.accounts: List of accounts requiring special push. If it is null, it means to push to all users in current session.

    • apns.content: It determines that special push is required for text. If it is null, the value is pushContent by default.

    • apns.forcePush: It determines force push. If it is null, the value is "true" by default. "True" means that current content can be pushed to related users even though users in a push list have blocked current session (e.g. mute).

    • isHistoryable: It determines that storage to cloud history is required.

    • isRoamingable: It determines that roaming support is required.

    • isSyncable: It determines that multi-client synchronization is supported for the sender.

    • cc: It determines that cc is supported.

    • isPushable: It determines whether a message is pushed

    • isOfflinable: It determines that offline storage is required.

    • isUnreadable: It determines that the message is included in unread count.

    • needMsgReceipt: It determines that message is acknowledged (if the field is contained, it means that acknowledged receipt is needed). Only when the acknowledged receipt is configured, The API getTeamMsgReads, getTeamMsgReadAccounts and the like can be invoked.

    • yidunEnable: It designates whether it is necessary to use custom anti-spam field, i.e. antiSpamContent. The default value is false which means that it is not required.

    • antiSpamUsingYidun: It determines whether GuideEase anti-spam is enabled for a single message. false means that GuideEase anti-spam is disabled when GuideEase is enabled.

    • antiSpamContent: When yidunEnable is enabled, developers customize anti-spam field with json format {"type": 1, "data": "custom content"}. Notes: type: 1. Text; 2. Image, 3. Video; data content: text or image address or video address.

    • antiSpamBusinessId: It is the extra anti-spam service ID that is configured for a single message by users.

  • We take an example of sending file message here. The API for sending other messages is similar.
var msg = nim.sendText({
    scene: 'p2p',
    to: 'account',
    text: 'hello',
    custom: '{}',
    done: sendMsgDone
});

Send local message

  • The parameter isLocal can be set to true when a message is sent. Then SDK will not send the message, but invoke the callback to indicate success, and update related session.
var value = Math.ceil(Math.random()*3);
var content = {
    type: 1,
    data: {
        value: value
    }
};
var msg = nim.sendCustomMsg({
    scene: 'p2p',
    to: 'account',
    content: JSON.stringify(content),
    isLocal true,
    done: sendMsgDone
});
console.log('sending p2p custom message, id=' + msg.idClient);
pushMsg(msg);

Re-send message

If a message is not sent successfully, it can be re-sent.

nim.resendMsg({
  msg: someMsg,
  done: sendMsgDone
})
console.log('resending message', someMsg)

Forward messages

  • msg: Message to be forwarded
  • scene: New scene.
  • to: New receiver, account or team ID.
nim.forwardMsg({
  msg: someMsg,
  scene: 'p2p',
  to: 'account',
  done: sendMsgDone
})
console.log('forwarding message', someMsg)

Recall message

  • Users can revoke a message that is sent in a certain time in the session. The revocation duration can be configured at CommsEase console.
  • If a tip is required after revocation (see Demo interaction), developers can create a tip message independently and insert it to local database.
  • After the operation "Revoke message", message receiver will receive a System notification of 'deleteMsg' type. For such system notification, msg is the field of deleted message. If it is a team message, all team members will receive the system notification. If a same account logins on multiple clients, other clients will receive the system notification.
  • msg: Message to be revoked
nim.deleteMsg({
  msg: someMsg,
  done: deleteMsgDone
})
console.log('recalling message', someMsg)
function deleteMsgDone (error) {
  console.log('recall message' + (!error?'succeeded:'failed'), error);
}

Mark message as received

  • The process of sending and receiving message is explained firstly. If A sends a message to B, the actual process is:
    • A sends a message to server. If B is online, server will push the message to B. If B is offline, server will store the message offline and then push it to B when B is online.
    • After receiving online and offline message, B shall send acknowledged receipt to server, so that server will not push such message next time when B is online.
    • If B did not send acknowledged receipt to server, server will push such message to B again next time when B logins.
  • By default, SDK will mark a message as "received" after receiving the message (including online and offline message). As a result, such message will not be received at next login. Generally, developers shall not pay attention to The API.
    • At the operation "Support database", SDK will store message to database. If developers find that unread count of session is larger than offline message count, it is necessary to Get unread message from local database.
    • When the "Support database" is not available, if developers want to configure the time of marking message as received, they can set initialization parameter autoMarkRead to false, so that SDK will not automatically mark the message as received. Now, developers need to invoke The API at proper time to mark the message as received, otherwise, the message that is not marked as received will be pushed again next time at login.

Sample codes

var nim = NIM.getInstance({
    autoMarkRead false
});
nim.markMsgRead(someMsg);
// or
nim.markMsgRead([someMsg]);

Read receipt

  • The attribute msgReceiptTime is added to Session object to indicate timestamp of acknowledged receipt. If the field is not null, it means that all messages before the timestamp are acknowledged.

Send acknowledged receipt of message

  • It is available to 'P2P' session only.
  • If the message is null, it will return success.
  • If acknowledged receipt with timestamp larger than input message has been sent, success will be returned.
  • The parameter msg is the final message in the session with acknowledged receipt to be sent, which can be acquired with session.lastMsg.
nim.sendMsgReceipt({
    msg: session.lastMsg,
    done: sendMsgReceiptDone
});
function sendMsgReceiptDone(error, obj) {
    console.log('send message read receipt' + (!error?'succeeded':'failed'), error, obj);
}

Query acknowledged status of message

  • It is available to 'P2P' session only.
var isRemoteRead = nim.isMsgRemoteRead(msg);
Was this topic helpful?
Yes
No
  • Overview
  • Initialization parameters
  • Message object
  • Message scenarios
  • Message types
  • Text object
  • Image object
  • Audio object
  • Video object
  • File object
  • Geographical location object
  • Team notification messages
  • Notification message for call event
  • SuperTeam notification message
  • Process team notification message
  • Send message
  • Send text message
  • Preview file
  • Send file message
  • Send geographical location message
  • Send tip message
  • Send custom message
  • Configuration options for sending message
  • Send local message
  • Re-send message
  • Forward messages
  • Recall message
  • Mark message as received
  • Read receipt
  • Send acknowledged receipt of message
  • Query acknowledged status of message