I want to know the code that targets the person who gave the command - discord.js

I want to know the code that targets the person who gave the command instead 'message.mentions.members.first();'
I want to create a way to change my nickname by typing a command, but I always have to do an mention
The code consists of this configuration.
module.exports = {
name: "nick",
async execute(message, args, client) { const member = message.mentions.members.first();
if (!member) return message.reply("Please specify a member!");
const arguments = args.shift(2)
if (!arguments) return message.reply("Please specify a nickname!");
try {
const arguments = args.shift(2) member.setNickname(arguments); }catch (error) { console.error(error);
} }, }

If message is the message sent by the user invoking the bot command, you can access the user that sent that message using the .author property on the Message.

Well if you want to get member of the guild (server) use message.member or if you want the user then message.author or message.member.user. To change the nickname you would want to use message.member.setNickname(arguments)

Related

TypeError: Cannot read property 'id' of undefined | Discord.js

Aim: To ban every time a user is caught on the audit log attempting to create a channel
Code:
// Channel Create
client.on("channelCreate", async (channel) => {
const FetchingLogs = await client.guilds.cache.get(channel.guild.id).fetchAuditLogs({
limit: 1,
type: "CHANNEL_CREATE",
})
const ChannelLog = FetchingLogs.entries.first();
if (!ChannelLog) {
return console.log(red(`CHANNEL: ${channel.id} was created.`));
}
const { executor, target, createdAt } = ChannelLog;
if (target.id === channel.id) {
console.log(greenBright(`${channel.id} got created, by ${executor.tag}`));
} else if (target.id === executor.id) {
return
}
if (executor.id !== client.user.id) {
channel.guild.member(executor.id).ban({
reason: `Unauthorised Channel Created`
}).then(channel.guild.owner.send(`**Unauthorised Channel Created By:** ${executor.tag} \n**Channel ID:** ${channel.id} \n**Time:** ${createdAt.toDateString()} \n**Sentence:** Ban.`)).catch();
}
});
Result:
It bans the user successfully but still throws an error.
Error:
TypeError: Cannot read property 'id' of undefined
Code: Error Specified | Referring to channel.guild.id
const FetchingLogs = await client.guilds.cache.get(channel.guild.id).fetchAuditLogs({
limit: 1,
type: "CHANNEL_CREATE",
})
I'm guessing the reason for this is that the parameter ,channel, type is DMChannel and not GuildChannel
Is there any way to fix this or be able to change the parameter type to GuildChannel??? I've checked the Docs and I can't seem to find anything that indicates this is possible. Any help is appreciated ;)
Your assumption of why this error is occurring is correct. The channelCreate event does indeed handle the creation of both GuildChannel and DMChannel, and your code sends the guild owner a DM after banning the user. That's why the ban works but you get an error afterwards; because the DM creates a DMChannel with the owner, triggering the event handler again but with channel.guild being undefined since DMs do not have guilds.
So let me state the problem again. You are getting the error Cannot read property 'id' of undefined which you've figured out means channel.guild is undefined. You don't want the error to occur, so you don't want channel.guild to be undefined. But in your question you're asking:
Is there any way to fix this or be able to change the parameter type to GuildChannel???
That's not the approach you want to take. Doing that would mean users would get banned for DMing your bot because it would trigger your channelCreate event handler; plus, the bot would try to ban the guild owner since it sends the owner a DM. And you only want to ban users for creating channels in the guild.
When we put the problem that way, the solution is simple: check if the channel is a DMChannel, and discontinue if it is. Only allow users to get banned for creating a GuildChannel. So how do you do that? Well, as you've seen from your error already, channel.guild is undefined when the channel is a DMChannel. So simply check for this condition, and return if it is the case. Here's an example:
// Channel Create
client.on("channelCreate", async (channel) => {
if (!channel.guild) return; //<- added this
const FetchingLogs = await client.guilds.cache.get(channel.guild.id).fetchAuditLogs({
limit: 1,
type: "CHANNEL_CREATE",
})
const ChannelLog = FetchingLogs.entries.first();
if (!ChannelLog) {
return console.log(red(`CHANNEL: ${channel.id} was created.`));
}
const { executor, target, createdAt } = ChannelLog;
if (target.id === channel.id) {
console.log(greenBright(`${channel.id} got created, by ${executor.tag}`));
} else if (target.id === executor.id) {
return
}
if (executor.id !== client.user.id) {
channel.guild.member(executor.id).ban({
reason: `Unauthorised Channel Created`
}).then(channel.guild.owner.send(`**Unauthorised Channel Created By:** ${executor.tag} \n**Channel ID:** ${channel.id} \n**Time:** ${createdAt.toDateString()} \n**Sentence:** Ban.`)).catch();
}
});
This prevents the error from occurring, prevents users from getting banned for DMing the bot, and prevents the guild owner from being infinitely DM'd (if the DMChannel were to be somehow converted into a GuildChannel, the bot would DM the owner after banning the user that created the channel, which would trigger the event again and ban the user again, and DM the owner again, in an infinite loop).

Always getting back an, "Internal Server Error," when trying to run ban command on my Discord bot

