消息收发

消息说明

初始化参数

示例代码

var nim = NIM.getInstance({
    onroamingmsgs: onRoamingMsgs,
    onofflinemsgs: onOfflineMsgs,
    onmsg: onMsg
});
function onRoamingMsgs(obj) {
    console.log('收到漫游消息', obj);
    pushMsg(obj.msgs);
}
function onOfflineMsgs(obj) {
    console.log('收到离线消息', obj);
    pushMsg(obj.msgs);
}
function onMsg(msg) {
    console.log('收到消息', msg.scene, msg.type, msg);
    pushMsg(msg);
    switch (msg.type) {
    case 'custom':
        onCustomMsg(msg);
        break;
    case 'notification':
        // 处理群通知消息
        onTeamNotificationMsg(msg);
        break;
    // 其它case
    default:
        break;
    }
}
function pushMsg(msgs) {
    if (!Array.isArray(msgs)) { msgs = [msgs]; }
    var sessionId = msg[0].scene + '-' + msgs[0].account;
    data.msgs = data.msgs || {};
    data.msgs[sessionId] = nim.mergeMsgs(data.msgs[sessionId], msgs);
}
function onCustomMsg(msg) {
    // 处理自定义消息
}

参数解释

消息对象

消息对象有以下字段

消息场景

消息对象有一个字段scene来标明消息所属的场景, 具体场景如下

消息类型

消息对象有一个字段type来标明消息的类型, 具体类型如下

不同类型的消息收发可参考:

文本对象

发送文本消息或收到文本消息时, 消息对象text字段代表文本消息内容

图片对象

发送图片消息或收到图片消息时, 消息对象file字段代表图片对象, 包含以下属性:

音频对象

发送音频消息或收到音频消息时, 消息对象file字段代表音频对象, 包含以下属性:

视频对象

发送视频消息或收到视频消息时, 消息对象file字段代表视频对象, 包含以下属性:

视频对象取封面(首帧图片):

文件对象

发送文件消息或收到文件消息时, 消息对象file字段代表文件对象, 包含以下属性:

地理位置对象

发送地理位置消息或收到地理位置消息时, 消息对象geo字段代表地理位置对象, 包含以下属性:

机器人消息对象

发送机器人消息或收到机器人消息时, 消息对象会包含以下属性:

群通知消息

处理群通知消息

示例代码

function onTeamNotificationMsg(msg) {
    // 处理群通知消息
    var type = msg.attach.type,
        from = msg.from,
        teamId = msg.to,
        timetag = msg.time,
        team = msg.attach.team,
        account = msg.attach.account,
        accounts = msg.attach.accounts,
        members = msg.attach.members;
    switch (type) {
    case 'updateTeam':
        team.updateTime = timetag;
        onTeams(team);
        break;
    case 'addTeamMembers':
        onAddTeamMembers(team, accounts, members);
        break;
    case 'removeTeamMembers':
        onRemoveTeamMembers(team, teamId, accounts);
        break;
    case 'acceptTeamInvite':
        onAddTeamMembers(team, [from], members);
        break;
    case 'passTeamApply':
        onAddTeamMembers(team, [account], members);
        break;
    case 'addTeamManagers':
        updateTeamManagers(teamId, members);
        break;
    case 'removeTeamManagers':
        updateTeamManagers(teamId, members);
        break;
    case 'leaveTeam':
        onRemoveTeamMembers(team, teamId, [from]);
        break;
    case 'dismissTeam':
        dismissTeam(teamId);
        break;
    case 'transferTeam':
        transferTeam(team, members);
        break;
    }
}
function onAddTeamMembers(team, accounts, members) {
    var teamId = team.teamId;
    /*
    如果是别人被拉进来了,那么拼接群成员列表
    如果是自己被拉进来了,那么同步一次群成员列表
    */
    if (accounts.indexOf(data.account) === -1) {
        onTeamMembers({
            teamId: teamId,
            members: members
        });
    } else {
        nim.getTeamMembers({
            teamId: teamId,
            sync: true,
            done: function(error, obj) {
                if (!error) {
                    onTeamMembers(obj);
                }
            }
        });
    }
    onTeams(team);
}
function onRemoveTeamMembers(team, teamId, accounts) {
    /*
    如果是别人被踢了,那么移除群成员
    如果是自己被踢了,那么离开该群
    */
    if (accounts.indexOf(data.account) === -1) {
        if (team) {
            onTeams(team);
        }
        data.teamMembers[teamId] = nim.cutTeamMembersByAccounts(data.teamMembers[teamId], teamId, accounts);
        refreshTeamMembersUI();
    } else {
        leaveTeam(teamId);
    }
}
function updateTeamManagers(teamId, members) {
    onTeamMembers({
        teamId: teamId,
        members: members
    });
};
function leaveTeam(teamId) {
    onInvalidTeams({
        teamId: teamId
    });
    removeAllTeamMembers(teamId);
}
function dismissTeam(teamId) {
    onInvalidTeams({
        teamId: teamId
    });
    removeAllTeamMembers(teamId);
}
function removeAllTeamMembers(teamId) {
    delete data.teamMembers[teamId];
    refreshTeamMembersUI();
}
function transferTeam(team, members) {
    var teamId = team.teamId;
    onTeamMembers({
        teamId: teamId,
        members: members
    });
    onTeams(team);
}

参数解释

发送消息

发送文本消息

