How do I get the user of a mentioned user in an option? discord.js v13 - javascript

I have a bot that's trying to kick a mentioned user in the slash command but when I mention a user in the "user" option it says User not found and gives an error of x is not a valid function (x is whatever I'm trying). I'm trying to find a valid function to actually define the user mentioned but can't seem to find one. Any help is appreciated since I am new to javascript and discord.js
const { SlashCommandBuilder, OptionType } = require('discord.js');
module.exports = {
data: new SlashCommandBuilder()
.setName('tkick')
.setDescription('Kicks the specified user by tag (Moderation)')
.addMentionableOption((option) =>
option
.setName('user')
.setDescription('The user to be kicked')
.setRequired(true),
),
async execute(interaction, client) {
if (!interaction.member.permissions.has(['KICK_MEMBERS']))
return interaction.reply(
'You do not have permission to use this command.',
);
// Get the user from the interaction options
const user = interaction.user;
if (!user) return interaction.reply('User not found.');
// Kick the user
await interaction.option.('user').kick(); // This is where I am having the issue
// Reply with the text
await interaction.reply({
content: 'User has been kicked.',
});
},
};
I tried looking at different questions I looked up but it's either in an older version where it isn't there or got removed. Discord.js v13 got released in December 2022 but I can only find posts before that.

interaction.option.('user').kick() is not a valid syntax and interaction.user is not a GuildMember, but a User object. To be able to kick someone, you need a GuildMember object which can be obtained by using the interaction.options.getMentionable method if you use addMentionableOption.
However, it accepts roles and users. If you don't want your bot to accept mentions of roles, which would make your life a bit more difficult, it's better to use the addUserOption instead of addMentionableOption. With addUserOption, you can get the GuildMember object by using the interaction.options.getMember method:
module.exports = {
data: new SlashCommandBuilder()
.setName('tkick')
.setDescription('Kicks the specified user by tag (Moderation)')
. addUserOption((option) =>
option
.setName('user')
.setDescription('The user to be kicked')
.setRequired(true),
),
async execute(interaction) {
if (!interaction.member.permissions.has(['KICK_MEMBERS']))
return interaction.reply(
'You do not have permission to use this command.',
);
try {
await interaction.options.getMember('user').kick();
interaction.reply('User has been kicked.');
} catch (err) {
console.error(error);
interaction.reply('⚠️ There was an error kicking the member');
}
},
};

Related

How can i make this discord.js v14 slash command not return "undefined" for each option?

The idea of this command is to add a user to the .txt file full of customers info so it can be used by other parts of the bot.
The problem is no matter what i put into the options that pop up here
Command Example
it will always return "undefined" for each option like so.
Example Reply
i think the issue is its not actually returning anything from the interaction when asking for that information inside the execute function. im not quite sure why though.
here is the code in question.
const { SlashCommandBuilder } = require('discord.js');
const fs = require('fs');
module.exports = {
data: new SlashCommandBuilder()
// command name
.setName('addfrozencustomer')
// command description
.setDescription('Add a frozen customer account/discord')
.addStringOption(option =>
option.setName('id')
.setDescription('The ID of the customer')
.setRequired(true))
.addStringOption(option =>
option.setName('username')
.setDescription('The username of the customer')
.setRequired(true))
.addStringOption(option =>
option.setName('email')
.setDescription('The email of the customer')
.setRequired(true)),
async execute(interaction) {
const { id, username, email } = interaction.options;
const data = `${id}:::${username}:::${email}`;
fs.appendFile('users/frozencustomers.txt', `${data}\n`, (error) => {
if (error) {
console.error(error);
return;
}
console.log('The data was successfully written to the file.');
});
interaction.channel.send(`Successfully added frozen customer:\n ID: ${id}\n User: ${username}\n Email: ${email}`);
}
};
Out of everything i have tried the code above is the closest iv come to getting this to work as intended.
You can't grab interaction options values directly from the interaction.options object, it has seperate methods to grab each type of value, in your case:
const
username = interaction.options.getString("username"),
id = interaction.options.getString("id"),
email = interaction.options.getString("email")
You can read more about this here: https://discordjs.guide/slash-commands/parsing-options.html#command-options

