【问题标题】:Detecting if User Exists on the Discord Client (Discord.js)检测用户是否存在于 Discord 客户端 (Discord.js)
【发布时间】:2020-12-10 06:50:03
【问题描述】:

我一直在尝试检测 Discord 客户端本身是否存在用户...我使用了这个:

var user_id;

//on message and after assigning user_id
if(client.users.cache.get(user_id) !== undefined) {
//checks if user does exist on the client and does action (it always thinks it's undefined for some reason)
}

你能帮帮我吗?感谢您的所有帮助...

谢谢你, Rako 游戏

【问题讨论】:

  • 你试过这个吗:client.fetch(user_id)

标签: javascript node.js discord.js detect


【解决方案1】:

欢迎来到 SO!这就是我的做法。 UserManager#Cache 是一个集合,因此您可以使用Collection#has 检查您要查找的内容是否存在。演示:

const userId = "000000000000000000";
const exists = client.users.cache.has(userId);
console.log(exists); // true or false

// Advice to stop making cringe code --no worries, we've all been there before ;)
if (exists) doSomething(); // And not: if (exists === true), although it still can be used in other places
if (!exists) do SomethingElse(); // And definitely not: if (exists === false)

当然,这将在缓存中进行搜索,因此如果您的机器人启动时用户从未做过任何事情,它将无法工作。使用UserManager#fetch 获取并测试用户是否存在:

const exists = await client.users.fetch(userId); // Warning: await here. To be used in async functions, or to be replaced by .then()
// Here, the user is cached
console.log(exists); // undefined or User; can be check as in the snippet above. You can still wrap 'exists' with Boolean() if you feel more comfortable having boolean values

【讨论】:

  • 是的,如果我使用它,它会起作用:if(exists = true){} 谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-08
  • 2016-05-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多