Permission Error Nickname Change Command discord js - discord.js

There is no permission error when using code a, but there is a permission error whenever using code b. Is there a solution?
module.exports = {
name: "NICK",
async execute(message, args, client) {
//A: const member = message.mentions.members.first();
//B: const member = await message.guild.members.cache.get(message.author.id)
console.log(message.author.id)
if (!member) return message.reply("target error");
const arguments = args.shift(1)
if (!arguments) return message.reply("name error");
try {
const arguments = args.shift(1)
member.setNickname(arguments);
}catch (error) {
console.error(error);
}
},
};
I currently have these intents
const { Client, GatewayIntentBits, Collection, MembershipScreeningFieldType, ClientUser, User, time, GuildChannel, GuildManager, MessageManager, GuildMemberManager, GuildBanManager, GuildBan, GuildStickerManager, PermissionsBitField, PermissionOverwriteManager, MessageFlagsBitField, GuildMemberRoleManager, gu } = require('discord.js');
const { record } = require('../config.json');
const client = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMessages, GatewayIntentBits.GuildMessageReactions, GatewayIntentBits.GuildVoiceStates, GatewayIntentBits.DirectMessages, GatewayIntentBits.MessageContent, GatewayIntentBits.Guilds, GatewayIntentBits.GuildMembers, GatewayIntentBits.GuildBans] });

Checking code B I could say a few things:
You don't need to await a cache.get() call;
If you are the owner of the guild, then the bot needs to have a role above your highest role to change your nickname.

Related

This code runs without errors, but cannot add anyone to any roles

const { Client, Intents } = require('discord.js');
const { GoogleSpreadsheet } = require('google-spreadsheet');
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MEMBERS, Intents.FLAGS.GUILD_MESSAGES] });
const PREFIX = '!';
// Specify your credentials here
const creds = {
client_email: 'myclient',
private_key: 'myprivatekey',
};
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
});
client.on('message', async (message) => {
if (!message.content.startsWith(PREFIX) || message.author.bot) return;
const args = message.content.slice(PREFIX.length).trim().split(/ +/);
const command = args.shift().toLowerCase();
if (command === 'assignrole') {
if (!message.member.permissions.has('MANAGE_ROLES')) {
console.error('Error: User does not have the ManageRole permission');
message.reply('You do not have permission to use this command');
return;
}
const sheetId = args[0];
if (!sheetId) {
console.error('Error: Missing spreadsheet ID in command');
message.reply('Please provide a valid spreadsheet ID');
return;
}
const doc = new GoogleSpreadsheet(sheetId);
try {
await doc.useServiceAccountAuth(creds);
await doc.loadInfo(); // loads document properties and worksheets
const sheet = doc.sheetsByIndex[0]; // assumes sheet is first in document
const rows = await sheet.getRows();
const role = message.mentions.roles.first();
if (!role) {
console.error('Error: Missing role in command');
message.reply('Please provide a valid role');
return;
}
const roleName = role.name;
const successfulUsers = [];
for (let i = 0; i < rows.length; i++) {
const row = rows[i];
const user = message.guild.members.cache.find(
(member) => member.user.username === row._rawData[0]
);
if (user) {
try {
await user.roles.add(role);
row._rawData[1] = 'OK';
await row.save();
successfulUsers.push(user.user.username);
} catch (err) {
console.error(`Error: ${err.message}`);
}
}
}
message.channel.send(
`The role ${roleName} was added to the following users: ${successfulUsers.join(', ')}`
);
} catch (err) {
console.error(`Error: ${err.message}`);
message.reply('An error occurred while trying to access the spreadsheet');
}
}
});
client.login('mykey');
This is code was made to access a google sheet, reads column A and adds specified role to Users in column A, then adds 'OK' to column B to users who actually got the roleThis runs without errors, but cannot add anyone to any roles.
How can I change this so that it reads usernames on column A, and adds the role specified in the command?
I tried with a test code that exports whats in column A, and it seems to be reading column A.
I have checked permisions on discord side and the role I was trying to assign was under the bot role.

TypeError when trying to create a discord bot

I'm trying to build a discord bot that sends data to an airtable. This one sends user info when they join my server. I have the following code, but every time I try to run it, I get the following error:
TypeError: Cannot read properties of undefined (reading 'GUILDS')at Object.
This is the code:
const { Intents } = require('discord.js');
const Discord = require('discord.js');
const Airtable = require('airtable');
const client = new Discord.Client({
token: 'TOKEN_ID',
intents: [Intents.GUILDS, Intents.GUILD_MEMBERS]
});
Airtable.configure({ apiKey: 'API_KEY' });
const base = Airtable.base('BASE_ID');
client.on('guildMemberAdd', member => {
base('New Members').create({
'Username': member.user.username,
'Time Joined': new Date().toISOString()
}, function(err, record) {
if (err) {
console.error(err);
return;
}
console.log(`Added new record with ID ${record.getId()}`);
});
});
client.login();
Using Discord.js v14, the way to declare intents is as follows:
import { Client, GatewayIntentBits } from "discord.js";
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMembers
]
});
and your token should be put in client.login
client.login("your-bot-token");

How to send a direct message to a user using Discord.js? [duplicate]

