Send and receive message

Update time: 2021/12/03 09:45:20

Messaging

Sending messages

The SDK supports multiple types of messages, such as text, images, voice, video, geolocation, notification, alert, file, chatbot messages, and custom messages.

  • API introduction

    • C++

      static void SendMsg (const std::string &json_msg, const std::string &json_extension="", FileUpPrgCallback *pcb=nullptr)

      File:nim_cpp_talk.h

      Namespace:NIM

      Class:Talk

    • C#

      static void SendMessage (NIMIMMessage message, ReportUploadProgressDelegate action=null)

      Namespace:NIM

      Class:TalkAPI

    • C

      NIM_SDK_DLL_API void nim_talk_send_msg (const char *json_msg, const char *json_extension, nim_nos_upload_prg_cb_func prg_cb, const void *prg_user_data)

      File:nim_talk.h

    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.

    • C++

      static bool StopSendMsg (const std::string &client_msg_id, const NIMMessageType &type, const std::string &json_extension="")

      File:nim_cpp_talk.h

      Namespace:NIM

      Class:Talk

    • C#

      static void StopSendMessage (NIMIMMessage message, ReportUploadProgressDelegate action=null)

      Namespace:NIM

      Class:TalkAPI

    • C

      NIM_SDK_DLL_API void nim_talk_stop_send_msg (const char *json_msg, const char *json_extension)

      File:nim_talk.h

    The result of message sending (not whether it has been read) is obtained through the global callback registered before login.

    • C++

      static void RegSendMsgCb (const SendMsgAckCallback &cb, const std::string &json_extension="")

      File:nim_cpp_talk.h

      Namespace:NIM

      Class:Talk

      Example:

        void OnSendMsgCallback(const nim::SendMessageArc& arc)
        {
        	···
        }
      
        void foo()
        {
        	nim::Talk::RegSendMsgCb(&OnSendMsgCallback);
        }
      

      Define: SendMessageArc

    • C#

      static EventHandler< MessageArcEventArgs > OnSendMessageCompleted [get, set]

      Namespace:NIM

      Class:TalkAPI

      Example:

        void SendMessageResultHandler(object sender, MessageArcEventArgs args)
        {
        	if (args.ArcInfo.Response == ResponseCode.kNIMResSuccess)
        	{
        		···
        	}
        	if (args.ArcInfo.Response == ResponseCode.kNIMResSuccess)
        		return;
      
        	Action action = () =>
        	{
        		MessageBox.Show(args.Dump(), "The message is not sent successfully");
        	};
        	this.Invoke(action);
        }
      
        private void foo()
        {
        	NIM.TalkAPI.OnSendMessageCompleted += SendMessageResultHandler;
        }
      

      Define: MessageArcEventArgs

    • C

      NIM_SDK_DLL_API void nim_talk_reg_ack_cb (const char *json_extension, nim_talk_ack_cb_func cb, const void *user_data)

      File:nim_talk.h

      Example:

        void CallbackSendMsgResult(const char* result, const void *user_data)
        {
        	//Decode result {"msg_id" : "" , "talk_id" : "" , "rescode" : ""}
        }
      
        typedef void(*nim_talk_reg_arc_cb)(const char *json_extension, nim_talk_arc_cb_func cb, const void *user_data);
      
        void foo()
        {
        	nim_talk_reg_arc_cb func = (nim_talk_reg_arc_cb) GetProcAddress(hInst, "nim_talk_reg_arc_cb");
        	func(nullptr, &CallbackSendMsgResult, nullptr);
        }
      
  • Parameters

    • message sending interface