Change your nickname command discord.js v14

I'm trying to make a command that can change a user's nickname but I can’t make it work. I have tried to find solutions but I can't.
Here is my code:
const { SlashCommandBuilder, EmbedBuilder } = require("discord.js");
module.exports = {
data: new SlashCommandBuilder()
.setName("nickname")
.setDescription("Change your nickname")
.addStringOption(option =>
option.setName("nickname")
.setDescription("New Nickname")
.setRequired(true)
),
async execute(interaction) {
const { options } = interaction;
const nick = options.getString("nickname");
const member = interaction.author;
const embed = new EmbedBuilder()
.setDescription(`Succesfully changed your nickname to ${nick}`)
.setColor(0xFFFFFE)
.setTimestamp();
await member.setNickname(`${nick}`)
await interaction.reply({
embeds: [embed],
ephemeral: true
});
}
}
I think the problem is with this but I'm not sure
await member.setNickname(`${nick}`)
It's because interaction.author is undefined. You probably thought that it's like message.author but that's still a User, not a GuildMember and only members have the setNickname() method.
You should get the member instead of the user though. Try something like this:
const member = await interaction.guild.members.fetch(interaction.user.id)
You could also use options.getMember("nickname") if you used addUserOption() instead of addStringOption().
I was just making a similar command and ran into the same issue as you. I realized the member that I'm trying to change the nickname of, had another role assigned to them, which was higher than the role of the bot. Give this a look and let me know. Also, make sure you have GatewayIntentBits.Guilds andGatewayIntentBits.GuildMembers passed in your intents.

Getting "Missing Access" error in console

I'm working on an add role command in discord.js v13 and this is the error I am getting:
Error
const { MessageEmbed } = require("discord.js");
const Discord = require("discord.js")
const config = require("../../botconfig/config.json");
const ee = require("../../botconfig/embed.json");
const settings = require("../../botconfig/settings.json");
module.exports = {
name: "addrole",
category: "Utility",
permissions: ["MANAGE_ROLES"],
aliases: ["stl"],
cooldown: 5,
usage: "addrole <user> <role>",
description: "Add a role to a member",
run: async (client, message, args, plusArgs, cmdUser, text, prefix) => {
/**
* #param {Message} message
*/
if (!message.member.permissions.has("MANAGE_ROLES")) return message.channel.send("<a:mark_rejected:975425274487398480> **You are not allowed to use this command. You need `Manage Roles` permission to use the command.**")
const target = message.mentions.members.first();
if (!target) return message.channel.send(`<a:mark_rejected:975425274487398480> No member specified`);
const role = message.mentions.roles.first();
if (!role) return message.channel.send(`<a:mark_rejected:975425274487398480> No role specified`);
await target.roles.add(role)
message.channel.send(`<a:mark_accept:975425276521644102> ${target.user.username} has obtined a role`).catch(err => {
message.channel.send(`<a:mark_rejected:975425274487398480> I do not have access to this role`)
})
}
}
What your error means is that your bot doesn't have permissions to give a role to a user. It might be trying to add a role which has a higher position than the bot's own role. One way to stop the error is to give the bot the highest position. The bot will also require the MANAGE_ROLES permission in the Discord Developers page to successfully add roles in the first place. If you want to learn more about role permissions, I suggest you go here => Roles and Permissions. Also, when you are using .catch() at the end, all it is checking for is if the message.channel.send() at the end worked and if not, then send a message to channel telling that the bot was not able to add the role. Instead you need to use .then() after adding the role and then use .catch() to catch the error. Then, your code might look like this:
target.roles.add(role).then(member => {
message.channel.send(`<a:mark_accept:975425276521644102> ${target.user.username} has obtined a role`)
}).catch(err => {
message.channel.send(`<a:mark_rejected:975425274487398480> I do not have access to this role`)
})

Discord.js mod bot ban command not working

