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

如何在discord.js中标记玩家并获取Discord ID(修复重复输出问题)

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

嘿,我来帮你搞定这个重复输出的问题!

问题原因

你的代码里在for循环中每匹配到一个joined数组里的元素就会发送一次ID。如果同一个用户在joined数组里出现了多次(比如用户多次加入游戏,或者数组随着操作不断累积元素),就会对应发送多次ID——这就是为啥第一个用户ID输出1次、第二个2次、第三个3次的原因。

修复方案

方案一:找到匹配后立刻跳出循环

修改循环逻辑,只要找到匹配的用户,发送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)){ 
    for(var i = 0; i < joined.length; i++){ 
      if(mention.id === user[joined[i]].getID()) { 
        playerFind.channel.send(mention.id); 
        break; // 找到匹配后直接跳出循环,只发送一次
      } 
    } 
  } 
})

方案二:先判断存在性再发送(更高效)

用Array.some()方法先检查用户是否在joined对应的列表中,存在就发送一次,不需要遍历整个数组:

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)){ 
    // 检查目标用户是否在joined列表中
    const userExists = joined.some(item => mention.id === user[item].getID());
    if (userExists) {
      playerFind.channel.send(mention.id);
    }
  } 
})

这两种方案都能实现“每个用户ID仅输出1次”的需求,你可以根据自己的习惯选择~

内容的提问来源于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:57:16