var msg = nim.sendText({
    scene: 'p2p',
    to: 'account',
    text: 'hello',
    done: sendMsgDone
});
console.log('正在发送p2p text消息, id=' + msg.idClient);
pushMsg(msg);
function sendMsgDone(error, msg) {
    console.log(error);
    console.log(msg);
    console.log('发送' + msg.scene + ' ' + msg.type + '消息' + (!error?'成功':'失败') + ', id=' + msg.idClient);
    pushMsg(msg);
}

预览文件

nim.previewFile({
    type: 'image',
    fileInput: fileInput,
    uploadprogress: function(obj) {
        console.log('文件总大小: ' + obj.total + 'bytes');
        console.log('已经上传的大小: ' + obj.loaded + 'bytes');
        console.log('上传进度: ' + obj.percentage);
        console.log('上传进度文本: ' + obj.percentageText);
    },
    done: function(error, file) {
        console.log('上传image' + (!error?'成功':'失败'));
        // show file to the user
        if (!error) {
            var msg = nim.sendFile({
                scene: 'p2p',
                to: 'account',
                file: file,
                done: sendMsgDone
            });
            console.log('正在发送p2p image消息, id=' + msg.idClient);
            pushMsg(msg);
        }
    }
});

发送文件消息

nim.sendFile({
    scene: 'p2p',
    to: 'account',
    type: 'image',
    fileInput: fileInput,
    beginupload: function(upload) {
        // - 如果开发者传入 fileInput, 在此回调之前不能修改 fileInput
        // - 在此回调之后可以取消图片上传, 此回调会接收一个参数 `upload`, 调用 `upload.abort();` 来取消文件上传
    },
    uploadprogress: function(obj) {
        console.log('文件总大小: ' + obj.total + 'bytes');
        console.log('已经上传的大小: ' + obj.loaded + 'bytes');
        console.log('上传进度: ' + obj.percentage);
        console.log('上传进度文本: ' + obj.percentageText);
    },
    uploaddone: function(error, file) {
        console.log(error);
        console.log(file);
        console.log('上传' + (!error?'成功':'失败'));
    },
    beforesend: function(msg) {
        console.log('正在发送p2p image消息, id=' + msg.idClient);
        pushMsg(msg);
    },
    done: sendMsgDone
});

发送地理位置消息

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

发送提醒消息

var msg = nim.sendTipMsg({
    scene: 'p2p',
    to: 'account',
    tip: 'tip content',
    done: sendMsgDone
});
console.log('正在发送p2p提醒消息, id=' + msg.idClient);
pushMsg(msg);

发送自定义消息

var value = Math.ceil(Math.random()*3);
var content = {
    type: 1,
    data: {
        value: value
    }
};
var msg = nim.sendCustomMsg({
    scene: 'p2p',
    to: 'account',
    content: JSON.stringify(content),
    done: sendMsgDone
});
console.log('正在发送p2p自定义消息, id=' + msg.idClient);
pushMsg(msg);

发送机器人消息

// 直接在p2p会话中发送机器人消息
var msg = nim.sendRobotMsg({
    scene: 'p2p',
    to: 'robotAccid',
    content: {
      type: 'text',
      content: '机器人你好'
    }
    done: sendMsgDone
});

// 在于他人的会话中通过@机器人 发送机器人消息
var msg = nim.sendRobotMsg({
  scene: 'p2p',
  to: 'account',
  robotAccid: 'robotAccid',
  content: {
    type: 'link',
    params: 'a=1&b=2',
    target: 'A511F4B67336BE45-954F87865D2205C8'
  }
  done: sendMsgDone
})

function sendMsgDone(error, msg) {
    console.log(error, msg);
    console.log('发送' + msg.scene + ' ' + msg.type + '消息' + (!error?'成功':'失败') + ', id=' + msg.idClient);
    // ...
}

机器人回复消息模板解析

发送消息的配置选项

var msg = nim.sendText({
    scene: 'p2p',
    to: 'account',
    text: 'hello',
    custom: '{}',
    done: sendMsgDone
});

发送本地消息

var value = Math.ceil(Math.random()*3);
var content = {
    type: 1,
    data: {
        value: value
    }
};
var msg = nim.sendCustomMsg({
    scene: 'p2p',
    to: 'account',
    content: JSON.stringify(content),
    isLocal: true,
    done: sendMsgDone
});
console.log('正在发送p2p自定义消息, id=' + msg.idClient);
pushMsg(msg);

重发消息

如果消息发送失败, 那么可以重发消息

nim.resendMsg({
  msg: someMsg,
  done: sendMsgDone
})
console.log('正在重发消息', someMsg)

转发消息

nim.forwardMsg({
  msg: someMsg,
  scene: 'p2p',
  to: 'account',
  done: sendMsgDone
})
console.log('正在转发消息', someMsg)

消息撤回

nim.deleteMsg({
  msg: someMsg,
  done: deleteMsgDone
})
console.log('正在撤回消息', someMsg)
function deleteMsgDone (error) {
  console.log('撤回消息' + (!error?'成功':'失败'), error);
}

标记消息为已收到

示例代码

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

已读回执

发送消息已读回执

nim.sendMsgReceipt({
    msg: session.lastMsg,
    done: sendMsgReceiptDone
});
function sendMsgReceiptDone(error, obj) {
    console.log('发送消息已读回执' + (!error?'成功':'失败'), error, obj);
}

查询消息是否被对方读过了

var isRemoteRead = nim.isMsgRemoteRead(msg);