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) || 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.

Related

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(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.

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 repl.it
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.name, command);
}
require('./server.js')
client.on("ready", () => {
console.log('Bot ready!');
client.user.setActivity('-help', { type: "LISTENING"} ).catch(console.error)
})
client.on("message", async (message) => {
if (message.author.bot) return;
const filter = (m) => m.author.id === message.author.id;
if (message.content === "-ticket") {
let channel = message.author.dmChannel;
if (!channel) channel = await message.author.createDM();
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.')
embed.setColor('AQUA')
message.author.send(embed);
channel
.awaitMessages(filter, {max: 1, time: 1000 * 300, errors: ['time'] })
.then ( async (collected) => {
const msg = collected.first();
message.author.send(`
>>> ✅ 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')
claimEmbed.setDescription(`
New ticket created by ${message.author.tag}: ${msg}
React with ✅ to claim!
`)
claimEmbed.setColor('AQUA')
claimEmbed.setTimestamp()
try {
let claimChannel = client.channels.cache.find(
(channel) => channel.name === 'general',
);
let claimMessage = await claimChannel.send(claimEmbed);
claimMessage.react('✅');
const handleReaction = (reaction, user) => {
if (user.id === '923956860682399806') {
return;
}
const name = `ticket-${user.tag}`
claimMessage.guild.channels
.create(name, {
type: 'text',
}).then(channel => {
console.log(channel)
})
claimMessage.delete();
}
client.on('messageReactionAdd', (reaction, user) => {
const channelID = '858428421683675169'
if (reaction.message.channel.id === channelID) {
handleReaction(reaction, user)
}
})
} catch (err) {
throw err;
}
})
.catch((err) => console.log(err));
}
})
client.login(process.env['TOKEN'])
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: https://ziad87.net/intents/
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', () => {
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

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 (message.author.bot) {
return;
}
mention = message.mentions.users.first();
if (msg.startsWith("kill")) {
if (mention == null) {
return;
}
message.delete();
mention.send('you are dead');
message.channel.send("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(mention.id);
// You can use the ID of the roles, or get the role by name. Example:
// const aliveRole = message.guild.roles.cache.find(r => r.name === '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([
member.roles.remove(aliveRole),
member.roles.add(deadRole)
]);
} catch (error) {
console.error(error);
}
})
*/
Promise.all([
member.roles.remove(aliveRole),
member.roles.add(deadRole)
]).catch(console.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 message.channel.send("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(`${message.author} suggests: ${yes.slice(9)}`)
if (chanell1.reaction.emoji.name === '✅'){
const channel2 = bot.channels.cache.get('722595812462297139');
channell2.react.author.message('✅')
}
}
})
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;
bot.channels.cache
.get("722590953017442335")
.send(`${message.author} suggests: ${yes.slice(9)}`)
.then(async (msg) => {
msg
.awaitReactions((reaction) => reaction.emoji.name === "✅", {
time: 15000,
})
.then((collected) => message.react("✅"))
.catch(console.error);
});
}
});
Please read the official documentation at https://discord.js.org/#/docs/main/v12/general/welcome 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) || message.author.bot) return;
const args = message.content.split(' '),
command = args.shift().slice(prefix.length);
if (command == 'suggest') {
const suggestion = args.join(' '),
suggestionMessage = `${message.author} 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[logMessage.id] = suggestionMessage.id; // 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[reaction.message.id];
if (!messageID || reaction.emoji.name !== '✅') 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.
message.react('✅');
} catch {
return;
};
});
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.

Resources