This code runs without errors, but cannot add anyone to any roles - discord.js

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) || 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');
const sheetId = args[0];
if (!sheetId) {
console.error('Error: Missing spreadsheet ID in command');
message.reply('Please provide a valid spreadsheet ID');
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');
const roleName =;
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';
} catch (err) {
console.error(`Error: ${err.message}`);
`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');
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.


Permission Error Nickname Change Command 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(
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)
}catch (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.

Discord bot not coming online despite no error messages?

I have recently spent a long time making a discord ticket bot, and all of a sudden now, it isnt turning on. There are no error messages when I turn the bot on, and the webview says the bot is online. I am hosting on
Sorry for the long code, but any genius who could work this out would be greatly appreciated. Thanks in advance.
const fs = require('fs');
const client = new Discord.Client();
const prefix = '-'
client.commands = new Discord.Collection();
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
for (const file of commandFiles){
const command = require(`./commands/${file}`)
client.commands.set(, command);
client.on("ready", () => {
console.log('Bot ready!');
client.user.setActivity('-help', { type: "LISTENING"} ).catch(console.error)
client.on("message", async (message) => {
if ( return;
const filter = (m) => ===;
if (message.content === "-ticket") {
let channel =;
if (!channel) channel = await;
let embed = new Discord.MessageEmbed();
embed.setTitle('Open a Ticket')
embed.setDescription('Thank you for reaching out to us. If you have a question, please state it below so I can connect you to a member of our support team. If you a reporting a user, please describe your report in detail below.')
.awaitMessages(filter, {max: 1, time: 1000 * 300, errors: ['time'] })
.then ( async (collected) => {
const msg = collected.first();`
>>> ✅ Thank you for reaching out to us! I have created a case for your inquiry with out support team. Expect a reply soon!
❓ Your question: ${msg}
let claimEmbed = new Discord.MessageEmbed();
claimEmbed.setTitle('New Ticket')
New ticket created by ${}: ${msg}
React with ✅ to claim!
try {
let claimChannel = client.channels.cache.find(
(channel) => === 'general',
let claimMessage = await claimChannel.send(claimEmbed);
const handleReaction = (reaction, user) => {
if ( === '923956860682399806') {
const name = `ticket-${user.tag}`
.create(name, {
type: 'text',
}).then(channel => {
client.on('messageReactionAdd', (reaction, user) => {
const channelID = '858428421683675169'
if ( === channelID) {
handleReaction(reaction, user)
} catch (err) {
throw err;
.catch((err) => console.log(err));
Your problem could possibly be that you have not put any intents. Intents look like this:
const { Client } = require('discord.js');
const client = new Client({
intents: 46687,
You can always calculate your intents with this intents calculator:
Side note:
If you are using discord.js v14 you change client.on from message to messageCreate.

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', () => {
client.on('message', async message => {
if ( 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')) {'pong');
if (msg.startsWith(prefix + 'hello')) {'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:

Giving roles on discord

I'm making a discord murder mystery bot.
const Discord = require('discord.js');
const client = new Discord.Client();
client.on("message", (message) => {
msg = message.content.toLowerCase();
if ( {
mention = message.mentions.users.first();
if (msg.startsWith("kill")) {
if (mention == null) {
mention.send('you are dead');"now done");
client.login('my token');
What would I add to the code so after the person who was tagged got there role changed from alive to dead?
// First, make sure that you're in a guild
if (!message.guild) return;
// Get the guild member from the user
// You can also use message.mentions.members.first() (make sure that you check that
// the message was sent in a guild beforehand if you do so)
const member = message.guild.members.cache.get(;
// You can use the ID of the roles, or get the role by name. Example:
// const aliveRole = message.guild.roles.cache.find(r => === 'Alive');
const aliveRole = 'alive role ID here';
const deadRole = 'dead role ID here';
// You can also use try/catch with await if you make the listener and async
// function:
client.on("message", async (message) => {
// ...
try {
await Promise.all([
} catch (error) {
The Promise.all means that the promises for adding and removing the roles are started at the same time. A promise is an object that can resolve to a value or reject with an error, so the .catch(console.error) logs all errors. I recommend that you handle errors for message.delete(), mention.send('you are dead'), and"now done") as well.
For more information on member.roles.remove() and member.roles.add(), see the documentation for GuildMemberRoleManager.

How to transfer reaction to original message, discord.js

I am trying to make a suggestion feature for one of my bots. I have searched online but nothing really helps with it. The suggestion part is working but I want to add a feature where if i react to the message in the log channel it sends the reaction to the original message. Here is my code:
bot.on('message', message => {
if (message.content.startsWith("/suggest")){
message.reply(`Your response has been recorded.`)
var yes = message.content
const channel1 = bot.channels.cache.get('722590953017442335');
channel1.send(`${} suggests: ${yes.slice(9)}`)
if ( === '✅'){
const channel2 = bot.channels.cache.get('722595812462297139');'✅')
I am using v12 of node.
You can use the awaitReactions() function:
bot.on("message", (message) => {
if (message.content.startsWith("/suggest")) {
message.reply(`Your response has been recorded.`);
var yes = message.content;
.send(`${} suggests: ${yes.slice(9)}`)
.then(async (msg) => {
.awaitReactions((reaction) => === "✅", {
time: 15000,
.then((collected) => message.react("✅"))
Please read the official documentation at for v12 help. You ought to use the Client#messageReactionAdd event to track reactions - your code isn't too far off, however it is missing that key event. Please note that to track reactions you'll need persistent storage if you want the reactions to work after restart. Alternatively, you could try awaiting the reactions or using a reaction collector if only short term.
Try this instead:
const { Client } = require('discord.js');
const bot = new Client({ partials: ['REACTION', 'USER'] });
const prefix = '/';
const suggestionsCache = {};
bot.on('message', async message => {
if (!message.content.startsWith(prefix) || return;
const args = message.content.split(' '),
command = args.shift().slice(prefix.length);
if (command == 'suggest') {
const suggestion = args.join(' '),
suggestionMessage = `${} suggests: ${suggestion}`,
suggestionChannel = bot.channels.cache.get('722590953017442335'),
logChannel = bot.channels.cache.get('722595812462297139');
if (!suggestionChannel || !logChannel) return message.reply('Oops! Something went wrong.');
try {
const suggestionMessage = await suggestionChannel.send(suggestionMessage);
const logMessage = await logChannel.send(suggestionMessage);
suggestionsCache[] =; // Save the ID for later.
message.reply('Your response has been recorded.');
} catch {
message.reply('Oops! Something went wrong.');
bot.on('messageReactionAdd', async (reaction, user) => {
if (reaction.partial) {
try {
await reaction.fetch();
} catch {}
const messageID = suggestionsCache[];
if (!messageID || !== '✅') return; // If not found in cache, ignore and if the emoji isn't the check, ignore it.
try {
const channel = await client.channels.fetch('722590953017442335');
if (!channel) return;
const message = channel.messages.fetch(messageID);
if (!message) return; // Message deleted.
} catch {
Please note that I am new to v12 and normally use v11! The code above is not tested and may contain bugs as a result. Please feel free to edit/update the code.