最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Check if user ID exists in Discord server - Stack Overflow

programmeradmin3浏览0评论

My Discord bot needs to check whether a user is in the server or not. I'm using node.js and discord.js.

var USER_ID = randomNumbers
if (client.guild.member(USER_ID).exists){
   do something
}

Is there a way to do this?

My Discord bot needs to check whether a user is in the server or not. I'm using node.js and discord.js.

var USER_ID = randomNumbers
if (client.guild.member(USER_ID).exists){
   do something
}

Is there a way to do this?

Share Improve this question asked Nov 13, 2018 at 10:21 Thomas BlasquezThomas Blasquez 1181 gold badge1 silver badge8 bronze badges
Add a comment  | 

4 Answers 4

Reset to default 10

If you have the Guild object, you can use the Guild.member() method.

let guild = client.guilds.get('guild ID here'),
  USER_ID = '123123123';

if (guild.member(USER_ID)) {
  // there is a GuildMember with that ID
}

This is very similar to Way to check if a channel exists and the solution should be identical. Essentially, you need to get the guild collection, and then use the discord.js 'Collection.exists' helper function to check if the element (user id) exists in the collection (channel user list).

If in doubt, always check the documentation. :)

https://discord.js.org/#/docs/main/stable/class/Collection?scrollTo=exists

EDIT : Upon further reading, I noticed that 'Collection.exists' is deprecated. The documentation suggests using 'Collection.has' in it's place.

guild.member(USER_ID) - is a legacy syntax

If the above doesn't work for you, chanses are you are using discord.js v12 so that you'll have to do this:

let guild = client.guilds.get('guild ID here'),
  USER_ID = '123123123';

if (guild.member.fetch(USER_ID)) {
  // there is a GuildMember with that ID
}

Note that fetch() is an async function which returns a 'promise'. The code above is enough for checking whether the user is a member of a guild but if you wish to read the return value of guild.member.fetch(USER_ID) then you'll have to do the following

guild.members.fetch(usrID) 
 .then((data) => console.log(data));

You might find this to be helpful, provided you have an array of server member IDs and the ID of the member you are looking for: How do I check if an array includes an object in JavaScript?

You can use Array#includes to check to see if an array contains a specified object, or in this case your member ID.

发布评论

评论列表(0)

  1. 暂无评论