For some odd reason when I try to check if a member is in a guild it throws error
Uncaught TypeError: client.guilds.get is not a function
Here is a section of my code.
//IDS TO BAN
USER_ID = '860926166956769280 // test account' //863609914291388467
USER_ID2 = '863929485845594152'
USER_ID3 = '863572599221256203'
GUILD = '863564803892576276' // guild to ban members in
let guildToCheck = client.guilds.get(GUILD), // line it gets stuck on
server = msg.guild
// Check if forbidden users exist.
if (guildToCheck.member.fetch(USER_ID)) {
server.members.ban(USER_ID)
}
if (guildToCheck.member.fetch(USER_ID2)) {
server.members.ban(USER_ID2)
}
if (guildToCheck.member.fetch(USER_ID3)) {
server.members.ban(USER_ID3)
}
I am using the newest version of Node.js and discord.js.
Any help would be appreciated. Thanks.
As of DJS v12, you have to go through the cache to get a user/channel/guild or use .fetch() to get the user from the API, but be warned the latter returns a Promise.
Basically, as long as the guild is already cached, just do client.guilds.cache.get(GUILD) and that should solve your error.
Related
I am merging a bot under discord.js v12 to a newer bot with discord.js v14.
However it's my first experience on the node and I don't understand everything, I'm doing well in lua but I don't understand...
The events return me errors either it does not find the guild or it is impossible to rename a player, or a player is not found...
Here is how it is, I comment you the events according to the return of log that I have
on("DiscordBot:RenameMember", (guild, discordid, fullname) => {
let targetguild = client.guilds.cache.first(); // I got on log the name of GUILD
if (targetguild) {
let target = targetguild.members.fetch(discordid); // I got on log : [object Promise]
if (target) {
target.setNickname(fullname); // I got on log : TypeError: target.setNickname is not a function
target.member.setNickname(fullname); // I got on log : TypeError: Cannot read properties of undefined (reading 'setNickname')
}
}
});
I made a multitude of tests with cache, without cache but nothing makes it all I find is similar and does not work here...
Here you will find the launch of the bot :
https://hastebin.com/ovipelopam.js
And here is the file I made separately to find my way around :
https://hastebin.com/azaraqituh.js
Do you have an idea ?
In your case targetguild.members.fetch(discordid) seems to return a Promise, which is an async operation. Therefore target has no value right away, but instead, has to either be awaited, or the rest of the code has to be put in the then function, that can be set to the promise.
Here is an example where you await the promise to resolve. In order to achieve this you have to define your function as async, so that it itself returns a Promise:
on("DiscordBot:RenameMember", async (guild, discordid, fullname) => {
let targetguild = client.guilds.cache.first(); // I got on log the name of GUILD
if (targetguild) {
let target = await targetguild.members.fetch(discordid); // I got on log : [object Promise]
if (target) {
target.setNickname(fullname); // I got on log : TypeError: target.setNickname is not a function
target.member.setNickname(fullname); // I got on log : TypeError: Cannot read properties of undefined (reading 'setNickname')
}
}
});
Thank you for answering and explaining,
I still don't understand how it works, but it will come...
I had some problems with the setNickname and it started to work without understanding why either :)
Here is what I get in the end :
on("DiscordBot:RenameMember", async (guild, discordid, fullname) => {
let targetguild = client.guilds.cache.first();
if (targetguild) {
let target = await targetguild.members.fetch(discordid);
if (target) {
// target.setNickname(fullname); // I got on log : TypeError: target.setNickname is not a function
// target.members.setNickname(fullname); // I got on log : TypeError: Cannot read properties of undefined (reading 'setNickname')
let targetRename = await target.setNickname(fullname, 'Modification correspondant au profile InGame'); // That work
}
}
});
Thanks again :)
I am using discord js v13.6. I have written in my code where after using a slash command user is assigned many roles which are stored in a array named rolenumber. The problem is I am getting this error every time
await client.users.fetch(memberId).then((user,interaction) => {
user.send("Give me a few moments while I verify your details");
(async function(user){
let RoleArray = rolenumber.split(",");
//let guild = client.guilds.cache.get(guildNumber);
//let member = await client.users.fetch(msg);
for(let num of RoleArray) {
//console.log("Roles Inside a for loop",num);
let role = interaction.guild.roles.cache.get(num);
let data = await user.roles.add(role).catch(console.error);
//user.roles.add(num).catch(console.error);
}
let welcomeMessage = 'Welcome <#'+ user.id +'>, you are now officially part of channel.';
const channelMessage = await client.channels.cache.get(channelNumber);
channelMessage.send(welcomeMessage);
})();
here the guildNumber is a guild Number which is hidden for security reason from the question. I am getting this as error message:
let role = interaction.guild.roles.cache.get(num);
^
TypeError: Cannot read properties of undefined (reading 'guild')
at E:\OutscalGit\DiscordBot\index.js:200:44
at processTicksAndRejections (node:internal/process/task_queues:96:5)
interaction is undefined
Are you sure, interaction is passed to here?
you can use it but it not perfect
let role = interaction?.guild?.roles?.cache?.get(num);
Promise.prototype.then's fulfillment callback only takes 1 argument.
await client.users.fetch(memberId).then((user) => {
user.send("Give me a few moments while I verify your details")
// ...
})
Assuming interaction is already defined above, it should work
So I have this discord bot and since I'm personally hosting it from my pc with nodejs I wanted to make the bot update the members list on my webapi everytime I boot it back up.
Problem is that Using the code below the console returns an error saying the member.get is not a function.
var timestamp=Date.now(), json={timestamp:timestamp, guilds:[]}, count=0;
try{
client.guilds.forEach(guild => {
json.guilds.push(guild);
var list = guild.members;
json.guilds[count].members=[];
list.forEach(member => json.guilds[count].members.push(member.user.id));
count++;
});
} catch(e) {
console.log(e);
}
The error:
TypeError: this.members.get is not a function
Anyone can help?
Thanks in advance.
Since Discord.js v12 you need to use the cache:
So instead of...
guild.members.get();
...you have to do this:
guild.members.cache.get();
I'm trying to use multiple user mentions and message.mention.members.first() cannot do this. So I did some digging and found this function from Parsing Mention Arguments:
function getUserFromMention(mention) {
if (!mention) return;
if (mention.startsWith('<#') && mention.endsWith('>')) {
mention = mention.slice(2, -1);
if (mention.startsWith('!')) {
mention = mention.slice(1);
}
return client.users.cache.get(mention);
}
}
When I try to use this function I get the "Discord JS - TypeError: Cannot read property 'setChannel' of undefined" here is the code causing the error
let channel = client.channels.cache.find(channel => channel.name === args[0]);
const user1 = getUserFromMention(args[1]);
const user2 = getUserFromMention(args[2]);
message.member.voice.setChannel(channel.id);
user1.voice.setChannel(channel.id);
user2.voice.setChannel(channel.id);
This code Is meant to move Myself and mentioned users to selected Voice Channel it works perfectly fine when using message.mention.members.first() but can only handle one out of two of the mentioned users.
I was wondering if there was a fix for my current error or if there is another way I should be working this out?
Remember that,
message.mentions.members- Returns a GuildMember whereas
client.users.cache.get - Returns a User
You can only move/disconnect GuildMembers across VCs.
Therefore you can use message.mentions.members, which returns a Collection of all mentioned Users.
let channel = client.channels.cache.find(channel => channel.name === args[0]);
message.member.voice.setChannel(channel.id);
message.mentions.members.each(u => {
u.voice.setChannel(channel.id);
})
The problem can be, that the user is not in cache, so you must use GuildMemberManager#fetch(id). Problem is, that this function is async. The easiest solution is to make getUserFromMention and the functions where you use it async and use await.
I want to send a greeting message to an "welcome" text channel, whenever a new user joins the server (guild).
The problem I'm facing is that, when I find the wanted channel, I will receive the channel with the type GuildChannel.
Since GuildChannel has no send() function, I'm not able to send the message. But I can't find a way to find the TextChannel, so I'm stuck here.
How can I get to the TextChannel so that I'm able to use the send() message? Below the code I'm using by now:
// Get the log channel (change to your liking)
const logChannel = guild.channels.find(123456);
if (!logChannel) return;
// A real basic message with the information we need.
logChannel.send('Hello there!'); // Property 'send' does not exist on type 'GuildChannel'
I'm using version 11.3.0 of discord.js
Thanks to this GitHub issue I've found the solution to my problem.
I need to use a Type Guard to narrow down the correct type.
My code now is this:
// Get the log channel
const logChannel = member.guild.channels.find(channel => channel.id == 123456);
if (!logChannel) return;
// Using a type guard to narrow down the correct type
if (!((logChannel): logChannel is TextChannel => logChannel.type === 'text')(logChannel)) return;
logChannel.send(`Hello there! ${member} joined the server.`);
Maybe for latecomers who are still looking for an answer this worked for me
let channel = client.channels.get("channelid") as Discord.TextChannel;
channel.send("what you want to send to that channel");
You can use the GuildChannel#isText() method to type guard before invoking send.
Example:
if (channel.isText()) {
await channel.send('...');
}
Or:
if (!channel.isText()) return;
await channel.send('...');
Discord v14
const channel: TextChannel = client.channels.cache.get(channelId) as TextChannel;
channel.send('test')
If you have problems with cache, you can use
const channel: TextChannel = await client.channels.fetch(channel.channelId) as TextChannel;
I do this:
let channel = client.guilds.get('your-guild-id').channels.get('your-channel-id');
channel.send("it worked");
(client is the discord client). your code should work if you change find to get and put the channel id in some single quotes. Well, it works for me.
Maybe this can help you?
Code:
client.on('guildMemberAdd', member => {
let channel = member.guild.channels.find('name', 'welcome');
let memberavatar = member.user.avatarURL
if (!channel) return;
let embed = new Discord.RichEmbed()
.setColor('RANDOM')
.setThumbnail(memberavatar)
.addField(':bust_in_silhouette: | name : ', `${member}`)
.addField(':microphone2: | Welcome!', `Welcome to the server, ${member}`)
.addField(':id: | User :', "**[" + `${member.id}` + "]**")
.addField(':family_mwgb: | Your are the member', `${member.guild.memberCount}`)
.addField("Name", `<#` + `${member.id}` + `>`, true)
.addField('Server', `${member.guild.name}`, true )
.setFooter(`**${member.guild.name}**`)
.setTimestamp()
channel.sendEmbed(embed);
});