Parameter Type Description
json_msg(C/C++) string Message body Json string. C interface needs to actively assemble the Json data structure and serialize it into an unformatted Json string,
C++ interface can be generated using Talk::CreateXXXMessage (for details, see the introduction to auxiliary API in this chapter)
message(C#) object Message object, see NIMIMMessage
prg_cb/pcb/action feature The callback feature of upload progress, if the message sent contains file resources,
notification of the upload progress can be implemented using this callback feature
json_extension(C) string json extension parameters (in reserve, currently not needed)
user_data(C) void* APP's custom user data, which SDK is only responsible for passing back to the callback feature cb
(without any processing)
  • parameters of the interface for stopping sending messages
Parameter Type Required Description
client_msg_id(C++) string Yes client_msg_id of message object subject to stop sending
message(C#) object Yes Message object subject to stop sending, see NIMIMMessage
json_msg(C) string Yes Json string of message object subject to stop sending
json_extension(C) string No json extension parameters (in reserve, currently not needed)

Text message

  • Construction API introduction

    • C++

        /** @fn static std::string CreateTipMessage(const std::string& recipient_id, const NIMSessionType session_type, const std::string& client_msg_id, const std::string& tip_content, const MessageSetting& msg_setting, int64_t timetag  = 0)
        * Generate text message. The generated character string is  input when SendMsg is invoked. 
        *  @param[in] recipient_id - Chat object ID. It is user account for one-to-one chat and team ID for team chat.
        *  @param[in] session_type NIMSessionType - Chat type, one-to-one chat or team chat.
        *  @param[in] client_msg_id - Client message id. It is recommended to use uuid.
        *  @param[in] content - Text content
        *  @param[in] msg_setting - Message attribute settings
        *  @param[in] timetag - Message time
        *  @return std::string - Json character string of text message
        */
        static std::string CreateTipMessage (const std::string &recipient_id, const NIMSessionType session_type, const std::string &client_msg_id, const std::string &tip_content, const MessageSetting &msg_setting, int64_t timetag=0)
      

      Define: NIMSessionType ; MessageSetting

      File:nim_cpp_talk.h

      Namespace:NIM

      Class:Talk

    • C#

      N/A, operation object.

    • C

      N/A, assemble Json data based on definition.

Image message

  • Construction API introduction

    • C++

        /** @fn static std::string CreateImageMessage(const std::string& recipient_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)
        * Generate image message. The generated character string is  input when SendMsg is invoked.
        *  @param[in] recipient_id - Chat object ID. It is user account for one-to-one chat and team ID for team chat.
        *  @param[in] session_type NIMSessionType - Chat type, one-to-one chat or team chat.
        *  @param[in] client_msg_id - Client message id. It is recommended to use uuid.
        *  @param[in] image IMImage - Image file information
        *  @param[in] file_path - Local absolute path of a file
        *  @param[in] msg_setting - Message attribute settings
        *  @param[in] timetag - Message time
        *  @return std::string - Json character string of image message
        */
        static std::string CreateImageMessage (const std::string &recipient_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)
      

      Define: NIMSessionType ; MessageSetting ; IMImage

      File:nim_cpp_talk.h

      Namespace:NIM

      Class:Talk

    • C#

      N/A, operation object.

    • C

      N/A, assemble Json data based on definition.

  • Example

    • C++

        //Codes are extracted from DEMO source codes.
        void SessionBox::SendImage( const std::wstring &src )
        {
        	nim::IMMessage msg;
        	PackageMsg(msg);
        	msg.type_ = nim::kNIMMessageTypeImage;
      
        	std::wstring filename = nbase::UTF8ToUTF16(msg.client_msg_id_);
        	std::wstring dest = GetUserImagePath() + filename;
        	GenerateUploadImage(src, dest);
        	msg.local_res_path_ = nbase::UTF16ToUTF8(dest);
      
        	nim::IMImage img;
        	img.md5_ = GetFileMD5(dest);
        	img.size_ = (long)nbase::GetFileSize(dest);
      
        	Gdiplus::Image image(dest.c_str());
        	if (image.GetLastStatus() != Gdiplus::Ok)
        	{
        	assert(0);
        	}
        	else
        	{
        	img.width_ = image.GetWidth();
        	img.height_ = image.GetHeight();
        	}
      
        	msg.attach_ = img.ToJsonString();
      
        	std::string json_msg = nim::Talk::CreateImageMessage(msg.recipient_accid_, msg.session_type_, msg.client_msg_id_, img, msg.local_res_path_, msg.timetag_);
        	nim::Talk::SendMsg(json_msg);
        }
      
    • C#

        void SendImage(string path)
        {
        	string fileName = System.IO.Path.GetFileNameWithoutExtension(path);
        	string extension = System.IO.Path.GetExtension(path);
      
        	NIM.NIMImageMessage imageMsg = new NIMImageMessage();
        	imageMsg.LocalFilePath = path;
        	imageMsg.ImageAttachment = new NIMImageAttachment();
        	imageMsg.ImageAttachment.DisplayName = fileName;
        	imageMsg.ImageAttachment.FileExtension = extension;
        	imageMsg.ReceiverID = _peerId;
        	imageMsg.SessionType = _sessionType;
        	using (var i = Image.FromFile(path))
        	{
        		imageMsg.ImageAttachment.Height = i.Height;
        		imageMsg.ImageAttachment.Width = i.Width;
        	}
        	TalkAPI.SendMessage(imageMsg);
        }
      
    • C

        typedef void(*nim_talk_send_msg)(const char* json_msg, const char *json_extension, nim_nos_upload_prg_cb_func prg_cb, const void *prg_user_data);
      
        void foo()
        {
        	Json::Value json;
        	json[kNIMMsgKeyToType]			= ; //int Session type (NIMSessionType Individual 0 Team 1)
        	json[kNIMMsgKeyToAccount]		= ; //string - Message recipient id
        	json[kNIMMsgKeyTime]			= ; //int64  Sending time for a message (unit: ms), optional
        	json[kNIMMsgKeyType]			= ; //NIMMessageType - Message type
        	json[kNIMMsgKeyBody]			= ; //string - Message content
        	json[kNIMMsgKeyAttach]			= ; //string - Additional content
        	json[kNIMMsgKeyClientMsgid]		= ; //string - Message id. Generally, guid is used.
        	json[kNIMMsgKeyResendFlag]		= ; //int    - Resending flag (0 is not to resend; 1 is to resend)
        	json[kNIMMsgKeyLocalLogStatus]	= ; //NIMMsgLogStatus - Message status
        	json[kNIMMsgKeyType] 			= kNIMMessageTypeImage;
      
        	//Image details
        	Json::Value attach;
        	attach[kNIMImgMsgKeyMd5] = ;  	//string - File md5, optional
        	attach[kNIMImgMsgKeySize] = ; 	//long - File size, optional
        	attach[kNIMImgMsgKeyWidth] = ;  //int - Image width, required
        	attach[kNIMImgMsgKeyHeight] = ; //int - Image height, required
        	json[kNIMMsgKeyAttach] = attach.toStyledString();
      
        	json[kNIMMsgKeyLocalFilePath]	= ; //string - Local path of an image
        	json[kNIMMsgKeyLocalLogStatus] = kNIMMsgLogStatusSending;
      
        	nim_talk_send_msg func = (nim_talk_send_msg) GetProcAddress(hInst, "nim_talk_send_msg");
        	func(json.toStyledString().c_str(), "", NULL, "");
        }
      

File message

  • Construction API introduction

    • C++

        /** @fn static std::string CreateFileMessage(const std::string& recipient_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)
        * Generate file message. The generated character string is  input when SendMsg is invoked.
        *  @param[in] recipient_id - Chat object ID. It is user account for one-to-one chat and team ID for team chat.
        *  @param[in] session_type NIMSessionType - Chat type, one-to-one chat or team chat.
        *  @param[in] client_msg_id - Client message id. It is recommended to use uuid.
        *  @param[in] file IMFile - File information
        *  @param[in] file_path - Local absolute path of a file
        *  @param[in] msg_setting - Message attribute settings
        *  @param[in] timetag - Message time
        *  @return std::string - Json character string of file message
        */
        static std::string CreateFileMessage (const std::string &recipient_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)
      

      Define: NIMSessionType ; MessageSetting; IMFile

      File:nim_cpp_talk.h

      Namespace:NIM

      Class:Talk

    • C#

      N/A, operation object.

    • C

      N/A, assemble Json data based on definition.

Voice message

  • Construction API introduction

    • C++

        /** @fn static std::string CreateAudioMessage(const std::string& recipient_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)
        * Generate audio message. The generated character string is  input when SendMsg is invoked.
        *  @param[in] recipient_id - Chat object ID. It is user account for one-to-one chat and team ID for team chat.
        *  @param[in] session_type NIMSessionType - Chat type, one-to-one chat or team chat.
        *  @param[in] client_msg_id - Client message id. It is recommended to use uuid.
        *  @param[in] audio IMAudio - Audio file information
        *  @param[in] file_path - Local absolute path of a file
        *  @param[in] msg_setting - Message attribute settings
        *  @param[in] timetag - Message time
        *  @return std::string - Json character string of audio message
        */
        static std::string CreateAudioMessage (const std::string &recipient_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)
      

      Define: NIMSessionType ; MessageSetting; IMAudio

      File:nim_cpp_talk.h

      Namespace:NIM

      Class:Talk

    • C#

      N/A, operation object.

    • C

      N/A, assemble Json data based on definition.

Short video message

  • Construction API introduction

    • C++

        /** @fn static std::string CreateVideoMessage(const std::string& recipient_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)
        * Generate video message. The generated character string is  input when SendMsg is invoked.
        *  @param[in] recipient_id - Chat object ID. It is user account for one-to-one chat and team ID for team chat.
        *  @param[in] session_type NIMSessionType - Chat type, one-to-one chat or team chat.
        *  @param[in] client_msg_id - Client message id. It is recommended to use uuid.
        *  @param[in] video IMVideo - Video file information
        *  @param[in] file_path - Local absolute path of a file
        *  @param[in] msg_setting - Message attribute settings
        *  @param[in] timetag - Message time
        *  @return std::string - Json character string of video message
        */
        static std::string CreateVideoMessage (const std::string &recipient_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)
      

      Define: NIMSessionType ; MessageSetting; IMVideo

      File:nim_cpp_talk.h

      Namespace:NIM

      Class:Talk

    • C#

      N/A, operation object.

    • C

      N/A, assemble Json data based on definition.

Location message

  • Construction API introduction

    • C++

        /** @fn static std::string CreateLocationMessage(const std::string& recipient_id, const NIMSessionType session_type, const std::string& client_msg_id, const IMLocation& location, const MessageSetting& msg_setting, int64_t timetag  = 0)
        * Generate location message. The generated character string is  input when SendMsg is invoked.
        *  @param[in] recipient_id - Chat object ID. It is user account for one-to-one chat and team ID for team chat.
        *  @param[in] session_type NIMSessionType - Chat type, one-to-one chat or team chat.
        *  @param[in] client_msg_id - Client message id. It is recommended to use uuid.
        *  @param[in] location IMLocation - Location information
        *  @param[in] msg_setting - Message attribute settings
        *  @param[in] timetag - Message time
        *  @return std::string - Json character string of location message
        */
        static std::string 	CreateLocationMessage (const std::string &recipient_id, const NIMSessionType session_type, const std::string &client_msg_id, const IMLocation &location, const MessageSetting &msg_setting, int64_t timetag=0)
      

      Define: NIMSessionType ; MessageSetting; IMLocation

      File:nim_cpp_talk.h

      Namespace:NIM

      Class:Talk

    • C#

      N/A, operation object.

    • C

      N/A, assemble Json data based on definition.

Message alert

  • Construction API introduction

    • C++

        /** @fn static std::string CreateTipMessage(const std::string& recipient_id, const NIMSessionType session_type, const std::string& client_msg_id, const std::string& tip_content, const MessageSetting& msg_setting, int64_t timetag  = 0)
        * Generate Tip message. The generated character string is  input when SendMsg is invoked.
        *  @param[in] recipient_id - Chat object ID. It is user account for one-to-one chat and team ID for team chat.
        *  @param[in] session_type NIMSessionType - Chat type, one-to-one chat or team chat.
        *  @param[in] client_msg_id - Client message id. It is recommended to use uuid.
        *  @param[in] content - Tip text content
        *  @param[in] msg_setting - Message attribute settings
        *  @param[in] timetag - Message time
        *  @return std::string - Json character string of location message
        */
        static std::string CreateTipMessage (const std::string &recipient_id, const NIMSessionType session_type, const std::string &client_msg_id, const std::string &tip_content, const MessageSetting &msg_setting, int64_t timetag=0)
      

      Define: NIMSessionType ; MessageSetting

      File:nim_cpp_talk.h

      Namespace:NIM

      Class:Talk

    • C#

      N/A, operation object.

    • C

      N/A, assemble Json data based on definition.

Robot message

  • Construction API introduction

    • C++

        /** @fn static std::string CreateBotRobotMessage(const std::string& recipient_id, const NIMSessionType session_type, const std::string& client_msg_id, const std::string& content, const IMBotRobot& bot_msg, const MessageSetting& msg_setting, int64_t timetag  = 0)
        * Generate Tip message. The generated character string is  input when SendMsg is invoked.
        *  @param[in] recipient_id - Chat object ID. It is user account for one-to-one chat and team ID for team chat.
        *  @param[in] session_type NIMSessionType - Chat type, one-to-one chat or team chat.
        *  @param[in] client_msg_id - Client message id. It is recommended to use uuid.
        *  @param[in] content - Content
        *  @param[in] bot_msg - Machine message information
        *  @param[in] msg_setting - Message attribute settings
        *  @param[in] timetag - Message time
        *  @return std::string - Json character string of location message
        */	
        static std::string CreateBotRobotMessage (const std::string &recipient_id, const NIMSessionType session_type, const std::string &client_msg_id, const std::string &content, const IMBotRobot &bot_msg, const MessageSetting &msg_setting, int64_t timetag=0)
      

      Define: NIMSessionType ; MessageSetting; IMBotRobot

      File:nim_cpp_talk.h

      Namespace:NIM

      Class:Talk

    • C#

      N/A, operation object.

    • C

      N/A, assemble Json data based on definition.

User-defined messages

In addition to built-in message types, IM SDK also supports sending and receiving user-defined messages. Like transparent transmission, SDK will not parse the specific content of custom messages, and the corresponding work should be assumed by the developer.

Message property settings

The following message property settings can be set for message sending:

  • 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 clients, while the local extension field is only valid locally. Both extension fields will be stored by the SDK in the database. Examples are as follows:

      json[kNIMMsgKeyServerExt] = ""; // json string
      json[kNIMMsgKeyLocalExt] = ""; // json string
    
  • 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.

      json[kNIMMsgKeyPushContent] = "";
      json[kNIMMsgKeyPushPayload] = ""; // json string
    
  • Whether push field is needed (kNIMMsgKeyPushEnable), 0: not needed, 1: needed.

  • Whether message count field is needed (kNIMSysMsgKeyNeedBadge), 0: not needed, 1: needed.

  • Whether push display name 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 pulling the interface of server message history. 0: Not needed, 1: Needed.

  • Whether roaming is supported for the message (kNIMMsgKeyMsgRoaming). If needed, even if the message has been received at a certain client, it will also be roamed upon re-login at other clients. 0: Not needed, 1: Needed.

  • Whether the message can be synced with multiple clients (kNIMMsgKeyMsgSync). If needed, a message sent will be synchronized to other clients logged in at the same time. 0: Not needed, 1: Needed.

  • Whether the message is routable to a third party (kNIMMsgKeyMsgRoutable), 0: not supported, 1: supported, and the default is subject to app's message delivery for setting

  • Whether offline viewing is needed (kNIMMsgKeySetMsgOffline), 0: not needed, 1: needed, 1 by default

  • Message resend flag (kNIMMsgKeyResendFlag), 0 indicates the first time, 1 indicates retransmission, it is used for message deduplication

Team messages have two additional property settings, namely forced push (can be used to implement @ features.) and read receipt:

  • Whether forced push is needed for the field (kNIMMsgKeyPushEnable), 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.
  • Force push content field (kNIMMsgKeyForcePushContent), to be filled in with the text of the force push notifications.
  • Whether read status needs to be enabled for a team message (kNIMMsgKeyTeamMsgAck), 0: not needed, 1: needed

In conjunction with read receipt service for team message, when the message is received, the read receipt service can be implemented basing on the following fields:

  • Whether the team message read receipt has been sent (kNIMMsgKeyLocalKeyTeamMsgAckSent), bool, if set to true, there is no need to send the read receipt again
  • Unread count of team message (kNIMMsgKeyLocalKeyTeamMsgUnreadCount), int, indicates the number of people who have not read the 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 GuardEase anti-spam is needed (kNIMMsgKeyAntiSpamEnable), 0: not needed, 1: needed.
  • (Optional) Anti-spam field customized by developers(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 message uses GuardEase anti-spam (kNIMMsgKeyAntiSpamUsingYiDun), 0: (GuardEase activated) not passing GuardEase anti-spam but general anti-spam, with all other matters still subject to original rules.
  • Whether the message is a hit for the client's anti-spam (kNIMMsgKeyClientAntiSpam), hit: 1 miss: 0 or empty

multi-client push switch

C++

void OnMultiportPushConfigChange(int rescode, bool switch_on)
{
	if (rescode == nim::kNIMResSuccess)
	{
		···
	}
}

void OnInit()
{
	//Log in current registered global callback to get current status of switch for multi-client push
	nim::Client::RegSyncMultiportPushConfigCb(&OnMultiportPushConfigChange);
}

void SetMultiportConfig(bool switch_on)
{
	//When PC/Web client is online, you can configure that messages are pushed to the mobile client.
	nim::Client::SetMultiportPushConfigAsync(switch_on, &OnMultiportPushConfigChange);
}

void GetMultiportConfig()
{
	//Actively get current status of switch for multi-client push
	nim::Client::GetMultiportPushConfigAsync(&OnMultiportPushConfigChange);
}

C#

public delegate void ConfigMultiportPushDelegate(ResponseCode response,ConfigMultiportPushParam param)
{
	 if (response == ResponseCode.kNIMResSuccess)
	{
		···
	}
}

/// <summary>
/// Enable multi-client push
/// </summary>
/// <param name="cb">Entrust operation results</param>
public static void EnableMultiportPush(ConfigMultiportPushDelegate cb)
{
    ConfigMultiportPushParam param = new ConfigMultiportPushParam();
    param.Enabled = true;
    var ptr = DelegateConverter.ConvertToIntPtr(cb);
    ClientNativeMethods.nim_client_set_multiport_push_config(param.Serialize(), null, ConfigMultiportPushCb, ptr);
}

/// <summary>
/// Disable multi-client push
/// </summary>
/// <param name="cb">Entrust operation results</param>
public static void DisableMultiportPush(ConfigMultiportPushDelegate cb)
{
    ConfigMultiportPushParam param = new ConfigMultiportPushParam();
    param.Enabled = false;
    var ptr = DelegateConverter.ConvertToIntPtr(cb);
    ClientNativeMethods.nim_client_set_multiport_push_config(param.Serialize(), null, ConfigMultiportPushCb, ptr);
}

/// <summary>
/// Get the control switch for multi-client push
/// </summary>
/// <param name="cb"></param>
public static void IsMultiportPushEnabled(ConfigMultiportPushDelegate cb)
{
    var ptr = DelegateConverter.ConvertToIntPtr(cb);
    ClientNativeMethods.nim_client_get_multiport_push_config(null, ConfigMultiportPushCb, ptr);
}

/// <summary>
/// Register the callback for setting synchronization of multi-client push
/// </summary>
/// <param name="cb"></param>
public static void RegMulitiportPushEnableChangedCb(ConfigMultiportPushDelegate cb)
{
    var ptr = DelegateConverter.ConvertToIntPtr(cb);
    ClientNativeMethods.nim_client_reg_sync_multiport_push_config_cb(null, OnMultiportPushEnableChanged, ptr);
}

C

static void CallbackMultiportPushConfig(int rescode, const char *content, const char *json_extension, const void *user_data)
{
	Json::Value values;
	Json::Reader reader;
	if (rescode == nim::kNIMResSuccess && reader.parse(content, values) && values.isObject())
	{
		bool open = values[kNIMMultiportPushConfigContentKeyOpen].asInt() == 1;
		···
	}
}

typedef void(*nim_client_reg_sync_multiport_push_config_cb)(const char *json_extension, nim_client_multiport_push_config_cb_func cb, const void *user_data);
typedef void(*nim_client_set_multiport_push_config)(const char *switch_content, const char *json_extension, nim_client_multiport_push_config_cb_func cb, const void *user_data);
typedef void(*nim_client_get_multiport_push_config)(const char *json_extension, nim_client_multiport_push_config_cb_func cb, const void *user_data);

void OnInit()
{
	//Log in current registered global callback to get current status of switch for multi-client push
	nim_client_reg_sync_multiport_push_config_cb func = (nim_client_reg_sync_multiport_push_config_cb) GetProcAddress(hInst, "nim_client_reg_sync_multiport_push_config_cb");
	func("", &CallbackMultiportPushConfig, nullptr);
}

void SetMultiportConfig(bool switch_on)
{
	//When PC/Web client is online, you can configure that messages are pushed to the mobile client.
	nim_client_set_multiport_push_config func = (nim_client_set_multiport_push_config) GetProcAddress(hInst, "nim_client_set_multiport_push_config");
	func(switch_on, "", &CallbackMultiportPushConfig, nullptr);
}

void GetMultiportConfig()
{
	//Actively get current status of switch for multi-client push
	nim_client_get_multiport_push_config func = (nim_client_get_multiport_push_config) GetProcAddress(hInst, "nim_client_get_multiport_push_config");
	func("", &CallbackMultiportPushConfig, nullptr);
}

Receiving messages

You must register the global broadcast notification of message reception before logging in to the SDK.

  • C++

    Online message broadcast notification:

    static void RegReceiveCb (const ReceiveMsgCallback &cb, const std::string &json_extension="")

    Broadcast notifications for offline and synchronized messages:

    static void RegReceiveMessagesCb (const ReceiveMsgsCallback &cb, const std::string &json_extension="")

    File:nim_cpp_talk.h

    Namespace:NIM

    Class:Talk

  • C#

    Online message broadcast notification:

    static EventHandler< NIMReceiveMessageEventArgs> OnReceiveMessageHandler [get, set]

    Broadcast notifications for offline and synchronized messages:

    static void RegReceiveBatchMessagesCb (ReceiveBatchMesaagesDelegate cb)

    Namespace:NIM

    Class:TalkAPI

  • C

    Online message broadcast notification:

    NIM_SDK_DLL_API void nim_talk_reg_receive_cb (const char *json_extension, nim_talk_receive_cb_func cb, const void *user_data)

    Broadcast notifications for offline and synchronized messages:

    NIM_SDK_DLL_API void nim_talk_reg_receiv_msgs_cb (const char *json_extension, nim_talk_receive_cb_func cb, const void *user_data)

    File:nim_talk.h

Example

  • C++

      void OnReceiveMsgCallback(const nim::IMMessage& message)
      {
      	std::string ID = GetSessionId(message);
    
      	if (message.feature_ == nim::kNIMMessageFeatureDefault)
      	{
      		···
      	}
      	else if (message.feature_ == nim::kNIMMessageFeatureSyncMsg || message.feature_ == nim::kNIMMessageFeatureRoamMsg)
      	{
      		···
      	}
      	else if (message.feature_ == nim::kNIMMessageFeatureCustomizedMsg)
      	{
      		···
      	}
      }
    
      void foo()
      {
      	nim::Talk::RegReceiveCb(&OnReceiveMsgCallback);
      }
    
  • C#

      void OnReceiveMessage(object sender, NIM.NIMReceiveMessageEventArgs args)
      {
      	if (args.Message.MessageContent.SessionType == NIM.Session.NIMSessionType.kNIMSessionTypepeer-to-peer && args.Message.MessageContent.SenderID != _peerId)
      		return;
      	if (args.Message.MessageContent.SessionType == NIM.Session.NIMSessionType.kNIMSessionTypeTeam && args.Message.MessageContent.ReceiverID != _peerId)
      		return;
      	//Process custom message
      	if (args.Message != null && args.Message.MessageContent.MessageType == NIMMessageType.kNIMMessageTypeCustom)
      	{
      		···
      	}
      	if (args.Message != null && args.Message.MessageContent.MessageType == NIM.NIMMessageType.kNIMMessageTypeText)
      	{
      		···
      	}
      }
    
      private void foo()
      {
      	NIM.TalkAPI.OnReceiveMessageHandler += OnReceiveMessage;
      }
    
  • C

      void CallbackReceiveMsg(const char* msg, const char *json_exten, const void *user_data)
      {
      	Json::Value value;
      	Json::Reader reader;
      	if (reader.parse(msg, value))
      	{
      		int rescode = value[nim::kNIMMsgKeyLocalRescode].asInt();
      		int feature = value[nim::kNIMMsgKeyLocalMsgFeature].asInt();
    
      		switch (feature)
      		{
      		case kNIMMessageFeatureDefault:
      			...
      		case kNIMMessageFeatureSyncMsg:
      			...
      		...
      		}
      	}
      }
    
      typedef void(*nim_talk_reg_receive_cb)(const char *json_extension, nim_talk_receive_cb_func cb, const void* user_data);
    
      void foo()
      {
      	nim_talk_reg_receive_cb func = (nim_talk_reg_receive_cb) GetProcAddress(hInst, "nim_talk_reg_receive_cb");
      	func(nullptr, &CallbackReceiveMsg, nullptr);
      }
    

Forwarding messages

The user gets a new message object using construction API, and then calls the message sending interface.

Constructor

  • C++

      /** @fn 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)
      * Generate retweet messages from other messages
      *  @param[in] src_msg_json - json of original message
      *  @param[in] client_msg_id - New client message id. It is recommended to use uuid.
      *  @param[in] retweet_to_session_type - Session type of retweet target NIMSessionType
      *  @param[in] retweet_to_session_id - Retweet target ID
      *  @param[in] msg_setting - Message attribute settings
      *  @param[in] timetag - Message time
      *  @return std::string - Json character string of location message
      */
      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)
    

    Define: NIMSessionType ; MessageSetting

    File:nim_cpp_talk.h

    Namespace:NIM

    Class:Talk

  • C#

      /** @fn
      * Generate retweet messages from other messages
      *  @param[in] srcMsg - Original message object
      *  @param[in] msgSetting - New message attributes
      *  @param[in] msgId - New client message id. It is recommended to use uuid.
      *  @param[in] sessionId	Retweet target
      *  @param[in] sessionType	Session type of retweet target
      *  @param[in] timetag - Message time
      *  @return - New message object
      */
      static NIMIMMessage CreateRetweetMessage (NIMIMMessage srcMsg, NIMMessageSetting msgSetting, string msgId, string sessionId, Session.NIMSessionType sessionType, long timetag)
    

    Define: NIMIMMessage ; NIMMessageSetting ; NIMSessionType

    Namespace:NIM

    Class:TalkAPI

  • C

      /** @fn char *nim_talk_create_retweet_msg(const char* src_msg_json, const char* client_msg_id, enum NIMSessionType retweet_to_session_type, const char* retweet_to_session_id, const char* msg_setting, int64_t timetag)
      * Generate retweet messages from other messages
      *  @param[in] src_msg_json - json of original message
      *  @param[in] client_msg_id - New client message id. It is recommended to use uuid.
      *  @param[in] retweet_to_session_type - Session type of retweet target NIMSessionType
      *  @param[in] retweet_to_session_id - Retweet target ID
      *  @param[in] msg_setting - Message attribute settings
      *  @param[in] timetag - Message time
      *  @return char * - Json character string of location message. The upper developers must invoke the interface for releasing memory nim_global.h for release.
      */
      NIM_SDK_DLL_API char *nim_talk_create_retweet_msg(const char* src_msg_json, const char* client_msg_id, enum NIMSessionType retweet_to_session_type, const char* retweet_to_session_id, const char* msg_setting, int64_t timetag);
    

    Define: NIMSessionType

    File:nim_talk.h

Example

  • C++

      void foo(nim::IMMessage msg)
      {
      	std::string send_msg = nim::Talk::CreateRetweetMessage(msg.ToJsonString(false), QString::GetGUID(), nim::kNIMSessionTypepeer-to-peer, session_id, msg.msg_setting_, 1000 * nbase::Time::Now().ToTimeT());
      	nim::Talk::SendMsg(send_msg);
      }
    
  • C#

      void foo(NIMImageMessage msg)
      {
      	NIM.NIMMessageSetting setting = new NIMMessageSetting();
      	NIMImageMessage send_msg = TalkAPI.CreateRetweetMessage(msg, setting, NimUtility.Utilities.GenerateGuid(), session_id, NIM.Session.NIMSessionType.kNIMSessionTypepeer-to-peer, 0);
      	TalkAPI.SendMessage(send_msg);  
      }
    
  • C

      typedef char*(*nim_talk_create_retweet_msg)(const char* src_msg_json, const char* client_msg_id, const NIMSessionType retweet_to_session_type, const char* retweet_to_session_id, const char* msg_setting, __int64 timetag);
      typedef	void (*nim_global_free_buf)(void *data);
    
      void foo(const char *src_msg_json, const char *msg_id, NIMSessionType session_type, const char *session_id, const char* msg_sessiong_json, __int64 timetag)
      {
      	nim_talk_create_retweet_msg func = (nim_talk_create_retweet_msg) GetProcAddress(hInst, "nim_talk_create_retweet_msg");
      	nim_global_free_buf free_func = (nim_global_free_buf) GetProcAddress(hInst, "nim_global_free_buf");
    
      	const char *msg = func(src_msg_json, msg_id, session_type, session_id, msg_sessiong_json, timetag);
      	free_func((void *)msg);
      }
    

Recall message

Sender, team owner and administrator 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, see IM Demo.

  • C++

    Active message recall interface:

    static void RecallMsg (const IMMessage &msg, const std::string &notify, const RecallMsgsCallback &cb, const std::string &json_extension="")

    Register recall notification:

    static void RegRecallMsgsCallback (const RecallMsgsCallback &cb, const std::string &json_extension="")

    File:nim_cpp_talk.h

    Namespace:NIM

    Class:Talk

  • C#

    Active message recall interface:

    static void RecallMessage (string msgId, string notify, RecallMessageDelegate cb)

    Register recall notification:

    static void RegRecallMessageCallback (RecallMessageDelegate cb)

    Namespace:NIM

    Class:TalkAPI

  • C

    Active message recall interface:

    NIM_SDK_DLL_API void nim_talk_recall_msg (const char *json_msg, const char *notify, const char *json_extension, nim_talk_recall_msg_func cb, const void *user_data)

    Register recall notification:

    NIM_SDK_DLL_API void nim_talk_reg_recall_msg_cb (const char *json_extension, nim_talk_recall_msg_func cb, const void *user_data)

    File:nim_talk.h

Parameters

  • Active message recall interface
Parameter Type Description
msg(C++) struct Object of message recall, see IMMessage
msgId(C#) string Client's message ID of the recalled message
json_msg(C) string Json string of the recalled message
notify string Custom notification
cb feature Callback feature
json_extension string json extension parameters (in reserve, currently not needed)
user_data void* APP's custom user data, which SDK is only responsible for passing back to the callback feature cb(without any processing)

Example

  • C++

      void OnReceiveRecallMsgCallback(nim::NIMResCode code, const std::list<nim::RecallMsgNotify>& message)
      {
      	for (auto notify : message)
      	{
      		if (code == nim::kNIMResSuccess)
      		{
      			···
      		}
      	}
      }
    
      void OnInit()
      {
      	nim::Talk::RegRecallMsgsCallback(&OnReceiveRecallMsgCallback);
      }
    
      void foo(const nim::IMMessage& msg)
      {
      	nim::Talk::RecallMsg(msg, "test notify when recall", &OnReceiveRecallMsgCallback);
      }
    
  • C#

      private void OnRecallMessage(ResponseCode result, RecallNotification[] notify)
      {
      	···
      }
    
      void OnInit()
      {
      	NIM.TalkAPI.RegRecallMessageCallback(OnRecallMessage);
      }
    
      private void OnRecallMessageCompleted(ResponseCode result, RecallNotification[] notify)
      {
      	···
      }
    
      void foo(string msg_id)
      {
      	NIM.TalkAPI.RecallMessage(msg_id, "Recall messages", OnRecallMessageCompleted);
      }
    
  • C

      void nim_talk_recall_msg(const char *json_msg, const char *notify, const char *json_extension, nim_talk_recall_msg_func cb, const void *user_data);
    
      void nim_talk_reg_recall_msg_cb(const char *json_extension, nim_talk_recall_msg_func cb, const void *user_data);
    
      void OnInit()
      {
      	nim_talk_reg_recall_msg_cb func = (nim_talk_reg_recall_msg_cb) GetProcAddress(hInst, "nim_talk_reg_recall_msg_cb");
    
      	func("", &OnReceiveRecallMsgCallback, nullptr);
      }
    
      void foo(const nim::IMMessage& msg)
      {
      	nim_talk_recall_msg func = (nim_talk_recall_msg) GetProcAddress(hInst, "nim_talk_recall_msg");
    
      	func(msg, "test notify when recall", "", &OnReceiveRecallMsgCallback, nullptr);
      }
    

Read receipt

In the session interface, the operation of calling the interface for sending the read receipt and inputting the last message indicates that all the previous messages have been read, and the other side will receive the receipt. Starting from v5.0.0, the SDK supports read status of team message.

  • C++

    • Read receipt for peer-to-peer message

      Send read receipt:

      static void SendReceiptAsync (const std::string &json_msg, const MessageStatusChangedCallback &cb)

      Register read status notification:

      static void RegMessageStatusChangedCb (const MessageStatusChangedCallback &cb, const std::string &json_extension="")

      Query read status:

      static bool QuerySentMessageBeReaded (const IMMessage &msg)

      File:nim_cpp_msglog.h

      Namespace:NIM

      Class:MsgLog

    • Read receipt for team message

      Send read receipt:

      static void TeamMsgAckRead(const std::string& tid, const std::list& msgs, const TeamEventCallback& cb, const std::string& json_extension = "");

      Read receipt of team message:

      static void RegTeamEventCb(const TeamEventCallback& cb, const std::string& json_extension = "");

      Notification ID:

      kNIMNotificationIdLocalGetTeamMsgUnreadCount = 2010, /**< Get unread count of team message {[{"client_msg_id":"", "count":int, "read_accid":"accid of members who have read the message"},...]}*/

      kNIMNotificationIdLocalGetTeamMsgUnreadList = 2011, /**< Get team message unread list {"client_msg_id":"", "read":["id1",...], "unread":["id2",...]} */

      Get the read status of team message (unread and read Accid list):

      static void TeamMsgQueryUnreadList(const std::string& tid, const IMMessage& msg, const TeamEventCallback& cb, const std::string& json_extension = "");

      File:nim_cpp_team.h

      Namespace:NIM

      Class:Team

  • C#

    Send read receipt:

    static void SendReceipt (NIMIMMessage msg, MsglogStatusChangedDelegate cb, string jsonExtension=null)

    Register read status notification:

    static void RegMsglogStatusChangedCb (MsglogStatusChangedDelegate cb)

    Query read status:

    static bool IsMessageBeReaded (NIMIMMessage msg, string jsonExtension=null)

    Namespace:NIM

    Class:MessagelogAPI

  • C

    • Read receipt for peer-to-peer message

      Send read receipt:

      NIM_SDK_DLL_API void nim_msglog_send_receipt_async (const char *json_msg, const char *json_extension, nim_msglog_status_changed_cb_func cb, const void *user_data)

      Register read status notification:

      NIM_SDK_DLL_API void nim_msglog_reg_status_changed_cb (const char *json_extension, nim_msglog_status_changed_cb_func cb, const void *user_data)

      Query read status:

      NIM_SDK_DLL_API bool nim_msglog_query_be_readed (const char *json_msg, const char *json_extension)

      File:nim_msglog.h

    • Read receipt for team message

      Send read receipt:

      NIM_SDK_DLL_API void nim_team_msg_ack_read(const char *tid, const char *json_msgs, const char *json_extension, nim_team_opt_cb_func cb, const void *user_data);

      Read receipt of team message:

      NIM_SDK_DLL_API void nim_team_reg_team_event_cb(const char *json_extension, nim_team_event_cb_func cb, const void *user_data);

      Notification ID:

      kNIMNotificationIdLocalGetTeamMsgUnreadCount = 2010, /**< Get unread count of team message {[{"client_msg_id":"", "count":int, "read_accid":"accid of members who have read the message"},...]}*/

      kNIMNotificationIdLocalGetTeamMsgUnreadList = 2011, /**< Get team message unread list {"client_msg_id":"", "read":["id1",...], "unread":["id2",...]} */

      Get the read status of team message (unread and read Accid list):

      NIM_SDK_DLL_API void nim_team_msg_query_unread_list(const char *tid, const char *json_msg, const char *json_extension, nim_team_opt_cb_func cb, const void *user_data);

      File:nim_team.h

Parameters

  • Read receipt for peer-to-peer message
Parameter Type Description
msg(C#) struct Object of message read, see NIMIMMessage
json_msg(C/C++) string Json string for marking message read
cb feature Callback feature
json_extension string json extension parameters (in reserve, currently not needed)
user_data void* APP's custom user data, which SDK is only responsible for passing back to the callback feature cb(without any processing)
  • Read receipt for team message
Parameter Type Description
tid string Team ID
msgs(C++) std::list Object of message read mark, see NIMIMMessage
msgs(C) json array string Json string for marking message read
cb feature Callback feature
json_extension string json extension parameters (in reserve, currently not needed)
user_data void* APP's custom user data, which SDK is only responsible for passing back to the callback feature cb(without any processing)

Example

  • C++

    • Read receipt for peer-to-peer message

        //Send acknowledged receipt
        void foo(nim::IMMessage msg)
        {
        	nim::MsgLog::SendReceiptAsync(msg.ToJsonString(false), [](const nim::MessageStatusChangedResult& res) {
        	auto iter = res.results_.begin();	
        	});
        }
      
        //Query acknowledged status of a message
        bool IsMsgReaded(nim::IMMessage &msg)
        {
        	if (nim::MsgLog::QueryMessageBeReaded(msg))
        	{
        		return true;
        	}
      
        	return false;
        }
      
        //Get acknowledged status of messages through registered broadcast notification for change in message status in advance
        void OnMsgStatusChangedCallback(const nim::MessageStatusChangedResult& res)
        {
        	for (auto res : res.results_)
        	{
        		if (res.status_ == kNIMMsgLogStatusReceipt)
        		{
        			...
        		}
        	}
        }
      
        void OnInit()
        {
        	nim::MsgLog::RegMessageStatusChangedCb(&OnMsgStatusChangedCallback);
        }
      
    • Read receipt for team message

        //Mark team messages as acknowledged at a time
        void SessionBox::InvokeSetRead(const std::list<nim::IMMessage> &msgs)
        {
        	nim::Team::TeamMsgAckRead(session_id_, msgs, nim::Team::TeamEventCallback());
        }
      
        //Get acknowledged status of team messages through registered team time broadcast in advance
        void TeamCallback::OnTeamEventCallback(const nim::TeamEvent& result)
        {
        	if (result.notification_id_ == nim::kNIMNotificationIdLocalGetTeamMsgUnreadCount)
        	{
        		...
        	}
        }
      
        void Init()
        {
        	//Register the callback for team events
        	nim::Team::RegTeamEventCb(nbase::Bind(&nim_comp::TeamCallback::OnTeamEventCallback, std::placeholders::_1));
        }
      
        //Get the list of read and unread team messages
        void UnreadForm::DoLoadList()
        {
        	nim::Team::TeamMsgQueryUnreadList(msg_.recipient_accid_, msg_, nbase::Bind(&UnreadForm::OnTeamEventCallback, std::placeholders::_1));
        }
      
        void UnreadForm::OnTeamEventCallback(const nim::TeamEvent& result)
        {
        	UnreadForm * win = (UnreadForm *)nim_comp::Windowsadministrator::GetInstance()->GetWindow(UnreadForm::kClassName, UnreadForm::kClassName);
        	if (win)
        		win->OnLoadListCallback(result);
        }
      
  • C#

      //Send acknowledged receipt
    
      //Query acknowledged status of a message
      bool IsMsgReaded(NIM.NIMTextMessage msg)
      {
      	return NIM.Messagelog.MessagelogAPI.IsMessageBeReaded(msg);
      }
    
      //Get acknowledged status of messages through registered broadcast notification for change in message status in advance
      void OnInit()
      {
      	NIM.Messagelog.MessagelogAPI.RegMsglogStatusChangedCb((res, result) =>
      	{
      		···
      	});
      }
    
  • C

      //Send acknowledged receipt
    
      typedef bool(*nim_msglog_query_be_readed)(const char *json_msg, const char *json_extension);
    
      bool foo(const char *json_msg)
      {
      	nim_msglog_query_be_readed func = (nim_msglog_query_be_readed) GetProcAddress(hInst, "nim_msglog_query_be_readed");
    
      	return func(json_msg, "");
      }
    
      //Get acknowledged status of messages through registered broadcast notification for change in message status in advance
      void CallbackMsgStatusChanged(int rescode, const char *result, const char *json_extent, const void *callback)
      {
      	// parse result
      }
    
      typedef void(*nim_msglog_reg_status_changed_cb)(const char *json_extension, nim_msglog_status_changed_cb_func cb, const void *user_data);
    
      void foo(const char *json_msg)
      {
      	nim_msglog_reg_status_changed_cb func = (nim_msglog_reg_status_changed_cb) GetProcAddress(hInst, "nim_msglog_reg_status_changed_cb");
    
      	func( "", &CallbackMsgStatusChanged, nullptr);
      }
    

Multimedia message

Voice-to-text

SDK provides a voice-to-text interface.

void nim_tool_get_audio_text_async(const char *json_audio_info, const char *json_extension, nim_tool_get_audio_text_cb_func cb, const void *user_data);

For example:

C++

void foo(nim::IMMessage &msg_data)
{
	nim::IMAudio audio;
	nim::Talk::ParseAudioMessageAttach(msg_data, audio);
	nim::AudioInfo audio_info;
	audio_info.samplerate_ = "16000";
	audio_info.url_ = audio.url_;
	audio_info.duration_ = audio.duration_;
	audio_info.mime_type_ = audio.file_extension_;

	nim::Tool::GetAudioTextAsync(audio_info, ToWeakCallback([this](int rescode, const std::string& text) {
		if (rescode == nim::kNIMResSuccess) {
			···
		}
		else {
			···
		}
	}));
}

C#

private void foo(NIM.NIMIMMessage msg)
{
    NIM.NIMAudioInfo info = new NIMAudioInfo();
    info.Duration = 1000;
    info.SampleRate = "16000";
    info.URL = "···";
    info.MimeType = "aac";
    NIM.ToolsAPI.GetAudioTextAsync(info, "", OnGetText);
}
private void OnGetText(int rescode, string text, string json_extension, IntPtr user_data)
{
}

C

void CallbackGetAudioText(int rescode, const char *text, const char *json_extension, const void *user_data)
{
	...
}

typedef void(*nim_tool_get_audio_text_async)(const char *json_audio_info, const char *json_extension, nim_tool_get_audio_text_cb_func cb, const void *user_data);

void foo()
{
	Json::Value json_value;
	json_value[nim::kNIMTransAudioKeyMime] = ; //mime type
	json_value[nim::kNIMTransAudioKeySample] = ; //Sampling rate
	json_value[nim::kNIMTransAudioKeyAudioUrl] = ; //Download address
	json_value[nim::kNIMTransAudioKeyDuration] = ; //Duration (ms)

	nim_tool_get_audio_text_async func = (nim_tool_get_audio_text_async) GetProcAddress(hInst, "nim_tool_get_audio_text_async");
	func(json_value.toStyledString().c_str(), nullptr, &CallbackGetAudioText, nullptr);
}

Get image thumbnail

In default, after receiving a picture message, CommsEase PC SDK will pre-load the original image for local cache.Developers may set kNIMPreloadImageQuality (for quality control) to control the quality of the downloaded images and set kNIMPreloadImageResize (for size control) to control the length and width of the images when initializing the SDK. In the IM Demo's development example, original images are downloaded by default. Therefore, for the purpose of development based on source codes of IM Demo, developers need to download the original images in the process of image preview or from the channel where display of original images are required.

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 a 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 URL 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 URL is http(s)://?imageView&quality=N; http(s)://xxx; where N is image quality, with a range of 0-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 URL 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 See bubble_image.cpp

Get video cover

By default, CommsEase PC SDK currently downloads the video cover (screenshot taken in the first second of the video) and caches it locally after receiving the video message. For other application scenes, developers can use one method described below to download videos by the specified frame rate:

The format of the request link is as follows:
Http(s)://xxx?vframe&offset=1&resize=300x300&type=jpg;
parameter description

Name Description Required nor not
vframe Operation mark of video screenshot Yes
offset Start time of taking the screenshot, 0 by default No
resize Width x height No
crop crop=x_y_width_height indicates to crop a sub-image of width*height from the original coordinates (x, y) No
type Image format, jpg. by default No

Developers can See bubble_video.cpp of IM Demo

Was this page helpful?
Yes
No
  • Messaging
  • Sending messages
  • Text message
  • Image message
  • File message
  • Voice message
  • Short video message
  • Location message
  • Message alert
  • Robot message
  • User-defined messages
  • Message property settings
  • multi-client push switch
  • Receiving messages
  • Example
  • Forwarding messages
  • Constructor
  • Example
  • Recall message
  • Parameters
  • Example
  • Read receipt
  • Parameters
  • Example
  • Multimedia message
  • Voice-to-text
  • Get image thumbnail
  • Get video cover