Change your nickname command discord.js v14 - javascript

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.

Related

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

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');
}
},
};

How to .deferReply to specified channel?

How can I have it so that the bot sends a message to a specific channel, while using .deferReply and .editReply? Currently, I'm getting an error saying that suggestionChannel.deferReply is not a function. Here's my code:
const { SlashCommandBuilder } = require("#discordjs/builders");
const { MessageEmbed } = require("discord.js");
module.exports = {
data: new SlashCommandBuilder()
.setName("suggest")
.setDescription("Send your suggestion to the specified channel")
.addStringOption((option) =>
option
.setName("suggestion")
.setDescription("Your suggestion")
.setRequired(true)
),
async execute(interaction, client) {
var suggestionChannelID = "900982140504793109";
var suggestionChannel = client.channels.cache.get(suggestionChannelID);
const embed = new MessageEmbed()
.setColor("#0099ff")
.setTitle(`New suggestion by ${interaction.member.displayName}`)
.setDescription(`${interaction.options.getString("suggestion")}`);
await suggestionChannel.deferReply();
await suggestionChannel
.editReply({
embeds: [embed],
})
.then(function (interaction) {
interaction.react(`👍`).then(interaction.react(`👎`));
});
},
};
How can I have it so that the bot sends a message to a specific
channel, while using .deferReply and .editReply?
Well, the short answer is; you can't. But you can do this:
As the error already says, deferReply() is not a method of the TextBasedChannels class, defined by your suggestionChannel.
Instead, try sending a message to the channel instead of replying. Replies can only be executed in the interaction's channel:
var suggestionChannelID = "900982140504793109";
var suggestionChannel = client.channels.cache.get(suggestionChannelID);
const embed = new MessageEmbed()
.setColor("#0099ff")
.setTitle(`New suggestion by ${interaction.member.displayName}`)
.setDescription(`${interaction.options.getString("suggestion")}`);
// use this instead
await suggestionChannel.send({
embeds: [embed],
});
P.S side note, deferReply() starts a 15-minute timer before the interaction expires and triggers that 'x is thinking...' text to appear when the client is calculating stuff, so try to call it as soon as possible. By default, interactions expire after 3 seconds, so if your bot fails to finish whatever it needs to accomplish within that timeframe, that interaction will fail.

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.

invite Created event

so I'm making a Discord Bot, with auto logging capabilities, until now I managed due to do most of the code, these include the command for setting a mod-log channel and the event code, here's the code for the command:
let db = require(`quick.db`)
module.exports = {
name: "modlog",
aliases: ["modlogs", "log", "logs"],
description: "Change the modlogs channel of the current server",
permission: "MANAGE_CHANNELS",
usage: "modlog #[channel_name]",
run: async (client, message, args) => {
if(!message.member.hasPermission(`MANAGE_CHANNELS`)) {
return message.channel.send(`:x: You do not have permission to use this command!`)
} else {
let channel = message.mentions.channels.first();
if(!channel) return message.channel.send(`:x: Please specify a channel to make it as the modlogs!`)
await db.set(`modlog_${message.guild.id}`, channel)
message.channel.send(`Set **${channel}** as the server's modlog channel!`)
}
}
}
And the inviteCreate event:
client.on("inviteCreate", async invite => {
const log = client.channels.cache.get(`${`modlog_${message.guild.id}`}`)
let inviteCreated = new Discord.MessageEmbed()
log.send(`An invite has been created on this server!`)
})
The issue is that since the inviteCreate event only accepts one parameter (I think that's what they are called) which is invite, there is no message parameter, so message becomes undefined, does anyone have a solution?
Thanks!
You don't need message in this case. See the documentation of invite.
Your message.member can be replaced with invite.inviter
Your message.channel can be replaced with invite.channel
Your message.guild can be replaced with invite.guild
Invites also have a guild property, that's the guild the invite is for, so you can use that instead of the message.guild:
client.on('inviteCreate', async (invite) => {
const log = client.channels.cache.get(`${`modlog_${invite.guild.id}`}`);
let inviteCreated = new Discord.MessageEmbed();
log.send(`An invite has been created on this server!`);
});

How to log into the ban section of discord using discord.js v12?

I'm working on my ban command and it's fully functional, but I was wondering, how I would log the ban reason into the ban section of discord (example in the attachment)? My code looks like this:
const { DiscordAPIError } = require("discord.js");
const Discord = require('discord.js');
module.exports = {
name: 'ban',
description: "Mentioned user will be banned",
execute(message, args){
if (!message.member.hasPermission("BAN_MEMBERS")) return message.channel.send("Invalid Permissions")
let User = message.guild.member(message.mentions.members.first()) || message.guild.members.cache.get(args[0])
if (!User) return message.channel.send("Invalid User")
if (User.hasPermission("BAN_MEMBERS")) return message.reply("Invalid Permissions a")
let banReason = args.join(" ").slice(22);
if (!banReason) {
banReason = "None"
}
console.log(`USER = ${User}`)
User.ban
console.log(`Ban reason = ${banReason}`)
var UserID = User.id
console.log(`USER ID = ${UserID}`)
}
}
Any help? Thanks :)
It's actually quite easy, just add ({reason: banReason}) after the User.ban part, making it:
User.ban({reason: banReason})
That should log it there properly :)
You can use the reason property of the options parameter in the GuildMember.ban() method:
User.ban({ reason: 'real life danger' })
.then(member => console.log(`${member.name} was banned.`))
.catch(console.error)
Also, in your code, there's no reason for using the Guild.member() method when defining User. Guild.member(user) is used to turn a User object into a GuildMember object.
However, MessageMentions.members.first() already returns a GuildMember object, making it obsolete.

Categories

Resources