I have tried many different ways of formatting the code, however, whenever I add code so that I must provide a reasoning to ban someone, I am always given an Internal Server Error. Here is my code.
module.exports.run = async (client, message, args) => {
const member = message.mentions.members.first();
const reason = args.slice(1).join(" ")
if (!message.member.hasPermission("BAN_MEMBERS")) {
return message.reply("you lack sufficiant permissions to execute this command.");
} else if (member.hasPermission("ADMINISTRATOR")) {
message.reply("you cannot ban this member.")
}
member.ban(reason).then((member) => {
message.channel.send(`${member} has been banned.`);
});
I use a command handler, and all my other commands work fine.
first step: Define the user
let user = message.mentions.members.first() || message.guild.members.cache.get(args.join(' '));
Second step: Create embed message or normal message
const userbanned = new Discord.MessageEmbed()
.setColor('#FF0000')
.setAuthor('User Banned')
.setDescription(`**${user.user.username}#${user.user.discriminator}** is now banned from this server`)
.setFooter(`bot_name`);
Third step: Send message
user.send(`You were banned from **${message.guild.name}** by ${message.author.username}#${message.author.discriminator}`)
return user
.ban()
.then(() => message.channel.send(userbanned))
.catch(error => message.reply("ERROR"));
Try changing
member.ban().then((member) =>//
to
member.ban({reason : args.slice(1).join(' ')}).then((member) =>//

Discord.js - How do you move a user that reacts to an embed?

I am new to Discord js and I am trying to make my bot move all users that react to an embed into a certain voice channel. Currently, it takes whoever wrote the message and moves them to the specified voice channel.I tried many combinations of user.id, guild.member, etc. What would I put before the .setVoiceChannel? I am confused as to what message.member is other than the person that wrote the message. Thank you!
collector.on('collect', (reaction, user) => {
if (reaction.emoji.name == reactionControls.VOID) {
const channel = message.guild.channels.find('name', 'Void 1');
message.member.setVoiceChannel(channel);
}
});
message.member does refer to the user who execute the command, if you want the member who reacted you will have to convert user using <GuildMember>.fetchMember, the only issue now is that the collect event doesn't give the parameter of user in v11.5.1 so you will need to just use collector.users.last() to get the last reactor
collector.on('collect', async (reaction) => {
if (reaction.emoji.name == reactionControls.VOID) {
const channel = message.guild.channels.find('name', 'Void 1');
const user = collector.users.last();
const member = await message.guild.fetchMember(user);
member.setVoiceChannel(channel);
}
});

Discord.js How can I edit previous bot's message?

so I am trying to make a ROSTER command. The command is $roster add/remove #user RANK. This command basically should edit a previous bot's message (roster) and add a user to the roster to the RANK in the command... This is my code so far, but I haven't managed to make the roster message and the editing part of it and the RANK system. If someone could help that would be very amazing!
//ROOSTER COMMAND
client.on('message', async message => {
if (message.content.startsWith(prefix + "roster")) {
if (!message.member.hasPermission('ADMINISTRATOR')) return message.channel.send('You do not have that permission! :x:').then(message.react(':x:'))
const args = message.content.slice(prefix.length + 7).split(/ +/)
let uReply = args[0];
const user = message.mentions.members.first()
if(!uReply) message.channel.send("Please use `add` or `remove`.")
if(uReply === 'add') {
if(!user) return message.channel.send("Please make sure to provide which user you would like to add...")
message.channel.send(`you are adding **${user.displayName}** from the roster.`)
} else if(uReply === 'remove') {
if(!user) return message.channel.send("Please make sure to provide which user you would like to add...")
message.channel.send(`you are removing **${user.displayName}** from the roster.`)
}
}})
Sounds like the .edit() method is what you want.
Example from the docs:
// Update the content of a message
message.edit('This is my new content!')
.then(msg => console.log(`Updated the content of a message to ${msg.content}`))
.catch(console.error);
To edit your bots previous message, you need to have a reference of the message you want to edit. The returned reference is a promise so do not forget to use await keyword. you can then use .edit() function on the reference to update you msg.
const msgRef = await msg.channel.send("Hello");
msgRef.edit("Bye");

Add roles to users in specific guild through DM

When I try
message.member.roles.add('695699359634817094');
I get the following error:
TypeError: Cannot read property 'add' of undefined
Is there a specific way to add my guild ID and update their role to that specific server through DM?
My function works within the guild by calling the command, however, through DM it doesn't.
You could do this by using message.author.id to get the user's ID and then using guild.get(guild_ID).members.fetch(user_ID) to access the GuildMember of that user.
You also mentioned that you give users the ability to run that command either in DM or a text channel in your guild.
If that is the case I would suggest adding a check to see if the command is being sent to a text channel or dm channel.
if (message.channel.type === "dm") {
const member = await client.guilds.get(guild_ID).members.fetch(message.author.id);
member.roles.add(role_ID);
} else {
message.member.roles.add('695699359634817094');
}
Ignore the if statement if you intend on having the command only run from dm.
By using the info given from Syntle and tipakA this is the solution.
if (message.channel.type === "dm") {
client.guilds.get('[SeverId]').members.fetch(message.author.id).then(async () => {
await client.guilds.get('[ServerId]').members.fetch(message.author.id).then((memberid) => {
memberid.roles.add('[roleid]');
}).catch((err) => {
console.log("ERROR");
});
});
}
else
{
message.member.roles.add('[roleid]');
}

Resources