How to add role to user in discord? - discord

How can I add role to user in this case? I don't want to do this with roles.find.
Thanks for help!
My script:
const discord = require('discord.js');
const client = new discord.Client;
const prefix = "$"`;
client.on('message', function (message) {
if (!message.content.startsWith(prefix)) return
const args = message.content.slice(prefix.length).trim().split(/ +/g);
const command = args[0].toLowerCase();
if (command === 'add') {
let member = message.member.guild.member(args[1])
client.cache.get(member.id).roles.add("roleid");
client.login('token');

You can do it like this:
use args.shift() to get a command, so then you can use args as command arguments
const Discord = require('discord.js');
const client = new Discord.Client();
const prefix = '$';
client.on('message', function (message) {
if (!message.content.startsWith(prefix)) return;
let args = message.content.slice(prefix.length).trim().split(/ +/g);
let command = args.shift();
if (command === 'add') {
if (args.length === 0) return message.reply('pls mention a member or write a ID');
let member = message.mentions.members.first() || message.guild.members.cache.get(args[0]);
if (!member) return message.reply(`can't get a member ${args[0]}`);
member.roles
.add('ROLE ID')
.then(() => {
message.channel.send(`successfully add role to member ${member.user}`);
})
.catch((err) => {
message.channel.send(`Failed to add role to member`);
});
}
});
client.login('token');

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.

Discord.js v13 bot cannot send message

Here is my code
I tried to run it and when i run the command nothing shows up
can someone pls help me with this
const Discord = require("discord.js");
const bot = new Discord.Client({ intents: ["GUILDS", "GUILD_MESSAGES"] });
const token =
"MTAxNzgyMjQ1MjU1MTc5NDgxOA.GjO8F-.VWCMsDKV5_YdP1w6gnEME6Jucd7BN9OADesM4s";
const prefix = "lb!";
bot.on("ready", () => {
console.log("Your bot is now online");
});
bot.on("messagecreate", (message) => {
if (message.author.bot) return;
const args = message.content.slice(prefix.length).trim().split(/ +/g);
const command = args.shift().toLocaleLowerCase();
if (command === "hello") {
message.reply("Hi ${message.author}");
}
});
bot.login(token);
Message content is now a privileged intent. You may have to enable it for your bot in the Discord Developer Portal. You could (or should) also use interaction commands instead, so that you don't need that intent, as its purpose is to provide user privacy.
Hello Syed Faizan Ali Kazmi, Done Fix Your Code
// © Ahmed1Dev
const Discord = require("discord.js");
const bot = new Discord.Client({ intents: ["GUILDS", "GUILD_MESSAGES"] });
const token =
"MTAxNzgyMjQ1MjU1MTc5NDgxOA.GjO8F-.VWCMsDKV5_YdP1w6gnEME6Jucd7BN9OADesM4s";
const prefix = "lb!";
bot.on("ready", () => {
console.log("Your bot is now online");
});
bot.on("messagecreate", (message) => {
if (message.author.bot) return;
const args = message.content.slice(prefix.length).trim().split(/ +/g);
const command = args.shift().toLocaleLowerCase();
if (command === prefix + "hello") {
message.reply("Hi ${message.author}");
}
});
bot.login(token);
// © Ahmed1Dev
With Regards,
Ahmed1Dev
I rewrite the code. Hope this will work
const Discord = require("discord.js");
const bot = new Discord.Client({ intents: ["GUILDS", "GUILD_MESSAGES"] });
const token = "never post your bot token online";
const prefix = "lb!";
bot.on("ready", () => {
console.log("Your bot is now online");
});
bot.on("messageCreate", (message) => {
if (message.author.bot) return;
const args = message.content.slice(prefix.length).trim().split(/ +/g);
const command = args.shift().toLowerCase();
if (command === "hello") {
message.reply(`Hi ${message.author}`);
}
});
bot.login(token);
Also, if you didn't tick Message Content Intent, then go tick it in Discord Developer Portal

discord js v13 message reply don't work (prefix)