My discord bot's ban command isn't working and is currently giving me this error. My rols id is 853527575317708820
I don't know what I am doing wrong so please help me out
Here is the command :
Server is ready.
TigerShark Community#3557 Has logged in
(node:204) UnhandledPromiseRejectiontarning: DiscordAPTError: T
AEE RS
user_id: Value "<#!856413967595012127>" is not snowflake.
at RequestHandler.execute (/home/Tunner/TSC/node_modules/di
scoxd. js/src/rest/RequestHandler. js:154:13)
at processTicksAndRejections (internal/process/task
§5:97:5) :!
at async RequestHandler.push (/home/zunner/TSC/node
/discord. js/s1c/rest/RequestHandler. js:39:14)
Here is my code :
module.exports = {
name: 'ban',
description: "Used to ban members from a server",
async execute(client, message, args, Discord) {
if (!(message.member.roles.cache.some(r => r.id === "853527575317708820"))) return
let reason;
const user = await client.users.fetch(args[0])
if (!args[1])
{
reason = "Not specified"
} else {
reason = args[1]
}
const embed = new Discord.MessageEmbed()
.setTitle(`${user.username} was banned!`)
.setDescription(`${user.username} was banned by ${message.author.username} for: ${reason}`)
.setColor("#f0db4f")
.setFooter("Ban Command")
.setTimestamp()
message.channel.send(embed)
message.guild.members.ban(user)
}
}
Your command has few issues in it.
The first being that it does not allow banning users with command if the user is mentioned, it only allows banning by user ID. To fix that simply do:
const user = message.mentions.members.first() || await client.users.fetch(args[0])
You should also add check if the user is found, so right after you declare value for user
const user = message.mentions.members.first() || await client.users.fetch(args[0])
if(!user) return message.reply(`No user found`);
Now if you allow banning both mentions and user IDs there might be a different user value. So I recommend editing your embed aswell to something like:
const embed = new Discord.MessageEmbed()
.setTitle(`${user.user.username} was banned!`)
.setDescription(`${user.user.username} was banned by ${message.author.username} for: ${reason}`)
.setColor("#f0db4f")
.setFooter("Ban Command")
.setTimestamp()
This should fix majority of your issues, I recommend that if something is undefined in future or you come across any bugs in your code. Do some debugging by sending messages to console console.log(variable) or console.log("This works?")
if you are using discord.js v12 you can do what the other answer said and get the user by mention message.mentions.members.first() but if you are using v13 that wont work anymore
the reason its giving that error is because you need to fetch the user by their id alone, so you can do this client.users.fetch(args[0].replace('<#!', '').replace('>', '')) to remove the <#! and > (mention prefix) from it.

.joinedAt proprety always returning undefined in discord.js

im trying to make a userinfo command right now on my discord bot. one of the fields is the time that the user joined the server.
heres my code
module.exports.run = async (Client, msg, args, UserDataBase, messages, commands_ran) => {
let user = msg.guild.member(msg.mentions.users.first() || msg.guild.members.get(args[0]))
if(!user) {
user = msg.author
}else {
user = user.user
}
const embed = new Discord.RichEmbed()
.setTitle('**User info**')
.setThumbnail(user.avatarURL)
.addField('Name:', user.username,true)
.addField('Tag:', `#${user.discriminator}`,true)
.addField('Date Joined:', user.createdAt)
.addField('Joined Server:', user.joinedAt)
msg.channel.send(embed)
}
it always returns Undefined in the final product
User objects don't have a joinedAt property because a User is not specific to any server. The representation of a user in a server is a GuildMember, which is what you're getting in the first line of your function.
You could just remove the part that forces it to be a User object and your code should work due to discord.js adding getters for all User properties on the GuildMember.
module.exports.run = async (Client, msg, args, UserDataBase, messages, commands_ran) => {
let user = msg.guild.member(msg.mentions.users.first() || msg.guild.members.get(args[0]))
const embed = new Discord.RichEmbed()
.setTitle('**User info**')
.setThumbnail(user.avatarURL)
.addField('Name:', user.username,true)
.addField('Tag:', `#${user.discriminator}`,true)
.addField('Date Joined:', user.createdAt)
.addField('Joined Server:', user.joinedAt)
msg.channel.send(embed)
}
user doesn't have any joinedAt property, so you will need to use GuildMember.
This can be obtained by member = msg.guild.member(user)
and then .addField('Joined at:' member.joinedAt)

Categories

Resources