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

Discord.js中提及玩家并获取Discord ID:重复输出问题求助

解决Discord机器人重复输出用户ID的问题

嘿,我瞅你这Discord机器人遇到重复输出用户ID的问题了,咱们来捋捋怎么修复!

问题根源

你当前的代码逻辑是:在joined数组里循环遍历,每匹配到一次用户ID就发送一次消息。这就导致如果用户在joined数组里对应多个条目(或者循环里多次匹配成功),就会重复输出ID——比如第三个用户匹配了3次,就发3遍ID。

修复方案

核心思路是找到匹配项后只发送一次ID,然后停止循环,或者先确认用户存在再统一发送。下面给你两种可行的修改方式:

方式一:找到后发送并立即跳出循环

这种方式最直接,一旦匹配成功就发送ID,然后用break终止循环,避免后续重复匹配:

client.on('message', function(playerFind) { 
  const playerID = playerFind.content; 
  if (playerFind.author.bot) return; 
  let mention = playerFind.mentions.users.first(); 
  if((playerID.startsWith('!find id ')) && (mention) && (joined.length > 0)){
    for(var i = 0; i < joined.length; i++){
      if(mention.id === user[joined[i]].getID()) { 
        playerFind.channel.send(mention.id);
        // 发送后立刻跳出循环,防止重复输出
        break;
      }
    }
  } 
})

方式二:先标记是否找到,循环结束后统一发送

这种方式先遍历整个数组确认用户是否存在,标记后再发送ID,适合需要完整遍历数组做其他操作的场景:

client.on('message', function(playerFind) { 
  const playerID = playerFind.content; 
  if (playerFind.author.bot) return; 
  let mention = playerFind.mentions.users.first(); 
  if((playerID.startsWith('!find id ')) && (mention) && (joined.length > 0)){
    let isUserFound = false;
    for(var i = 0; i < joined.length; i++){
      if(mention.id === user[joined[i]].getID()) { 
        isUserFound = true;
        // 这里可以加其他需要的操作,比如记录用户位置等
        break; // 同样可以提前跳出循环提升效率
      }
    }
    // 确认找到后只发送一次ID
    if(isUserFound) {
      playerFind.channel.send(mention.id);
    }
  } 
})

效果验证

修改后,不管用户在joined数组里有多少匹配项,只会输出一次ID,完全符合你期望的效果:

  • 第一个用户-1234566
  • 第二个用户-1234576
  • 第三个用户-1234586

内容的提问来源于stack exchange,提问作者Coding Master

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 07:54:37