Send and receive message
Update time: 2024/08/20 15:45:46
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
- Not all initialization parameters are listed here. Please refer to Initialize SDK, and initialization parameters are given in other chapters.
- Initialization parameters for connection
- Initialization parameters for multi-device login
- Initialization parameters for messages
- Initialization parameters for team
- Initialization parameters for user profile
- Initialization parameters for friendship
- Initialization parameters for user relationship
- Initialization parameters for session
- Initialization parameters for system notifications
- Synchronization completed
- Complete initialization codes
Sample codes
javascriptvar 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
andonofflinemsgs
, 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.
- If the current login account sends message at other clients, the callback will also be returned. It is noted that the field
- 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 IDfromNick
: Nickname of message senderfromClientType
: Device types of senderfromDeviceId
: Device ID at sending clientto
: Message receiver, account or team IDtime
: Timestamptype
: Message typessessionId
: ID of Session object for a messagetarget
: 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.
idServer
: Server ID for distinguishing message. It is mainly used to Get cloud message history..
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 notJSON
format, other clients may abandon the information, although Web client will receive it ordinaryly.
- We recommend creating user profile in
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 notJSON
format, other clients may abandon the information, although Web client will receive it ordinaryly.
- We recommend creating user profile in
needPushNick
: It determines whether a nickname is pushedapns
: 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- At the operation Support databaseThe API Update local message can be invoked to update the field to local database only, instead of the server.
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 APIgetTeamMsgReads
,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 pushedisOfflinable
: 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)- After some operations, all team members will receive a related team notification message. For details, see Team notification message.
- Such message will not be included in unread count.
- Please refer to Message object and Type of message.
For receiving and sending different types of messages, see:
- Send message related documents
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
: Namesize
: Size, unit: byteMD5
: MD5url
: URLext
: Extension namew
: Width, unit: pxh
: 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
: Namesize
: Size, unit: byteMD5
: MD5url
: URLext
: Extension namedur
: 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
: Namesize
: Size, unit: byteMD5
: MD5url
: URLext
: Extension namedur
: Length, unit: msw
: Width, resolution, unit: pxh
: 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 ishttp://img-sample.nos-eastchina1.126.net/sample.wmv
, the cover (first frame) image address will behttp://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
: Namesize
: Size, unit: byteMD5
: MD5url
: URLext
: 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
: Longitudelat
: Latitudetitle
: 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 fieldtype
underattach
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 fieldfrom
is account of the user who updates team; the fieldto
is the corresponding team ID; the fieldteam
underattach
is updated Team information.
- After the operation "Update team", all team members will receive a Team notification message of
'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 fieldfrom
is account of the team inviter; the fieldto
is the corresponding team ID; the fieldteam
underattach
is the corresponding Team object; the fieldaccounts
underattach
is the list of invited accounts; the fieldmembers
underattach
is the list of invited team members.
- ordinary team - After the operation "Invite a user to team", all team members will receive a Team notification message of
'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 fieldfrom
is account of the team administrator who kicks members out of the team; the fieldto
is the corresponding team ID; the fieldteam
underattach
is the corresponding Team object; the fieldaccounts
underattach
is the list of removed accounts.
- After the operation "Kick out team member", all team members will receive a Team notification messages of
'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 fieldfrom
is account of inviter; the fieldto
is the corresponding team ID; and the fieldteam
underattach
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 fieldfrom
is account that accepts team invitation; the fieldto
is the corresponding team ID; the fieldteam
underattach
is the corresponding Team object; the fieldmembers
underattach
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 fieldfrom
is account rejecting team invitation and the fieldto
is the corresponding team ID.
- If the invited user selects to "Accept invitation", all team members will receive a Team notification message of
- 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
'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 fieldfrom
is account of the applicant and fieldto
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 fieldfrom
is account that accepts team application; the fieldto
is the corresponding team ID; the fieldteam
underattach
is the corresponding Team object; the fieldaccount
underattach
is account of the applicant; the fieldmembers
underattach
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 fieldfrom
is account that rejects team application; the fieldto
is the corresponding team ID; the fieldteam
underattach
is the corresponding Team.
- If they "Accept team application", all team members will receive a Team notification message of
- A user can Apply for joining advanced team, owner and adiministor of the target team will receive a System notification of
'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 fieldfrom
is account of the member who adds team administrator; the fieldto
is the corresponding team ID; the fieldaccounts
underattach
is the list of accounts added as administrators; the fieldmembers
underattach
is the list of team members added as administrators.
- After the operation "Add team administrator", all Team members will receive a Team notification message of
'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 fieldfrom
is account of the administrator who removes team administrator; the fieldto
is the corresponding team ID; the fieldaccounts
underattach
is the list of accounts of removed administrators; the fieldmembers
underattach
is the list of members in the team where manager is removed.
- After the operation "Remove team administrator", all Team members will receive a Team notification message of
'leaveTeam'
(Actively leave team)- After the operation "Actively leave team", all Team members will receive a Team notification message of
'leaveTeam'
type. For such team notification message, the fieldfrom
is account of the member who leaves team; the fieldto
is corresponding team ID; the fieldteam
underattach
is corresponding Team object.
- After the operation "Actively leave team", all Team members will receive a Team notification message of
'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 fieldfrom
is account of member who dismisses the team; the fieldto
is corresponding team ID.
- After the operation "Dismiss team", all Team members will receive a Team notification message of
'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 fieldfrom
is account of the member who transfers team; the fieldto
is corresponding team ID; the fieldteam
underattach
is corresponding Team object; the fieldaccount
underattach
is account of the new owner; the fieldmembers
underattach
is the list of team members (including original and new owner).
- After the operation "Transfer a team", all Team members will receive a Team notification message of
'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 fieldfrom
is operator; the fieldto
is the corresponding team ID; the fieldteam
underattach
is the corresponding Team object; the fieldaccount
underattach
is muted account; the fieldmembers
underattach
is the list of muted team members.
- After the operation "Update mute status of team members", all Team members will receive a Team notification message of
- If there is a field
account
oraccounts
underattach
, the fieldusers
underattach
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 fieldfrom
is account of the user who updates team; the fieldto
is corresponding team ID; the fieldteam
underattach
is updated SuperTeam information.
- After the operation "Update team", all team members will receive a Team notification message of
'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 fieldfrom
is account of the team inviter; the fieldto
is corresponding team ID; the fieldteam
underattach
is corresponding SuperTeam object; the fieldaccounts
underattach
is the list of invited accounts; the fieldmembers
underattach
is the list of invited team members.
- After the operation "Invite a user to team", all SuperTeam members will receive a SuperTeam notification message of
'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, thefrom
field is account of the team administrator who kicks members out of the team; theto
field is the corresponding team ID; theteam
field underattach
is corresponding Object of SuperTeam; theaccounts
field underattach
is the list of kicked-out accounts.
- After the operation "Kick out team member", all SuperTeam members will receive a SuperTeam notification message of
'leaveSuperTeam'
(Actively leave team)- After the operation "Actively leave team", all Team members will receive a Team notification message of
'leaveSuperTeam'
type. For such team notification message, the fieldfrom
is account of the member who leaves team; the fieldto
is corresponding team ID; the fieldteam
underattach
is corresponding Team object.
- After the operation "Actively leave team", all Team members will receive a Team notification message of
Process team notification message
- This chapter covers processing for team and team members, which shall be combined with chapters as below:
onteams
,onsynccreateteam
,onteammembers
,onupdateteammember
under Initialization parameters for teamonmsg
Under Initialization parameters for messages- Team notification message
Sample codes
javascriptfunction 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
- nim.cutTeamMembersByAccounts is invoked to merge team members.
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 callbackbeforesend
for sending file message. - In the callback
done
, sending status of corresponding information can be determined based on the objecterror
and the fieldidClient
under Message object.- If
error
is null, it means that the message corresponding toidClient
is sent successfully. - If
error
is not null, it means the message corresponding toidClient
is not sent successfully, anderror
contains detailed error information.
- If
- The parameter
- 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 replacescene
with'team'
and replaceto
with team ID.
Send text message
- Text message is one type under "Send and receive message".
javascriptvar 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
andto be abandoned
. (The path is specially designed for WeChat applet. It is recommended to usefilePath
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.
- A file is input with the parameter
- 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 parametermaxSize
.- The parameter
commonUpload
(with default valuefalse
) can be used forv6.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).
javascriptnim.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 usefilePath
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.
- A file is input with the parameter
- 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 parametermaxSize
.- The parameter
commonUpload
(with default valuefalse
) can be used forv6.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.
- Several scenes are available:
- 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 callbackbeforesend
. If you preview the file and then send it out, The API will returnidClient
. - 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).
javascriptnim.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
- Geographical location message is one type under "Send and receive message". For the parameter
geo
, seeGeographical location message.
javascriptvar 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.
javascriptvar 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.
javascriptvar 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 notJSON
format, other clients may abandon the information, although Web client will receive it ordinaryly.
- We recommend creating user profile in
-
pushContent
: Custom push text., limited to 500 characters -
pushPayload
: Custom push attribute.- We recommend creating user profile in
JSON
format. If it is notJSON
format, other clients may abandon the information, although Web client will receive it ordinaryly.
- We recommend creating user profile in
-
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 APIgetTeamMsgReads
,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 isfalse
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
: WhenyidunEnable
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.
javascriptvar msg = nim.sendText({
scene: 'p2p',
to: 'account',
text: 'hello',
custom: '{}',
done: sendMsgDone
});
Send local message
- The parameter
isLocal
can be set totrue
when a message is sent. Then SDK will not send the message, but invoke the callback to indicate success, and update related session.
javascriptvar 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.
javascriptnim.resendMsg({
msg: someMsg,
done: sendMsgDone
})
console.log('resending message', someMsg)
Forward messages
msg
: Message to be forwardedscene
: New scene.to
: New receiver, account or team ID.
javascriptnim.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
jsnim.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
tofalse
, 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
javascriptvar 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.- Now, it is available to
'P2P'
session only. - The field can be seen only when acknowledged receipt is sent.
- The API Send acknowledged receipt of message can be invoked to send acknowledged receipt of message.
- The API Query acknowledged status of message can be invoked to query that a message is acknowledged.
- Now, it is available to
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.
javascriptnim.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.
javascriptvar isRemoteRead = nim.isMsgRemoteRead(msg);