I was making discord bot that reply the user word with prefix.
example the user said !Hello the bot will reply with Hello
The error was
(node:11208) DeprecationWarning: The message event is deprecated. Use messageCreate instead (Use node --trace-deprecation ... to show where the warning was created)
So I changed the code message to messageCreate but the bot didn't reply either and have no error in the console log what should I change the code of my script?
this is the source code
prefix is ! (It is in the config.json)
index.js
const {Client,Intents,Collection} = require("discord.js");
const client = new Client ({intents:[Intents.FLAGS.GUILDS,Intents.FLAGS.GUILD_MESSAGES,Intents.FLAGS.GUILD_MEMBERS]})
const fs = require("fs");
const { token, prefix } = require("./config.json");
client.commands = new Collection();
const commandFiles = fs.readdirSync("./commands").filter((file) => file.endsWith(".js"));
var data = []
for(const file of commandFiles) {
const command = require(`./commands/${file}`);
client.commands.set(command.name, command);
data.push({name:command.name,description:command.description,options:command.options});
}
client.once('ready', async () =>{
console.log(`Logged in as ${client.user.tag}`)
// await client.guilds.cache.get('874178319434801192')?.commands.set(data)
setInterval(() => {
const statuses = [
'mimc!',
'wtf',
'prefix = !'
]
const status = statuses[Math.floor(Math.random()*statuses.length)]
client.user.setActivity(status, {type: "PLAYING"})
}, 10000)
});
client.on("messageCreate", (message) =>{
if(!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).trim().split(/ +/);
const command = args.shift();
if(!client.commands.has(command)) return;
try{
client.commands.get(command).execute(message, args);
}
catch(error){
console.error(error);
}
});
client.login(token)
Hello.js (in the folder of commands)
module.exports = {
name: "Hello",
description: "Say Hi",
execute(message) {
return message.channel.send(`${message.author}, Hello.`)
},
};
The code of index.js (or main file) goes by:
const {Client, Intents, MessageEmbed, Presence, Collection, Interaction}= require ('discord.js')
const client = new Client({intents:[Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES]})
const TOKEN = ''// get your TOKEN!
const PREFIX = '!'
const fs = require('fs')
client.commands = new 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);
}
client.on('ready', ()=> {
console.log('🕐 I am online!!')
client.user.setActivity('A GAME ', {type: ('PLAYING')})
client.user.setPresence({
status: 'Online'
})
})
client.on('message', message => {
if(!message.content.startsWith(PREFIX)|| message.author.bot) return
const arg = message.content.slice(PREFIX.length).split(/ +/)
const command= arg.shift().toLowerCase()
if (command === 'ping'){
client.commands.get('ping').execute(message,arg)
}
})
client.login(TOKEN)
After making a folder commands, add a new .js file, and name it as ping.js
The code for ping.js goes by -
module.exports={
name:'ping',
execute(message, arg){
message.reply('hello!!')
}
}

Discord.js - Discord bot stopped responding to commands

I was trying to add some new features to my bot, and it didn't end up working. So I removed the new code, and now it won't respond to any commands. It's still online but as I said earlier, it's completely unresponsive. I've looked through the code and I can't find the issue. I'm still new to coding bots so I'm probably missing something.
Here's my main code file:
const fs = require('fs');
const Discord = require('discord.js');
const { prefix, token } = require('./config.json');
const client = new Discord.Client();
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);
}
client.once('ready', () => {
console.log('Ready!');
});
client.on('message', message => {
console.log(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 (!client.commands.has(command)) return;
try {
client.commands.get(command).execute(message, args);
} catch (error) {
console.error(error);
message.reply('there was an error trying to execute that command!');
}
});
client.login(token);
And here's a command file:
function pickOneFrom(array) {
function pickOneFrom(array) {
return array[Math.floor(Math.random() * array.length)];
}
module.exports = {
name: 'throw',
description: 'this is a throw command!',
execute(message, args) {
const responses = ['a apple', 'a melon', 'a potato', 'a snowball', 'a spanner', 'a computer'];
message.channel.send(
`${message.author} threw ${pickOneFrom(responses)} at ${
message.mentions.users.first() ?? 'everyone'
}!`,
);
},
};```
After looking your code I see that you didn't import fs file system to reading commands files to import so you should add it into your code
const fs = require('fs');
const Discord = require('discord.js');
const { prefix, token } = require('./config.json');
const client = new Discord.Client();
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);
}
client.once('ready', () => {
console.log('Ready!');
});
client.on('message', 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 (!client.commands.has(command)) return;
try {
client.commands.get(command).execute(message, args);
} catch (error) {
console.error(error);
message.reply('there was an error trying to execute that command!');
}
});
client.login(token);
const fs = require('fs');
const Discord = require('discord.js');
const { prefix, token } = require('./config.json');
const client = new Discord.Client();
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);
}
client.once('ready', () => {
console.log('Ready!');
});
client.on('message', 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 (!client.commands.has(command)) return;
try {
client.commands.get(command).execute(client , message , args);
} catch (error) {
console.error(error);
message.reply('there was an error trying to execute that command!');
}
});
client.login(token);
You forgot to add client at client.commands.get(command).execute(message , args)

How to give user role by user id? I want to type user id in command (arguments)

How to give user role by user id?
I want to type user id in command.
E.g:
$add userid
I try a lot but I don't know how to do this
My script (not working):
const discord = require('discord.js');
const client = new discord.Client;
const prefix = "$";
client.on('message', function(message) {
if (!message.content.startsWith(prefix)) {return}
const args = message.content.slice(prefix.length).trim().split(/ +/g);
const command = args.shift().toLowerCase();
if(command === 'add') {
let member = guild.client.id();
if (member) {
var role= member.guild.roles.cache.find(role => role.name === "newrole");
member.addRole(role);
}
}
})
client.login('token');
Some of your code didn't really make much sense so I fixed it and got a version that should work for what you want.
const discord = require('discord.js');
const client = new discord.Client;
const prefix = "$";
client.on('message', function(message) {
if (!message.content.startsWith(prefix)) return
const args = message.content.slice(prefix.length).trim().split(/ +/g);
const command = args[0].toLowerCase();
if(command === 'add') {
let member = message.member.guild.member(args[1])
if (member) {
var role = message.member.guild.roles.cache.find(role => role.name === "newrole");
message.guild.member(args[1]).roles.add(role)
}
}
})
client.login('token');
Defining user might be useful for you so
let user = message.mentions.users.first();
And instead member.addRole(role);
Try using user.id.addRole(role);
Not sure if it will work for you

Resources