You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

开发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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 05:06:04