Messaging
Update time: 2021/09/25 13:53:57
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 | 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 |
MessageSetting
Message setting
Type | Parameter | Description |
---|---|---|
BoolStatus | resend_flag_ | To resend message? Send for the first time:0, resend the message: 1 |
BoolStatus | need_push_ | If push is needed, 1: yes, 0: no |
BoolStatus | push_need_badge_ | (Optional) Is counting needed for push message (corner mark), 1: yes, 0: no |
BoolStatus | push_need_prefix_ | (Optional) Whether push messages need prefixes, set to true by default |
string | push_content_ | Custom push content, with a length not exceeding 200 bytes |
string | push_payload_ | Custom push attributes, must be unformatted json string with a length limited to 2048 |
BoolStatus | server_history_saved_ | (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 |
BoolStatus | roaming_ | (Optional) Enable roaming for the message? The default is 1, 1: yes, 0: no |
BoolStatus | self_sync_ | (Optional) Enable multi-terminal sync for the message? The default is 1, 1: yes, 0: no |
BoolStatus | routable_ | (Optional) The message is copied? 0:no, 1:yes, follow app router configuration in default |
BoolStatus | need_offline_ | (Optional) Save messages offline? The default is 1, 1: yes, 0: no, if roaming is supported, then it must be set to 1 |
BoolStatus | anti_spam_enable_ | Is Yidun anti-spam needed? 1: yes, 0: no |
string | anti_spam_content_ | (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"} |
string | local_ext_ | Local extension contents, local storage only, reserved field |
string | server_ext_ | Third-party extension field with a length limited to 1024 |
BoolStatus | is_force_push_ | Force push switch for team message, with total force push set as true and force push list set as empty |
std::list< std::string > | force_push_ids_list_ | Force push team message list |
string | force_push_content_ | Text in force push team message |
IMMessage
Basic message contents
Type | Parameter | Description |
---|---|---|
NIMSessionType | session_type_ | Session type, for details please refer to NIMSessionType |
string | sender_accid_ | Sender ID, filled out by server, which the sender may ignore |
string | receiver_accid_ | Receiver's ID (required), which should be your own ID when sending a message to yourself |
NIMClientType | readonly_sender_client_type_ | Sender client type, filled out by server, which the sender may ignore |
string | readonly_sender_device_id_ | Sender device ID, filled out by server, which the sender may ignore |
string | readonly_sender_nickname_ | Sender nickname, filled out by server, which the sender may ignore |
int64_t | timetag_ | Message timestamp (13-digit UNIX timestamp in milliseconds) |
NIMMessageType | type_ | Message type, see NIMMessageType for details |
string | client_msg_id_ | Message uuid, unique identifier, to be completed by sender |
int64_t | readonly_server_id_ | Server-side message ID, to be completed by server |
MessageSetting | msg_setting_ | Message setting, see MessageSettingfor details |
string | local_res_path_ | 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 | local_talk_id_ | Session ID, optional for sender. The receiver receives the sender ID |
string | local_res_id_ | Session ID, optional for sender. The receiver receives the client message ID |
NIMMsgLogStatus | status_ | Local message status, see message status type for details) |
NIMMsgLogSubStatus | sub_status_ | (Local message sub-status, see message sub-status type for details) |
Note: Roaming means that the messages that have been received at one terminal will be synchronized to other terminals (the most recent 100 messages stored 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
static void SendMsg(const std::string& json_msg, const std::string& json_extension = "", FileUpPrgCallback* pcb = nullptr);
- Parameter Description
Parameter | Description |
---|---|
json_msg | Message content, see IMMessage for details |
json_extension | Extension field. Reserved |
pcb | Notification of upload progress callback, which informs upload progress of self-uploaded attachments such as images, audio and video files (if any) |
Message setting
Sending a message also involves the following message attribute settings (Corresponding fields are contained in MessageSetting):
-
Messages can have two types of extension fields, namely server extension field kNIMMsgKeyServerExt and local extension field kNIMMsgKeyLocalExt. Each type features 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 theSendMsg
interface.
- API prototype
static std::string CreateTextMessage(const std::string& receiver_id, const NIMSessionType session_type, const std::string& client_msg_id, const std::string& content, const MessageSetting& msg_setting, int64_t timetag = 0);
- Parameter Description
Parameter | Description |
---|---|
receiver_id | A user account is used in one-on-one chat; a team ID is used in a group chat |
session_type | Session type |
client_msg_id | Client message ID, uuid is recommended |
content | Text content |
msg_setting | Message property settings |
timetag | Current UNIX timestamp, in milliseconds |
- Example
//In case of p2p message and test account test1
Json::FastWriter fw;
std::string content = "This is a text message." ;
//Message settings, to be configured as needed
//Other message settings, same as above
MessageSetting setting;
setting.roaming_ = 1;
setting.need_offline_ = 1;
setting.server_history_saved_ = 1;
//If anti-spam is needed
setting.anti_spam_enable_ = 1;
//Assemble anti-spam content
Json::Value jx;
jx["type"] = 1;
jx["data"] = content;//If it is a image or video, fill in the url of the attachment
setting.anti_spam_content_ = fw.write(jx);//Serialize to get json string
//Other settings
...
//Create message
std::string msg = nim::Talk::CreateTextMessage("test1",kNIMSessionTypeP2P,"Generate your own unique uuid",content,setting,1520500638234);
//Send message
nim::Talk::SendMsg(msg,null);
Picture message
Create image message content, complete the necessary message setting and send the message through the SendMsg
interface. The sent local image file will be automatically uploaded.
The attachment contentIMImage
of the image message is derived from IMFile, the field of which contains description of
Type | Parameter | Field |
---|---|---|
int | width_ | Image width |
int | height_ | Image height |
- API prototype
static std::string CreateImageMessage(const std::string& receiver_id, const NIMSessionType session_type, const std::string& client_msg_id, const IMImage& image, const std::string& file_path, const MessageSetting& msg_setting, int64_t timetag = 0);
- Parameter Description
Parameter | Description |
---|---|
receiver_id | A user account is used in one-on-one chat; a team ID is used in a group chat |
session_type | Session type |
client_msg_id | Client message ID, uuid is recommended |
image | Image attachment content, see IMImage for details |
file_path | Path of the local image file, if the file exists, the SDK will upload it automatically |
msg_setting | Message property settings |
timetag | Current UNIX timestamp in milliseconds |
- Example
//In case of p2p message and test account test1
//Message settings, to be configured as needed
MessageSetting setting;
setting.roaming_ = 1;
setting.need_offline_ = 1;
setting.server_history_saved_ = 1;
//Other settings
...
//Assemble attachment content
IMImage attachment;
attachment.md5_ = "0ca175b9c0f726a831d895e269332461";
attachment.size_ = 409600;
attachment.url_="http://xxxxxx/img.png";//If sending a local file, leave it blank
attachment.display_name_ = "img";
attachment.file_extension_ = "png";
//Set image height and width
attachment.width_ = 800;
attachment.height = 600;
//Local file path
std::string local_file_path = "c:\\img.png";
//Create message
std::string msg = nim::Talk::CreateImageMessage("test1",kNIMSessionTypeP2P,"Generate your own unique uuid",attachment,local_file_path,setting,1520500638234);
//Send message
nim::Talk::SendMsg(msg,null);
Voice message
Create voice message content, complete the necessary message setting and send the message through theSendMsg
interface. The sent local audio file will be automatically uploaded.
The attachment contentIMAudio
of the voice message is derived from IMFile, the field of which contains description of
Type | Parameter | Field |
---|---|---|
int | duration_ | Audio message duration |
- API prototype
static std::string CreateAudioMessage(const std::string& receiver_id, const NIMSessionType session_type, const std::string& client_msg_id, const IMAudio& audio, const std::string& file_path, const MessageSetting& msg_setting, int64_t timetag = 0);
- Parameter Description
Parameter | Description |
---|---|
receiver_id | A user account is used in one-on-one chat; a team ID is used in a group chat |
session_type | Session type |
client_msg_id | Client message ID, uuid is recommended |
audio | Audio attachment content, see IMAudio for details |
file_path | Path of the local file, if the file exists, the SDK will upload it automatically |
msg_setting | Message property settings |
timetag | Current UNIX timestamp in milliseconds |
- Example
//In case of p2p message and test account test1
//Message settings, to be configured as needed
MessageSetting setting;
setting.roaming_ = 1;
setting.need_offline_ = 1;
setting.server_history_saved_ = 1;
//Other settings
...
//Assemble attachment content
IMAudio attachment;
attachment.md5_ = "0ca175b9c0f726a831d895e269332461";
attachment.size_ = 409600;
attachment.url_="http://xxxxxx/audio.aac";//If sending a local file, leave it blank
attachment.display_name_ = "audio";
attachment.file_extension_ = "aac";
//Set the duration
attachment.duration_ = 8000;//ms
//Local file path
std::string local_file_path = "c:\\audio.aac";
//Create message
std::string msg = nim::Talk::CreateAudioeMessage("test1",kNIMSessionTypeP2P,"Generate your own unique uuid",attachment,local_file_path,setting,1520500638234);
//Send message
nim::Talk::SendMsg(msg,null);
Video message
Create video message content, complete the necessary message setting and send the message through the SendMsg
interface. The sent local video file will be automatically uploaded.
The attachment contentIMVideo
of the video message is derived from IMFile, the field of which contains description of
Type | Parameter | Field |
---|---|---|
int | duration_ | Audio message duration |
int | width_ | Image width |
int | height_ | Image height |
- API prototype
static std::string CreateVideoMessage(const std::string& receiver_id, const NIMSessionType session_type, const std::string& client_msg_id, const IMVideo& video, const std::string& file_path, const MessageSetting& msg_setting, int64_t timetag = 0);
- Parameter Description
Parameter | Description |
---|---|
receiver_id | A user account is used in one-on-one chat; a team ID is used in a group chat |
session_type | Session type |
client_msg_id | Client message ID, uuid is recommended |
video | Image attachment content, see IMVideo for details |
file_path | Path of the local file, if the file exists, the SDK will upload it automatically |
msg_setting | Message property settings |
timetag | Current UNIX timestamp in milliseconds |
- Example
//In case of p2p message and test account test1
//Message settings, to be configured as needed
MessageSetting setting;
setting.roaming_ = 1;
setting.need_offline_ = 1;
setting.server_history_saved_ = 1;
//Other settings
...
//Assemble attachment content
IMVideo attachment;
attachment.md5_ = "0ca175b9c0f726a831d895e269332461";
attachment.size_ = 409600;
attachment.url_="http://xxxxxx/video.mp4";//If sending a local file, leave it blank
attachment.display_name_ = "video";
attachment.file_extension_ = "mp4";
//Set the duration, length and width
attachment.duration_ = 8000;//ms
attachment.width_ = 800;
attachment.height = 600;
//Local file path
std::string local_file_path = "c:\\video.mp4";
//Create message
std::string msg = nim::Talk::CreateVideoMessage("test1",kNIMSessionTypeP2P,"Generate your own unique uuid",attachment,local_file_path,setting,1520500638234);
//Send message
nim::Talk::SendMsg(msg,null);
Geographic location
Create location message content, complete the necessary message setting and send the message through the SendMsg
interface.
The attachment contentNIMLocationMsgInfo
of the location message contains description of
Type | Parameter | Field |
---|---|---|
string | description_ | Location description |
int | latitude_ | Latitude |
int | longitude_ | Longitude |
- API prototype
tatic std::string CreateLocationMessage(const std::string& receiver_id, const NIMSessionType session_type, const std::string& client_msg_id, const IMLocation& location, const MessageSetting& msg_setting, int64_t timetag = 0);
- Parameter Description
Parameter | Description |
---|---|
receiver_id | A user account is used in one-on-one chat; a team ID is used in a group chat |
session_type | Session type |
client_msg_id | Client message ID, uuid is recommended |
location | Location attachment content, see IMLocation for details |
msg_setting | Message property settings |
timetag | Current UNIX timestamp in milliseconds |
- Example
//In case of p2p message and test account test1
//Message settings, to be configured as needed
MessageSetting setting;
setting.roaming_ = 1;
setting.need_offline_ = 1;
setting.server_history_saved_ = 1;
//Other settings
...
//Assemble attachment content
IMLocation attachment;
//Set location name, latitude and longitude
attachment.description = "Hangzhou";
attachment.latitude_ = 30.3;
attachment.longitude_ = 120.2;
//Create message
std::string msg = nim::Talk::CreateLocationMessage("test1",kNIMSessionTypeP2P,"Generate your own unique uuid",attachment,setting,1520500638234);
//Send message
nim::Talk::SendMsg(msg,null);
File message
Create file message content, complete the necessary message setting and send the message through the SendMsg
interface.
IMFile
File attachment base class
Type | Parameter | Field |
---|---|---|
string | md5_ | md5 of the file content |
int64_t | size_ | File size, 64-bit integer |
string | url_ | http url of the file |
string | display_name_ | file name |
string | file_extension_ | File extension |
- API prototype
static std::string CreateFileMessage(const std::string& receiver_id, const NIMSessionType session_type, const std::string& client_msg_id, const IMFile& file, const std::string& file_path, const MessageSetting& msg_setting, int64_t timetag = 0);
- Parameter Description
Parameter | Description |
---|---|
receiver_id | A user account is used in one-on-one chat; a team ID is used in a group chat |
session_type | Session type |
client_msg_id | Client message ID, uuid is recommended |
file | File attachment content, see IMFile for details |
file_path | Path of the local file, if the file exists, the SDK will upload it automatically |
msg_setting | Message property settings |
timetag | Current UNIX timestamp in milliseconds |
- Example
//In case of p2p message and test account test1
//Message settings, to be configured as needed
MessageSetting setting;
setting.roaming_ = 1;
setting.need_offline_ = 1;
setting.server_history_saved_ = 1;
//Other settings
...
//Assemble attachment content
IMFile attachment;
attachment.md5_ = "0ca175b9c0f726a831d895e269332461";
attachment.size_ = 409600;
attachment.url_="http://xxxxxx/document.doc";//If sending a local file, leave it blank
attachment.display_name_ = "Document";
attachment.file_extension_ = "doc";
//Local file path
std::string local_file_path = "c:\\document.doc";
//Create message
std::string msg = nim::Talk::CreateFileMessage("test1",kNIMSessionTypeP2P,"Generate your own unique uuid",attachment,local_file_path,setting,1520500638234);
//Send message
nim::Talk::SendMsg(msg,null);
Tip message
Create reminder message content, complete the necessary message setting and send the message through the SendMsg
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.
- API prototype
static std::string CreateTipMessage(const std::string& receiver_id, const NIMSessionType session_type, const std::string& client_msg_id, const std::string& tip_content, const MessageSetting& msg_setting, int64_t timetag = 0);
- Parameter Description
Parameter | Description |
---|---|
receiver_id | A user account is used in one-on-one chat; a team ID is used in a group chat |
session_type | Session type |
client_msg_id | Client message ID, uuid is recommended |
tip_content | Reminder message content, defined and parsed by developer |
msg_setting | Message property settings |
timetag | Current UNIX timestamp in milliseconds |
- Example
//In case of p2p message and test account test1
//Message settings, to be configured as needed
MessageSetting setting;
setting.roaming_ = 1;
setting.need_offline_ = 1;
setting.server_history_saved_ = 1;
//Other settings
...
std::string tip_content = "This is a reminder message";
//Create message
std::string msg = nim::Talk::CreateTipMessage("test1",kNIMSessionTypeP2P,"Generate your own unique uuid",content,setting,1520500638234);
//Send message (or in some scenarios, use nim::MsgLog::WriteMsglogToLocalAsync to directly write local data)
nim::Talk::SendMsg(msg,null);
Custom message
Create custom message content, complete the necessary message setting and send the message through the SendMsg
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.
- Example
std::string CreateCustomMessage(const std::string& receiver_id, const NIMSessionType session_type, const std::string& client_msg_id, const std::string& content, const std::string& attachment, const MessageSetting& msg_setting, int64_t timetag/* = 0*/)
{
Json::Value values;
values[kNIMMsgKeyToAccount] = receiver_id;
values[kNIMMsgKeyToType] = session_type;
values[kNIMMsgKeyClientMsgid] = client_msg_id;
values[kNIMMsgKeyBody] = content;
values[kNIMMsgKeyAttach] = attachment; //Custom attachment content;
values[kNIMMsgKeyType] = kNIMMessageTypeCustom;//Custom message
values[kNIMMsgKeyLocalTalkId] = receiver_id;
msg_setting.ToJsonValue(values);
//Optional
if (timetag > 0)
values[kNIMMsgKeyTime] = timetag;
Json::FastWriter fw;
return fw.write(values);
}
//In case of p2p message and test account test1
//Message settings, to be configured as needed
MessageSetting setting;
setting.roaming_ = 1;
setting.need_offline_ = 1;
setting.server_history_saved_ = 1;
//Other settings
...
//Assemble attachment content
Json::FastWriter fw;
Json::Value attachment;
attachment["customFiled1"] = "Custom content 1";
attachment["customFiled2"] = 10; //Custom value
std::string contemt = "This is normal text content";
//Create message
std::string msg = CreateCustomMessage("test1",kNIMSessionTypeP2P,"Generate your own unique uuid",contemt,fw.write(attachment),setting,1520500638234);
//Send message
nim::Talk::SendMsg(msg,null);
Team force push message
Send a force push message to the team to @ the specified person or everyone, see MessageSettingfor details
- Example
//Take test team 1222222 as an example
Json::FastWriter fw;
std::string content = "This is a text message." ;
//Message settings, to be configured as needed
//Other message settings, same as above
MessageSetting setting;
setting.roaming_ = 1;
setting.need_offline_ = 1;
setting.server_history_saved_ = 1;
...
//Force push to team members test1, test2
setting.is_force_push_ = 1;
setting.force_push_ids_list_.push_back("test1");
setting.force_push_ids_list_.push_back("test2");
setting.force_push_content_ = "This is a force push message";
//Other settings
...
//Create message
std::string msg = nim::Talk::CreateTextMessage("1222222",kNIMSessionTypeTeam,"Generate your own unique uuid",content,setting,1520500638234);
//Send message
nim::Talk::SendMsg(msg,null);
Sending result notification
Sending is successful or failed, and the result also contains tag (if any) for client anti-spam hit.
SendMessageArc
Parameter description
Type | Parameter | Description |
---|---|---|
string | talk_id_ | Session ID |
string | msg_id_ | Message ID |
NIMResCode | rescode_ | Error code |
int64_t | msg_timetag_ | Message timestamp |
bool | client_anti_spam_hit_ | Is there a hit with client anti-spam, 1: Yes, 0: No |
- API prototype
static void RegSendMsgCb(const SendMsgAckCallback& cb, const std::string& json_extension = "");
- Example
//Monitor event
nim::Talk::RegSendMsgCb([&](const nim::SendMessageArc& ack)
{
...
});
//Cancel monitoring
nim::Talk::RegSendMsgCb(nullptr);
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
//The unique uuid of the message to be stopped, required
std::string clientMsgId = "uuid";
//Interrupt sending
nim::Talk::StopSendMsg(clientMsgId, kNIMMessageTypeFile);
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.
Message parsing
SDK supports parsing of built-in messages such as images, files, audio, video, geographic locations, etc. Other custom messages and attachments need to be parsed by the developer.
1. Parse message content
- API prototype
static bool ParseIMMessage(const std::string& json_msg, IMMessage& msg);
- Parameter Description
Parameter | Description |
---|---|
json_msg | Input the unformatted json string of message content |
msg | Output message content, see IMMessage for details |
2. Parse received message
Different from Parsing message content , this function parses fieldskNIMMsgKeyLocalRescode
, kNIMMsgKeyLocalMsgFeature
andkNIMMsgKeyLocalReceiveMsgContent
,whileParseIMMessage
parses actual message content carried bykNIMMsgKeyLocalReceiveMsgContent
.
- API prototype
static bool ParseReceiveMessage(const std::string& json_msg, IMMessage& msg);
- Parameter Description
Parameter | Description |
---|---|
json_msg | Input the unformatted json string of message content |
msg | Output message content, see IMMessage for details |
3. Parse image message attachment
- API prototype
static bool ParseImageMessageAttach(const IMMessage& msg, IMImage& image);
- Parameter Description
Parameter | Description |
---|---|
msg | Message content, see IMMessage for details |
image | Output image attachment content, see IMImage for details |
4. Parse file message attachment
- API prototype
static bool ParseFileMessageAttach(const IMMessage& msg, IMFile& file);
- Parameter Description
Parameter | Description |
---|---|
msg | Message content, see IMMessage for details |
file | Output image attachment content, see IMFile for details |
5. Parse voice message attachment
- API prototype
static bool ParseAudioMessageAttach(const IMMessage& msg, IMAudio& audio);
- Parameter Description
Parameter | Description |
---|---|
msg | Message content, see IMMessage for details |
audio | Output image attachment content, see IMAudio for details |
6. Parse video message attachment
- API prototype
static bool ParseVideoMessageAttach(const IMMessage& msg, IMVideo& video);
- Parameter Description
Parameter | Description |
---|---|
msg | Message content, see IMMessage for details |
video | Output image attachment content, see IMVideo for details |
7. Parse location message attachment
- API prototype
static bool ParseLocationMessageAttach(const IMMessage& msg, IMLocation& location);
- Parameter Description
Parameter | Description |
---|---|
msg | Message content, see IMMessage for details |
location | Output image attachment content, see IMLocation for details |
Online message receiving
It is recommended to register a global callback, so that the SDK only stores onecb
, registering multiple callbacks will result in overwriting, and only the last one will take effect.
- API prototype
static void RegReceiveCb(const ReceiveMsgCallback& cb, const std::string& json_extension = "");
- Parameter Description
Parameter | Description |
---|---|
cb | Asynchronous notification callback |
json_extension | Extension field. Reserved |
- Example
//Monitor event
nim::Talk::RegReceiveCb([&](const IMMessage& msg) {
//for test;
switch (msg.type_)
{
case kNIMMessageTypeFile:
{
IMFile file;
if (nim::Talk::ParseFileMessageAttach(msg, file))
{
...
}
}
break;
case kNIMMessageTypeImage:
{
IMImage img;
if (nim::Talk::ParseImageMessageAttach(msg, img))
{
...
}
}
break;
case kNIMMessageTypeAudio:
{
IMAudio audio;
if (nim::Talk::ParseAudioMessageAttach(msg, audio))
{
...
}
}
break;
case kNIMMessageTypeVideo:
{
IMVideo video;
if (nim::Talk::ParseVideoMessageAttach(msg, video))
{
...
}
}
break;
case kNIMMessageTypeLocation:
{
IMLocation location;
if (nim::Talk::ParseLocationMessageAttach(msg, location))
{
...
}
}
break;
default:
{
std::string attach = msg.attach_;
if (!attach.empty())
{
...
}
}
break;
}
});
//Cancel monitoring
nim::Talk::RegReceiveCb(nullptr);
Receive offline, sync, and roaming messages
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
//Monitor event
nim::Talk::RegReceiveMessagesCb([&](const std::list<IMMessage>& msgs) {
for (auto msg : msgs)
{
...
}
});
//Cancel monitoring
nim::Talk::RegReceiveMessagesCb(nullptr);
Filter team notifications
Register the callback for whether to filter the incoming team notifications. If this callback returns true, the SDK deems the notification as processed, therefore the SDK will not deliver the notification through the message reception channel, and will not save the notification to the local database.
- API prototype
public static void RegTeamNotificationFilterCb(TeamNotificationFilterDelegate action);
- Parameter Description
Parameter | Description |
---|---|
action | Callback for filtering team notifications |
- Example
bool filterTeamNotify = true;
//Monitor event
nim::Talk::RegTeamNotificationFilter([&](const IMMessage& msg)->bool
{
//If the notification is filtered, returns true, otherwise returns false;
if (filterTeamNotify)
{
...
return true;
}
return false;
});
//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
static std::string CreateRetweetMessage(const std::string& src_msg_json, const std::string& client_msg_id, const NIMSessionType retweet_to_session_type, const std::string& retweet_to_session_id, const MessageSetting& msg_setting, int64_t timetag = 0);
- Parameter Description
Parameter | Description |
---|---|
src_msg_json | Content of the received message, the same as that of IMMessage |
client_msg_id | New message uuid generated |
retweet_to_session_id | The other party's ID, forwarded, user account or team ID |
retweet_to_session_type | Session type, 0: p2p message 1: team message |
msg_setting | Message setting, see message setting description for details |
timetag | Current timestamp (in milliseconds) |
- Example
//Assumed to be the content of the message sent or received by srcMsg
std:string srcMsg;
//Message settings, to be configured as needed
MessageSetting msgSetting;
msgSettting.ServerSaveHistory = true;
...
//A new message generated through srcMsg.
int64_t timeNow = 1520500638234;//Current UNIX timestamp in milliseconds
string sessionid = "1222222";
string clientMsgID = "uuid2";//A generated new unique uuid;
NIMSessionType sessionType = kNIMSessionTypeTeam;
std::string newMsg = nim::Talk::CreateRetweetMessage(srcMsg,clientMsgID,sessionType,sessionid,msgSettting,timeNow);
nim::Talk::SendMsg(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 | session_type_ | Session type, 0: p2p message 1: team message |
string | from_id_ | Message from ID |
string | to_id_ | Message to ID |
string | msg_id_ | Unique ID of the message |
string | notify_ | Custom notification copy |
int64_t | notify_timetag_ | Timestamp of recall operation (in milliseconds)s |
NIMMessageFeature | notify_feature_ | Type of the recalled message, see NIMMessageFeature for details |
bool | msglog_exist_ | 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 |
int64_t | msglog_timetag_ | Timestamp of the message to be recalled (in milliseconds) (milliseconds) |
string | from_nick_ | Nickname of the sender of the message to be recalled |
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
static void RecallMsg(const IMMessage& msg, const std::string& notify, const RecallMsgsCallback& cb, const std::string& json_extension = "");
- Parameter Description
Parameter | Description |
---|---|
msg | To-be-recalled message |
notify | Custom notification |
cb | Callback notification of message recall |
json_extension | Notification extension, reserved |
- Example
//To be assembled by yourself, currently the recall is done through msgId,
IMMessage assembleMsg;
assembleMsg.client_msg_id_ = "Recalled message's uuid"; //only the message ID is used for now;
nim::Talk::RecallMsg(assembleMsg,"This is a recall notification", [&](NIMResCode code, const std::list<RecallMsgNotify>& notifications) {
...
});
Message recall notification
Notify the user that the message has been recalled, this notification is available offline.
- API prototype
static void RegRecallMsgsCallback(const RecallMsgsCallback& cb, const std::string& json_extension = "");
- Parameter Description
Parameter | Description |
---|---|
cb | Callback of message recall notification |
json_extension | Notification extension, reserved |
- Example
//Monitor event
nim::Talk::RegRecallMsgsCallback([&](const NIMResCode code, const std::list<RecallMsgNotify>& notifications)
{
for (auto msg : notifications)
{
...
}
});
//Cancel monitoring
nim::Talk::RegRecallMsgsCallback(nullptr);
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
static void SendReceiptAsync(const std::string& json_msg, const MessageStatusChangedCallback& cb);
- Parameter Description
Parameter | Description |
---|---|
json_msg | Message content received |
cb | The callback notification of message status change after sending the message read receipt |
- Example
//Assuming msg is a message that requires sending read receipt.
nim::MsgLog::SendReceiptAsync(msg, [&](const nim::MessageStatusChangedResult& result) {
for (auto r : result.results_)
{
...
}
});
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.
BroadcastMessage
Description of broadcast notification parameters
Type | Parameter | Description |
---|---|---|
int64_t | id_ | Notification message ID |
string | from_id_ | Sender account, can be empty |
int64_t | time_ | 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
static void RegReceiveBroadcastMsgCb(const ReceiveBroadcastMsgCallback& cb, const std::string& json_extension = "");
- Parameter Description
Parameter | Description |
---|---|
cb | Notification callback |
json_extension | Extension field. Reserved |
- Example
//Monitor event
nim::Talk::RegReceiveBroadcastMsgCb([&](const BroadcastMessage& msg)
{
//Process broadcast notification
...
});
//Cancel monitoring
nim::Talk::RegReceiveBroadcastMsgCb(nullptr);
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
static void RegReceiveBroadcastMsgsCb(const ReceiveBroadcastMsgsCallback& cb, const std::string& json_extension = "");
- Parameter Description
Parameter | Description |
---|---|
cb | Callback of batch messages |
json_extension | Extension field. Reserved |
- Example
//Monitor event
nim::Talk::RegReceiveBroadcastMsgsCb([&](const std::list<nim::BroadcastMessage> msgs)
{
//Process broadcast notification
for (auto msg : msgs)
{
...
}
});
//Cancel monitoring
nim::Talk::RegReceiveBroadcastMsgsCb(nullptr);
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::FetchMedia
. If thumbnail is preloaded according to global setting and the original image is needed, then before passing in the message content, the fieldlocal_res_path_
should be set to blank or a custom save path.
- API prototype
static std::string GetAttachmentPathFromMsg(const IMMessage& msg);
- Parameter Description
Parameter | Description |
---|---|
msg | Message content to be obtained |
- Example
//Assuming msg is a message to be obtained
std::string filePath = nim::Talk::GetAttachmentPathFromMsg(msg);
//Download original image
msg.local_res_path_ = ""; //Set it to blank or a custom save path;
nim::Talk::FetchMedia(msg,[&](NIMResCode res_code, const std::string& file_path, const std::string& call_id, const std::string& res_id){
//Notification completed
...
},[&](int64_t completed_size, int64_t file_size){
//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