I am trying to code a Discord bot for my personal server. I am using Discord.js and I have been following the discord.js guide.
I have now an event handler but when I add a file for another event, the code of this module is not executing. The event I am trying to trigger is the join of a new member in my server.
I have 2 important files : index.js which runs the corpse of my code and guildMemberAdd.js which is my event module for when a new member joins the server.
index.js:
// Require the necessary discord.js classes
const fs = require('node:fs');
const path = require('node:path');
const { Client, Collection, GatewayIntentBits } = require('discord.js');
const { token } = require('./config.json');
// Create a new client instance
const client = new Client({ intents: [GatewayIntentBits.Guilds] });
const eventsPath = path.join(__dirname, 'events');
const eventFiles = fs.readdirSync(eventsPath).filter(file => file.endsWith('.js'));
for (const file of eventFiles) {
const filePath = path.join(eventsPath, file);
const event = require(filePath);
if (event.once) {
client.once(event.name, (...args) => event.execute(...args));
} else {
client.on(event.name, (...args) => event.execute(...args));
}
}
// Log in to Discord with your client's token
client.login(token);
guildMemberAdd.js:
const { Events } = require('discord.js');
module.exports = {
name: Events.GuildMemberAdd,
async execute(member) {
console.log(member);
},
};
If you only have the GatewayIntentBits.Guilds intent enabled, the GuildMemberAdd event won't fire. You'll need to add the GatewayIntentBits.GuildMembers (and probably GatewayIntentBits.GuildPresences) too:
const { Client, GatewayIntentBits } = require('discord.js');
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMembers,
GatewayIntentBits.GuildPresences,
],
});
In discord.js v13, it should be:
const { Client, Intents } = require('discord.js');
const client = new Client({
intents: [
Intents.FLAGS.GUILDS,
Intents.FLAGS.GUILD_MEMBERS,
Intents.FLAGS.GUILD_PRESENCES,
],
});

discord.js v13 SlashCommandBuilder Reaction Roles

So i need help with the assign roles part - so if someone click on the reaction(emojiID) it should give the user who clicked on it the role(roleID)..
My code below sends the embed in the channel with my title & description and the emoji, but nothing happend if someone clicked on the emoji!
I use SlashCommandBuilder :
const { SlashCommandBuilder } = require('#discordjs/builders');
const fs = require('fs');
const { Client, Intents, MessageEmbed, MessageReaction } = require('discord.js');
const client = new Client({ intents: [
Intents.FLAGS.GUILDS,
Intents.FLAGS.GUILD_MEMBERS,
Intents.FLAGS.GUILD_MESSAGES,
Intents.FLAGS.GUILD_MESSAGE_REACTIONS,
Intents.FLAGS.DIRECT_MESSAGE_REACTIONS,
],
partials: ["MESSAGE", "CHANNEL", "REACTION"]
});
module.exports = {
data: new SlashCommandBuilder()
.setName('reaction')
.setDescription('Create reaction messages')
.addChannelOption((option) => {
return option
.setName('channel')
.setDescription('Choose a channel')
.setRequired(true)
})
...
async execute(interaction, client) {
const channelID = interaction.options.getChannel('channel');
const titleID = interaction.options.getString('title');
const descID = interaction.options.getString('desc');
const emojiID = interaction.options.getString('emoji');
const roleID = interaction.options.getRole('role');
let embed = new MessageEmbed()
.setTitle(titleID)
.setDescription(descID)
channelID.send({ embeds: [embed] }).then((sentMessage) => {
sentMessage.react(emojiID);
The code above is the working part - for the roles - I tried something like
async (reaction, user) => {
if(reaction.interaction.partial) await reaction.interaction.fetch();
if(reaction.partial) await reaction.fetch();
if(user.bot) return;
if(!reaction.interaction.guild) return;
if(reaction.interaction.channel.id === channelID) {
if(reaction.emoji.id === emojiID) {
reaction.interaction.guild.members.cache.get(user.id).roles.add(roleID)
}
}
};
but this is not working, please help :)

DM Specific User ID on Discord.js Bot

i'm new to coding bots and i need help on how to add a command on messaging a certain person a customized message. this is what i have so far. what should i do?
const Discord = require('discord.js');
const config = require("./Data/config.json")
const client = new Discord.Client({ intents: ["GUILDS", "GUILD_MESSAGES"] })
client.once('ready', () => {
console.log('Ready!');
});
client.login('TOKEN');
client.on('message', async message => {
if (message.author.bot) return;
let prefix = '??'
if (!message.content.startsWith(prefix)) return;
let args = message.content.slice(prefix.length).trim().split("/ +/g");
let msg = message.content.toLowerCase();
let cmd = args.shift().toLowerCase();
if (msg.startsWith(prefix + 'ping')) {
message.channel.send('pong');
}
if (msg.startsWith(prefix + 'hello')) {
message.channel.send('hewwo uwu');
}
});
To fetch a user by id, you can use bot.users.fetch()
To direct message a user, you can use User.send():
const user = await client.users.fetch(userId);
user.send("This is a DM!");
This simple function will easily resolve the user (you can provide a user object or user ID so it’s very helpful)
async function DMUser(resolvable, content, client) {
const user = client.users.resolve(resolvable)
return user.send(content)
}
//returns: message sent, or error
//usage: DMUser(UserResolvable, "content", client)
Related links:
UserManager.resolve
User.send
UserResolvable

Resources