Messaging
Update time: 2022/08/29 03:50:29
Overview
SDK provides a complete set of messaging management services, including messaging, storing messages, uploading and downloading attachments, and managing recent contacts. It originally supports sending various types of messages, including text, audio, image, video, file, geographic location, reminder etc., and supports sending custom messages as well. For details of the messaging features, please refer to basic messaging features in the product introduction.
NIMMessageType
Message type
Enumeration | Value | Description |
---|---|---|
kNIMMessageTypeText | 0 | Text message |
kNIMMessageTypekNIMMessageTypeImageText | 1 | Image message |
kNIMMessageTypeAudio | 2 | Audio message |
kNIMMessageTypeVideo | 3 | Video message |
kNIMMessageTypeLocation | 4 | Location message |
kNIMMessageTypeNotification | 5 | System notifications (including those for joining and exiting team, etc., |
kNIMMessageTypeFile | 6 | File message |
kNIMMessageTypeTips | 10 | Reminder type message, content of which should be from the kNIMMsgKeyServerExt field in the message structure and filled in according to format requirements |
kNIMMessageTypeRobot | 11 | and AI robot messages (not yet available) |
kNIMMessageTypeCustom | 100 | Custom message |
kNIMMessageTypeUnknown | 1000 | Unknown type of message, it is the default value |
NIMMessageFeature
Message type
Enumeration | Value | Description |
---|---|---|
kNIMMessageFeatureDefault | 0 | Default |
kNIMMessageFeatureLeaveMsg | 1 | Offline message |
kNIMMessageFeatureRoamMsg | 2 | Roaming message |
kNIMMessageFeatureSyncMsg | 3 | Default messages, which are synchronized to each terminal upon multi-terminal login |
kNIMMessageFeatureCustomizedMsg | 4 | Passthrough message |
NIMIMMessage
Basic message contents
Type | Parameter | Description |
---|---|---|
NIMSessionType | SessionType | Session type, for details please refer to NIMSessionType |
string | SenderID | Sender ID, filled out by server, which the sender may ignore |
string | ReceiverID | Receiver's id (required), which should be your own id when sending a message to yourself |
NIMClientType | SenderClientType | Sender client type, filled out by server, which the sender may ignore |
string | SenderDeviceId | Sender device id, filled out by server, which the sender may ignore |
string | SenderNickname | Sender nickname, filled out by server, which the sender may ignore |
long | TimeStamp | Message timestamp (13-digit UNIX timestamp in milliseconds) |
NIMMessageType | MessageType | Message type, see NIMMessageType for details |
string | ClientMsgID | Message uuid, unique identifier, to be completed by sender |
string | ServerMsgId | Server-side message id, to be completed by server |
string | ServerExtension | It is the third-party extension field and must be non-formative characters tring that can be parsed into json, with length limit 1024. |
bool | ResendFlag | To resend message? Send for the first time:0, resend the message: 1 |
bool | NeedPush | If push is needed, 1: yes, 0: no |
bool | NeedCounting | (Optional) Is counting needed for push message (corner mark), 1: yes, 0: no |
bool | NeedPushNick | (Optional) Whether push messages need prefixes, set to true by default |
string | PushContent | Custom push content, with a length not exceeding 200 bytes |
JsonExtension | PushPayload | Custom push attributes, must be unformatted json string with a length limited to 2048 |
bool | ServerSaveHistory | (Optional) The message is once saved on the cloud? The default is 1, 1: yes, 0: no, if roaming and offline features are supported, then it must be set to 1 |
bool | Roaming | (Optional) Enable roaming for the message? The default is 1, 1: yes, 0: no |
bool | MultiSync | (Optional) Enable multi-terminal sync for the message? The default is 1, 1: yes, 0: no |
bool | Routable | (Optional) The message is copied? 0:no, 1:yes, follow app router configuration in default |
bool | SavedOffline | (Optional) Save messages offline? The default is 1, 1: yes, 0: no, if roaming is supported, then it must be set to 1 |
bool | AntiSpamEnabled | Is Yidun anti-spam needed? 1: yes, 0: no |
string | AntiSpamContent | (Optional) Anti-spam field customized by developer, length limit: 5000 characters, format: json string, {"type": 1: text, 2: image, 3 video, "data": "Text content or image address or video address"} |
bool | ClientAntiSpamHitting | It determines to filter via the client anti-spam service. According to "Match with message filtering rules", if it is matched with relate rules, the value is "true", and the other party will not receive the message. It is mainly used for filtering sensitive words related to games. |
string | AntiSpamBizID | (Optional) It is the extra anti-spam service ID that is configured for a single message by users (unavailable temporarily). |
string | LocalFilePath | Local absolute path of multimedia message resource, managed by SDK locally and is required when sending multimedia messages. In case of image messages, when setting up thumbnail download, this path should be the local absolute path of the thumbnails |
string | TalkID | Session id, optional for sender. The receiver receives the sender id |
string | ResourceId | Session id, optional for sender. The receiver receives the client message id |
NIMMsgLogStatus | MsgLogStatus | Local message status, see message status type for details) |
NIMMsgLogSubStatus | MsgLogSubStatus | (Local message sub-status, see message sub-status type for details) |
string | LocalExtension | Local extension contents, local storage only, reserved field |
Note: Roaming means that the messages that have been received at one terminal will be delivered other offline clients (limited to the last 100 sessions on the server). Multi-terminal synchronization means that when multiple device platforms log in at the same time, a message sent by one terminal will be synchronously received by other terminals. Offline means if the receiver is offline when the message is sent, it can receive the message as soon as it goes online again.
Description of message settings:
SavedOffline | ServerSaveHistory | Roaming | MultiSync | |
---|---|---|---|---|
Offline message | 1 | 1 | optional | optional |
Roaming message | 1 | 1 | 1 | optional |
Multi-terminal message sync | optional | optional | optional | 1 |
Send message
SDK supports common built-in messages types such as text, picture, voice, video, file, geographic location, reminder (NIMMessageType), as well as sending custom messages. At the same time, we also provide a stop sending interface, which is currently mainly used to stop sending file message that is being uploaded.
- API prototype
public static void SendMessage(NIMIMMessage message, ReportUploadProgressDelegate action = null);
- Parameter Description
Parameter | Description |
---|---|
message | For message content, see NIMIMMessage. |
action | Notification of upload progress callback, which informs upload progress of self-uploaded attachments such as images, audio and video files (if any) |
Message setting
The following message property settings (corresponding to the field in NIMIMMessageare also provided for sending messages:
-
Messages can have two types of extension fields, namely server extension field kNIMMsgKeyServerExt and local extension field kNIMMsgKeyLocalExt, each with a maximum length of 1024 bytes. The server extension field will be sent to other terminals, while the local extension field is only valid locally. Both extension fields will be stored by the SDK in the database.
-
Push text field (
kNIMMsgKeyPushContent
, with a maximum length of 200 bytes) and custom push attribute (kNIMMsgKeyPushPayload
, with a maximum length of 2048 bytes), please pay attention to the maximum length. If push text is set, the text will be displayed in the notification bar when the message is received by the recipient, if not, then SDK's default text will be used. -
Whether push field is needed
kNIMMsgKeyPushEnable
, 0: not needed, 1: needed. -
Whether message count field is needed (
kNIMMsgKeyNeedBadge
), 0: not needed, 1: needed. -
Whether push nickname is needed (
kNIMMsgKeyNeedPushNick
), 0: not needed, 1: needed. -
Whether to store the message in the cloud (
kNIMMsgKeyHistorySave
), if it is set to 0, the message cannot be obtained by calling the interface of server message history. 0: Not needed, 1: Needed. -
Whether the message supports roaming (
kNIMMsgKeyMsgRoaming
). If it is set to 1, even if a certain client has received the message, other clients can still obtain it by roaming when they log in again. 0: Not needed, 1: Needed. -
Whether the message supports multi-terminal synchronization (
kNIMMsgKeyMsgSync
). If it is set to 1, a message sent will be synchronized to other clients logged in at the same time. 0: Not needed, 1: Needed.
Team messages have forced push attributes (can be used to implement @ features, etc.):
-
Whether force push field (
kNIMMsgKeyIsForcePush
)is needed, 0: not needed, 1: needed. -
Force push list field (
kNIMMsgKeyForcePushList
), should be filled in with the specified account id string array json, and left empty if forced push is enabled for all. -
Text field (
kNIMMsgKeyForcePushContent
) in force push team message
Anti-spam field:
-
The ID of the anti-spam rule specified by the developer for the message (kMsgTagAntiSpamBusinessId), should be the same as that on the server side
-
Whether YiDun anti-spam is needed (kNIMMsgKeyAntiSpamEnable), 0: not needed, 1: needed.
-
(Optional) Anti-spam field customized by developer (kNIMMsgKeyAntiSpamContent), length limit: 5000 characters, format: json string, {"type": 1: text, 2: image, 3 video, "data": "Text content or image address or video address"}
-
Whether a single message uses YiDun anti-spam (kNIMMsgKeyAntiSpamUsingYiDun), 0: (YiDun activated) not passing YiDun anti-spam but general anti-spam, with all other matters still subject to original rules.
Text message
Create text message content, complete the necessary message setting and send the message through theSendMessage
interface.
NIMTextMessage
Text message
NIMTextMessage
is derived from NIMIMMessage and will succeed all father-class fields.
Type | Parameter | Field |
---|---|---|
NIMMessageType | MessageType | It is designated as NIMMessageType.kNIMMessageTypeText. |
string | TextContent | Text content |
- Example
//In case of p2p message and test account test1
NIMTextMessage msg = new NIMTextMessage();
msg.ReceiverID = "test1";
msg.SessionType = NIMSessionType.kNIMSessionTypeP2P;
msg.TimeStamp=1520500638234;//Current UNIX timestamp, unit: ms
msg.ClientMsgID = "uuid";//Generate my unique uuid;
msg.TextContent = "This is a text message." ;
//Other message settings, same as above
msg.Roaming = true;
msg.SavedOffline = true;
msg.ServerSaveHistory = true;
//If anti-spam is needed
msg.AntiSpanEnabled = true;
//Assemble anti-spam content
JsonExtension jx = new JsonExtension();
jx.AddItem("type",1);
jx.AddItem("data",msg.TextContent);//If it is image or video type, attachment url shall be filled in.
msg.AntiSpamContent = jx.Value;
...
NIM.TalkAPI.SendMessage(msg,null);
Picture message
Create image message content, complete the necessary message setting and send the message through the SendMessage
interface. The sent local image file will be automatically uploaded.
NIMTextMessage
is derived from NIMIMMessage and will succeed all father-class fields.
Type | Parameter | Field |
---|---|---|
NIMMessageType | MessageType | It is designated as NIMMessageType.kNIMMessageTypeImage. |
NIMImageAttachment | ImageAttachment | Content of image attachment |
NIMMessageAttachment
File attachment base class
Type | Parameter | Field |
---|---|---|
string | MD5 | md5 of the file content |
Int64 | Size | File size, 64-bit integer |
string | RemoteUrl | http url of the file |
string | DisplayName | file name |
string | FileExtension | File extension |
string | LocalResID | Local file resource id, not required |
The attachment content of an image message NIMImageAttachment
is derived from NIMMessageAttachment, with field description.
Type | Parameter | Field |
---|---|---|
int | Width | Image width |
int | Height | Image height |
- Example
//In case of p2p message and test account test1
NIMImageMessage msg = new NIMImageMessage();
msg.ReceiverID = "test1";
msg.SessionType = NIMSessionType.kNIMSessionTypeP2P;
msg.TimeStamp=1520500638234;//Current UNIX timestamp, unit: ms
msg.ClientMsgID = "uuid";//Generate my unique uuid;
//If a local file is sent, LocalFilePath shall be assigned.
msg.LocalFilePath="c:\\img.png";
//Assemble attachment content
NIMImageAttachment attachment = new NIMImageAttachment();
attachment.MD5 = "0ca175b9c0f726a831d895e269332461";
attachment.Size = 409600;
attachment.RemoteUrl="http://xxxxxx/img.png";//If local file is sent, the value is null.
attachment.DisplayName="img";
attachment.FileExtension="png";
//Set image height and width
attachment.Width = 800;
attachment.Height = 600;
msg.ImageAttachment = attachment;
//Other message settings
...
NIM.TalkAPI.SendMessage(msg,null);
Voice message
Create voice message content, complete the necessary message setting and send the message through theSendMessage
interface. The sent local audio file will be automatically uploaded.
NIMAudioMessage
is derived from NIMIMMessage and will succeed all father-class fields.
Type | Parameter | Field |
---|---|---|
NIMMessageType | MessageType | It is designated as NIMMessageType.kNIMMessageTypeAudio. |
NIMAudioAttachment | AudioAttachment | Content of audio attachment |
The attachment content of an audio message NIMAudioAttachment
is derived fromNIMMessageAttachment, with field description.
Type | Parameter | Field |
---|---|---|
int | Duration | Audio message duration |
- Example
//In case of p2p message and test account test1
NIMAudioMessage msg = new NIMAudioMessage();
msg.ReceiverID = "test1";
msg.SessionType = NIMSessionType.kNIMSessionTypeP2P;
msg.TimeStamp=1520500638234;//Current UNIX timestamp, unit: ms
msg.ClientMsgID = "uuid";//Generate my unique uuid;
//If a local file is sent, LocalFilePath shall be assigned.
msg.LocalFilePath="c:\\audio.aac";
//Assemble attachment content
NIMAudioAttachment attachment = new NIMAudioAttachment();
attachment.MD5 = "0ca175b9c0f726a831d895e269332461";
attachment.Size = 409600;
attachment.RemoteUrl="http://xxxxxx/audio.aac";//If local file is sent, the value is null.
attachment.DisplayName="audio";
attachment.FileExtension="aac";
//Set the duration
attachment.Duration = 8000;//ms
msg.AudioAttachment = attachment;
//Other message settings
...
NIM.TalkAPI.SendMessage(msg,null);
Video message
Create video message content, complete the necessary message setting and send the message through the SendMessage
interface. The sent local video file will be automatically uploaded.
NIMVideoMessage
is derived from NIMIMMessage
and will succeed all father-class fields.
Type | Parameter | Field |
---|---|---|
NIMMessageType | MessageType | It is designated as NIMMessageType.kNIMMessageTypeVideo. |
NIMVideoAttachment | VideoAttachment | Content of video attachment |
The attachment content of a video message NIMVideoAttachment
is derived fromNIMMessageAttachment, with field description.
Type | Parameter | Field |
---|---|---|
int | Duration | Audio message duration |
int | Width | Image width |
int | Height | Image height |
- Example
//In case of p2p message and test account test1
NIMVideoMessage msg = new NIMVideoMessage();
msg.ReceiverID = "test1";
msg.SessionType = NIMSessionType.kNIMSessionTypeP2P;
msg.TimeStamp=1520500638234;//Current UNIX timestamp, unit: ms
msg.ClientMsgID = "uuid";//Generate my unique uuid;
//If a local file is sent, LocalFilePath shall be assigned.
msg.LocalFilePath="c:\\video.mp4";
//Assemble attachment content
NIMVideoAttachment attachment = new NIMVideoAttachment();
attachment.MD5 = "0ca175b9c0f726a831d895e269332461";
attachment.Size = 409600;
attachment.RemoteUrl="http://xxxxxx/video.mp4";//If local file is sent, the value is null.
attachment.DisplayName="video";
attachment.FileExtension="mp4";
//Set video length and image length and width
attachment.Duration = 8000;//ms
attachment.Width = 800;
attachment.Height = 600;
msg.VideoAttachment = attachment;
//Other message settings
...
NIM.TalkAPI.SendMessage(msg,null);
Geographic location
Create location message content, complete the necessary message setting and send the message through the SendMessage
interface.
NIMLocationMessage
Location message
Type | Parameter | Field |
---|---|---|
NIMMessageType | MessageType | It is designated as NIMMessageType.kNIMMessageTypeLocation. |
NIMLocationMsgInfo | LocationInfo | Content of geographical location attachment |
The attachment contentNIMLocationMsgInfo
of the location message contains description of
Type | Parameter | Field |
---|---|---|
string | Description | Location description |
int | Latitude | Latitude |
int | Longitude | Longitude |
- Example
//In case of p2p message and test account test1
NIMLocationMessage msg = new NIMLocationMessage();
msg.ReceiverID = "test1";
msg.SessionType = NIMSessionType.kNIMSessionTypeP2P;
msg.TimeStamp=1520500638234;//Current UNIX timestamp, unit: ms
msg.ClientMsgID = "uuid";//Generate my unique uuid;
//Assemble attachment content
NIMLocationMsgInfo attachment = new NIMLocationMsgInfo();
//Set location name, latitude and longitude
attachment.Description = "Hangzhou";
attachment.Latitude = 30.3;
attachment.Longitude = 120.2;
msg.LocationInfo = attachment;
//Other message settings
...
NIM.TalkAPI.SendMessage(msg,null);
File message
Create file message content, complete the necessary message setting and send the message through the SendMessage
interface.
NIMFileMessage
is derived from NIMIMMessage and will succeed all father-class fields.
Type | Parameter | Field |
---|---|---|
NIMMessageType | MessageType | It is designated as NIMMessageType.kNIMMessageTypeFile. |
NIMMessageAttachment | FileAttachment | For content of file attachment, see NIMMessageAttachment. |
- Example
//In case of p2p message and test account test1
NIMVideoMessage msg = new NIMVideoMessage();
msg.ReceiverID = "test1";
msg.SessionType = NIMSessionType.kNIMSessionTypeP2P;
msg.TimeStamp=1520500638234;//Current UNIX timestamp, unit: ms
msg.ClientMsgID = "uuid";//Generate my unique uuid;
msg.LocalFilePath="c:\\Document.doc";
//Assemble attachment content
NIMMessageAttachment attachment = new NIMMessageAttachment();
attachment.MD5 = "0ca175b9c0f726a831d895e269332461";
attachment.Size = 409600;
attachment.DisplayName="Document";
attachment.FileExtension="doc";
msg.FileAttachment = attachment;
//Other message settings
...
NIM.TalkAPI.SendMessage(msg,null);
Tip message
Create reminder message content, complete the necessary message setting and send the message through the SendMessage
interface. If sending to server is not needed, the developer can use the insert local message to store the message in the database and update the session class table.
NIMTipMessage
Tip message
NIMTipMessage
is derived from NIMIMMessage and will succeed all father-class fields.
Type | Parameter | Field |
---|---|---|
NIMMessageType | MessageType | It is designated as NIMMessageType.kNIMMessageTypeTips. |
string | TextContent | Text content |
string | Attachment | It is the content of message tip attachment, with custom json character string, and used for independent parsing and application. |
- Example
//The team message is taken as an example. The test team id is 122222.
NIMTipMessage msg = new NIMTipMessage();
msg.ReceiverID = "122222";
msg.SessionType = NIMSessionType.kNIMSessionTypeTeam;
msg.TimeStamp=1520500638234;//Current UNIX timestamp, unit: ms
msg.ClientMsgID = "uuid";//Generate my unique uuid;
//Assemble attachment content
msg.TextContent = "This is a message tip."
msg.Attachment = "attachment";//It is custom attachment content and used for independent parsing.
//Other message settings
...
Method 1:
//Send a message to the other party
NIM.TalkAPI.SendMessage(msg,null);
Method 2:
//If it is inserted locally, instead of being sent to the other party, the interface for inserting message history shall be used.
NIM.Messagelog.MessagelogAPI.WriteMsglog("122222",true, msg, (code, msgId)=>
{
...
});
Custom message
Create custom message content, complete the necessary message setting and send the message through the SendMessage
interface. SDK will not parse the specific content of custom messages, and the corresponding work should be assumed by the developer. SDK will save custom message to message database, which will be shown in message history together with built-in message.
NIMCustomMessage
Custom message
NIMCustomMessage<T>
is derived from NIMIMMessage and will succeed all father-class fields.
Type | Parameter | Field |
---|---|---|
NIMMessageType | MessageType | It is designated as NIMMessageType.kNIMMessageTypeCustom. |
string | Extention | Text content |
T | CustomContent | It is the content of custom message tip attachment, with custom json character string, and used for independent parsing and application. T is custom object that can be serialized into json, and succeeded from NimJsonObject. |
- Example
//Define custom class independently
public class CustomMessageAttachment:NimJsonObject<CustomMessageAttachment>
{
//Custom field 1
[JsonProperty("customFiled1")]
public string customFiled1 {set;get;}
//Custom field 2
[JsonProperty("customFiled2")]
public int customFiled2 {set;get;}
}
//The team message is taken as an example. The test team id is 122222.
NIMCustomMessage<CustomMessageAttachment> msg = new NIMCustomMessage<CustomMessageAttachment>();
msg.ReceiverID = "122222";
msg.SessionType = NIMSessionType.kNIMSessionTypeTeam;
msg.TimeStamp=1520500638234;//Current UNIX timestamp, unit: ms
msg.ClientMsgID = "uuid";//Generate my unique uuid;
//Assemble attachment content
CustomMessageAttachment attachment = new CustomMessageAttachment();
attachment.customFiled1 = "Custom content";
attachment.customFiled2 = 10;
msg.Extention = "Content of custom message";
msg.CustomContent = attachment;//Custom attachment content, for independent parsing.
//Other message settings
...
NIM.TalkAPI.SendMessage(msg,null);
Team force push message
Send force push message to a team, and @ designated members or all members
TeamForecePushMessage
Parameter description
Type | Parameter | Description |
---|---|---|
List |
ReceiverList | Set of account ids of @ members for force push |
bool | IsForcePush | It determines to force push. |
string | Content | Content of force push |
- API prototype
public static void SendTeamFrocePushMessage(NIMIMMessage message, TeamForecePushMessage forceMsg, ReportUploadProgressDelegate action = null);
- Parameter Description
Parameter | Description |
---|---|
message | For message content, see "Send messages. |
forceMsg | For settings of force push message, see TeamForcePushMessage |
action | It is the notification of callback for uploading files, and the message for automatic upload is not required. The value is null. |
- Example
//The team message is taken as an example. The test team id is 1222222.
NIMTextMessage msg = new NIMTextMessage();
msg.ReceiverID = "1222222";
msg.SessionType = NIMSessionType.kNIMSessionTypeTeam;
msg.TimeStamp=1520500638234;//Current UNIX timestamp, unit: ms
msg.ClientMsgID = "uuid";//Generate my unique uuid;
msg.TextContent = "This is a text message." ;
//Other message settings
...
//Force push to team members test1, test2
TeamForecePushMessage forePush = new TeamForecePushMessage();
forePush.IsForcePush = true;
forePush.ReceiverList = new List<string>();
forePush.ReceiverList.add("test1");
forePush.ReceiverList.add("test2");
forePush.Content = "This is a force push message";
NIM.TalkAPI.SendTeamFrocePushMessage(msg,forePush,null);
Sending result notification
Sending is successful or failed, and the result also contains tag (if any) for client anti-spam hit.
MessageAck
Parameter description
Type | Parameter | Description |
---|---|---|
string | TalkId | Session ID |
string | MsgId | Message id |
ResponseCode | Response | Error code |
bool | ClientAntiSpam | Is there a hit with client anti-spam, 1: Yes, 0: No |
- API prototype
void OnSendMessageResult(object sender,MessageArcEventArgs args)
{
....
}
//Monitor event
NIM.TalkAPI.OnSendMessageCompleted += OnSendMessageResult;
//Cancel monitoring
NIM.TalkAPI.OnSendMessageCompleted -= OnSendMessageResult;
Stop sending message
Stop sending message. Currently it only can be used on file messages, meaning sending can be terminated during file upload. It can't be used on a file that has already been uploaded.
- API prototype
public static void StopSendMessage(NIMIMMessage message, ReportUploadProgressDelegate action = null);
- Parameter Description
Parameter | Description |
---|---|
message | Structure of the message to be stopped |
action | Reserved, not in use for now |
- Example
//Current available file type, required
NIMIMMessage msg = new NIMIMMessage();
msg.MessageType = NIMMessageType.kNIMMessageTypeFile;
msg.ClientMsgID = "uuid";//Unique uuid of the message to be stopped, required
//Interrupt sending
NIM.TalkAPI.StopSendMessage(msg,null);
Receive message
The developer needs to register the event monitoring of message reception before logging in to the SDK. Message receiving covers online, offline, synchronized, roaming messages, etc. If a multimedia message is received, the SDK will automatically download attachments in the background by default. In case of voice message, the audio file will be downloaded directly. In case of image message, only the thumbnail will be downloaded, and you can get the original image through the download interface.
NIMReceivedMessage
Parameter description
Type | Parameter | Description |
---|---|---|
ResponseCode | ResponseCode | Error code |
NIMIMMessage | MessageContent | For message content, see NIMIMMessage. Different message types have different definitions. Refer to Send messages. |
NIMMessageFeature | Feature | See NIMMessageFeature |
TeamForecePushMessage | TeamPushMsg | For content of team forced push message, see TeamForecePushMessage |
1.Receive messages online
- API prototype
public static EventHandler<NIMReceiveMessageEventArgs> OnReceiveMessageHandler;
- Example
void OnMessageReceived(object sender,MessageArcEventArgs args)
{
if (args != null && args.Message != null) {
//Process various types of messages
if (args.Message.MessageContent.MessageType == NIMMessageType.kNIMMessageTypeText) {
...
}
else if (args.Message.MessageContent.MessageType == NIMMessageType.kNIMMessageTypeAudio) {
...
}
else if (args.Message.MessageContent.MessageType == NIMMessageType.kNIMMessageTypeVideo) {
...
}
else if (args.Message.MessageContent.MessageType == NIMMessageType.kNIMMessageTypeImage)
{
...
}
else
{
...
}
}
....
}
//Monitor event
NIM.TalkAPI.OnReceiveMessageHandler += OnMessageReceived;
//Cancel monitoring
NIM.TalkAPI.OnReceiveMessageHandler -= OnMessageReceived;
2. Receive offline synchronized roaming message
Receive batch messages, such as offline, roaming, and synchronized bulk messages. If this batch interface is also registered while registering receive message callback, when there are incoming batch messages, this interface will be used to notify the application. For example, for offline messages received after logging in, etc., the event monitoring must be registered before logging in.
- API prototype
public static void RegReceiveBatchMessagesCb(ReceiveBatchMesaagesDelegate cb)
- Parameter Description
Parameter | Description |
---|---|
cb | Callback of batch messages |
- Example
void OnBatchMessagesReceived(List<NIMReceivedMessage> msgsList)
{
if (msgsList != null)
{
//Enumerate array, process messages
foreach (NIMReceivedMessage v in msgsList)
{
....
}
}
}
//Monitor event
NIM.TalkAPI.RegReceiveBatchMessagesCb(OnBatchMessagesReceived);
//Cancel monitoring
NIM.TalkAPI.RegReceiveBatchMessagesCb(null);
3. Filter team notification message
Register the callback for whether filtering incoming team notifications. If this callback returns true, the SDK deems the notification as processed, therefore it will not deliver it through the receive message channel, and will not save it to the local database.
- API prototype
public static void RegTeamNotificationFilterCb(TeamNotificationFilterDelegate action);
- Parameter Description
Parameter | Description |
---|---|
action | Callback for filtering team notifications |
- Example
bool OnTeamNotificationFiltered(NIMIMMessage msg,string jsonExtension)
{
if (msg == null)
return false;
...
//If a notification message is processed and filtered, "true" will be returned; otherwise, "false" will be returned.
return true;
}
//Monitor event
NIM.TalkAPI.RegTeamNotificationFilterCb(OnBatchMessagesReceived);
//Cancel monitoring
NIM.TalkAPI.RegTeamNotificationFilterCb(null);
Forward message
The user gets a new message object via construction API, and then calls the message sending interface.
- API prototype
public static NIMIMMessage CreateRetweetMessage(NIMIMMessage srcMsg, NIMMessageSetting msgSetting, string msgId, string sessionId, Session.NIMSessionType sessionType, long timetag);
- Parameter Description
Parameter | Description |
---|---|
srcMsg | Received message content. For the content, see NIMIMMessage. |
msgSetting | Message setting, for details, please refer to message setting description |
msgId | New message uuid generated |
sessionId | The other party's id, forwarded, user account or team id |
sessionType | Session type, 0: p2p message 1: team message |
timetag | Current timestamp (in milliseconds)s |
- Example
//Assume srcMsg being the message body that has been sent or received.
NIMIMMessage srcMsg;
//Message settings, to be configured as needed
NIMMessageSetting msgSetting = new NIMMessageSetting();
msgSettting.ServerSaveHistory = true;
...
//A new message generated through srcMsg.
long timeNow = 1520500638234;//Current UNIX timestamp, unit: ms
string sessionid = "1222222";
string clientMsgID = "uuid2";//A generated new unique uuid;
NIMSessionType sessionType = NIMSessionType.kNIMSessionTypeTeam;
NIMIMMessage newMsg = NIM.TalkAPI.CreateRetweetMessage(srcMsg,msgSettting,clientMsgID,sessionid,sessionType,timeNow);
NIM.TalkAPI.SendMessage(newMsg,null);
Recall message
Sender, team owner and manager can perform recall through this interface (not applicable to chat room messages). This operation is generally time-limited (subject to global APP settings), and 508 is returned if the limit is exceeded. By registering callback notification for message recall, the developer receives notifications of message recalls on other clients. After receiving the notification, the SDK will mark the message as deleted in the message history. At the same time, the developer deletes the message displayed on the interface and can even insert a corresponding prompt if needed. For related development examples, refer to IM Demo.
RecallNotification
Parameter description
Type | Parameter | Description |
---|---|---|
NIMSessionType | SessionType | Session type, 0: p2p message 1: team message |
string | SenderId | Message from ID |
string | ReceiverId | Message to ID |
string | MsgId | Unique id of the message |
string | NOtify | Custom notification copy |
long | Timetag | Timestamp of recall operation (in milliseconds)s |
NIMMessageFeature | Feature | Type of the recalled message, see NIMMessageFeature for details |
bool | MsgLocalExist | Whether the recalled message exists locally. For example, if the other party sent and recalled a message while offline, then the other party gets an offline recall notification after going online, the tag should be false |
long | MsgTimetag | Timestamp of recalled message, unit: ms |
string | Nickname | Nickname of the sender of the message to be recalled |
string | Operator | Operator ID |
Active message recall
To recall messages that have been sent successfully, which relies on local history. It is required to find the message in local history according to its message id, if not the message can't be recalled.
- API prototype
public static void RecallMessage(string msgId, string notify, RecallMessageDelegate cb);
- Parameter Description
Parameter | Description |
---|---|
msgId | Uuid of the message to be recalled |
notify | Custom notification |
cb | Callback notification of message recall |
- Example
//Assume msgId is the id of the message that has been sent.
NIM.TalkAPI.RecallMessage(msgId,"This is a recall notify",(result, notify)=>{
...
});
Message recall notification
Notify the user that the message has been recalled, this notification is available offline.
- API prototype
public static void RegRecallMessageCallback(RecallMessageDelegate cb);
- Parameter Description
Parameter | Description |
---|---|
action | Callback of message recall notification |
- Example
void OnRecallMsgResult(ResponseCode result, RecallNotification[] notify)
{
//Processing interface
....
}
//Monitor event
NIM.TalkAPI.RegRecallMessageCallback(OnRecallMsgResult);
//Cancel monitoring
NIM.TalkAPI.RegRecallMessageCallback(null);
Read receipt
CommsEase provides read receipts of point-to-point messages. Note: This feature is only valid for P2P messages.
In the session interface, the operation of calling the interface for sending the read receipt and inputting the last message means that all the previous messages have been read, and the other side will receive the receipt.
General application scenarios for sending message read receipts:
1. Entering P2P chat interface (if you repeatedly enters the interface without receiving a new message, SDK can automatically filter repeated interface calls, so that only one of them is sent to the CommsEase server).
2. When you are in the chat interface and receive a new message from the current session.
Send read receipt
- API prototype
public static void SendReceipt(NIMIMMessage msg, MsglogStatusChangedDelegate cb, string jsonExtension = null);
- Parameter Description
Parameter | Description |
---|---|
msg | Message content received |
cb | The callback notification of message status change after sending the message read receipt |
jsonExtension | Extension field. Reserved |
- Example
//Assuming msg is a message that requires sending read receipt.
NIM.Messagelog.MessagelogAPI.SendReceipt(msg,(res,result)=>{
//Result - json character string, example: [{"talk_id":"test1","msg_timetag":"1520500638234","status":2}]
...
},null);
Monitor read receipt notification
Read receipt also represents a change in message status and therefore can be reflected in global message status change notification
Monitor broadcast to all notifications
Receive broadcast to all notifications. There are two types: individual and batch broadcast to all notifications. In general, batch notifications include offline broadcasts, synchronous broadcasts, and roaming broadcasts delivered when logging in.
NIMBroadcastMessage
Description of broadcast notification parameters
Type | Parameter | Description |
---|---|---|
long | MsgID | Notification message id |
string | Sender | Sender account, can be null |
long | Timetag | Notification message's UNIX timestamp, in milliseconds |
string | Body | Notification content |
1. Callback for receiving Individual broadcast to all notification , recommended to register it globally, so that messages can be distributed to specific sessions after accepting callbacks as a whole.
- API prototype
public static void RegReceiveBroadcastCb(ReceiveBroadcastDelegate cb);
- Parameter Description
Parameter | Description |
---|---|
cb | Notification callback |
- Example
void OnReceiveBroadcastMsg(NIMBroadcastMessage msgs)
{
//Process broadcast notification
...
}
//Monitor event
NIM.TalkAPI.RegReceiveBroadcastCb += OnReceiveBroadcastMsg;
//Cancel monitoring
NIM.TalkAPI.RegReceiveBroadcastCb -= OnReceiveBroadcastMsg;
2. Batch broadcast to all notifications
Callback for receiving batch broadcast messages. If this batch interface is also registered while registering receive message callback, when there are incoming batch messages, including offline messages received after logging in, this interface will be used to notify the application.
- API prototype
public static void RegReceiveBroadcastMsgsCb(ReceiveBroadcastMsgsDelegate cb);
- Parameter Description
Parameter | Description |
---|---|
cb | Callback of batch messages |
- Example
void OnReceiveBroadcastMsgs(List<NIMBroadcastMessage> msgs)
{
if (msgs != null)
{
//Enumerate array, process broadcast
foreach (var v in msgs)
{
....
}
}
}
//Monitor event
NIM.TalkAPI.RegReceiveBroadcastMsgsCb(OnReceiveBroadcastMsgs);
//Cancel monitoring
NIM.TalkAPI.RegReceiveBroadcastMsgsCb(null);
Get local path from message attachment
Get local paths of message attachments (image, voice, video, etc.). If pre-loaded only thumbnails without downloading the original images, files in the path obtained here may not exist, and the developer needs download them by callingnim.Nos.NosAPI.DownloadMedia
. If thumbnail is preloaded according to global setting and the original image is needed, then before passing in the message content, the fieldLocalFilePath
should be set to blank or a custom save path.
- API prototype
public static string GetAttachmentPathFromMsg(NIMIMMessage msg);
- Parameter Description
Parameter | Description |
---|---|
msg | Message content to be obtained |
- Example
//Assuming msg is a message to be obtained
string filePath = NIM.Talk.TalkAPI.GetAttachmentPathFromMsg(msg);
//Download original image
msg.LocalFilePath = null; //It is null, or set to custom save path;
nim.Nos.NosAPI.DownloadMedia (msg, (rescode, filePath, callId, resId)=>
{
//Notification completed
...
},
(prgData)=>
{
//Notification progress
...
});
Get image thumbnail
In default, after receiving an image message, CommsEase PC SDK will pre-load the original image and put it into the local cache. If you want to control the quality of downloaded images, you can do so by configuringkNIMPreloadImageQuality
(for quality control) andkNIMPreloadImageResize
(for size control) when initializing the SDK. The IM Demo's development example downloads original images by default. Therefore, in case of development using source codes of IM Demo, you need to download the original images for image preview or other links that need to use original images.
In scenes including but not limited to the following, developers can download thumbnails by themselves:
- There are special requirements on image size
- Received picture messages in chat room
Currently SDK provides two schemes for obtaining thumbnails:
-
To update image quality
After receiving the image message, the user can obtain the download address of the image by parsing the content of attachment
kNIMMsgKeyAttach
(kNIMChatRoomMsgKeyAttach
if chat room message), and then obtain the image of specified quality based on parameters for splicing download interface: Download address is http(s)://?imageView&quality=N; http(s)://xxx; where N is image quality, with a range of 0 to 100. -
The image is intra-shrunk by length and width (in proportion to the original size, with the obtained image having "one side of the requested length, and the other of less than or equal to the requested length")
After receiving an image message, users can obtain the download address of the image by parsing the content of attachment kNIMMsgKeyAttach (kNIMChatRoomMsgKeyAttach if chat room message), and then obtain the thumbnail based on parameters for splicing download interface: http(s)://xxx?imageView&thumbnail=XxY; http(s)://xxx is the image download address; where X is the width, Y is the height, and the middle symbol is the lowercase x. The value of width and height vary within the range of 0-4096.
Variations of several parameters: 1. XxY: general (intra) shrink 2. Xx0: fixed width and adaptive height (intra shrink) 3. 0xY: fixed height and adaptive width (intra shrink)
Currently in IM Demo project, images displayed in messages are all compressed, for details refer to bubble_image.cpp