开发Cisco Webex机器人如何将空间成员转为数组并随机抽取1人
问题原因
你现有代码的核心逻辑错误有2处:
- 你不需要对单个成员的姓名做
split('\n')处理:member.personDisplayName本身是单个用户的姓名,你现在是遍历每个成员时单独处理单个姓名,根本没把所有成员汇总到同一个数组里 - 随机数计算时用到的
items.length属于未定义变量,你没有先汇总所有符合条件的成员名单
修复后代码
framework.hears("daily host", function (bot) { console.log("Choosing a daily host"); responded = true; // 先定义空数组存所有符合条件的成员 const candidateMembers = []; // Use the webex SDK to get the list of users in this space bot.webex.memberships.list({roomId: bot.room.id}) .then((memberships) => { // 遍历所有成员,排除机器人自己,把符合条件的加入候选数组 for (const member of memberships.items) { if (member.personId === bot.person.id) { // Skip myself! continue; } const name = member.personDisplayName || member.personEmail; candidateMembers.push(name); } // 候选数组为空的兜底处理 if (candidateMembers.length === 0) { bot.say('Hello everybody!'); return; } // 随机抽取1个成员 const randomIndex = Math.floor(Math.random() * candidateMembers.length); const pickedHost = candidateMembers[randomIndex]; console.log(pickedHost); bot.say(`Hello ${pickedHost}`); }) .catch((e) => { console.error(`Call to sdk.memberships.get() failed: ${e.messages}`); bot.say('Hello everybody!'); }); });
关键修改说明
- 新增了
candidateMembers空数组,遍历所有成员时,把排除机器人后的所有用户姓名统一存入这个数组 - 移除了无意义的
split('\n')操作,单个用户姓名不需要拆分 - 遍历完全部成员后再做随机抽取,随机数的取值范围用候选数组的长度计算,避免未定义变量报错
- 增加了候选数组为空的兜底判断,避免极端情况下数组越界报错
内容的提问来源于stack exchange,提问作者stevemayster
相关产品推荐
相关产品推荐

