i am trying to make a discord.js bot that adds a role to a user when they type: +rolename .
This is what I have come up with:
const { Client } = require("discord.js");
const { config } = require("dotenv");
const fs = require('fs');
const client = new Client({
partials: ['MESSAGE', 'CHANNEL', 'REACTION']
});
config({
path: __dirname + "/.env"
});
client.on("ready", () => {
console.log(`Hi, ${client.user.username} is now online!`);
client.user.setStatus('online');
client.user.setActivity('me getting developed', { type: "WATCHING"})
.then(() => console.log('bot status set'))
.catch(console.error);
});
client.on("message", (message) => {
if (message.content.startsWith("+")) {
var args = message.content.split(' ');
if (args.length == 1) {
console.log(`message is created -> ${message}`);
const { guild } = message;
var passrole = args[0];
var roleid = passrole.substring(1);
var role = message.guild.roles.cache.find((role) => {
return role.name == roleid;
});
console.log('role found')
var authoruser = message.author.id;
if (!role) {
message.reply('this role does not exist')
console.log('role does not exist')
return;
}
console.log(target)
authoruser.roles.add(role)
console.log("role added")
} else {
message.reply('invalid argument length passed')
return;
}
} else {
return;
}
});
client.login(process.env.TOKEN);
When running the code i get the following error:
TypeError: Cannot read property 'add' of undefined
This doesn't happen when I use this code and type +test #DiscordName#0001:
const { Client } = require("discord.js");
const { config } = require("dotenv");
const fs = require('fs');
const client = new Client({
partials: ['MESSAGE', 'CHANNEL', 'REACTION']
});
config({
path: __dirname + "/.env"
})
client.on("ready", () => {
console.log(`Hi, ${client.user.username} is now online!`);
client.user.setStatus('online');
client.user.setActivity('me getting developed', { type: "WATCHING"})
.then(presence => console.log('bot status set'))
.catch(console.error);
});
client.on("message", (message) => {
let target = message.mentions.members.first();
if (message.content.startsWith("+")) {
var args = message.content.split(' ');
if(args.length == 2){
console.log(`message is created -> ${message}`);
const { guild } = message;
var passrole = args[0]
var roleid = passrole.substring(1);
var role = message.guild.roles.cache.find((role) => {
return role.name == roleid;
})
console.log('role found')
if (!role) {
message.reply('role does not exist')
console.log('role does not exist')
return;
}
console.log(target)
target.roles.add(role)
console.log("role added")
} else {
message.reply('invalid argument length passed')
return;
}
} else {
return;
}
});
client.login(process.env.TOKEN);
My question is: How can I add the role to the message author.
Thanks in advance
The problem is that your authoruser is the users id (= string) not the member. You cannot add roles to users. Also if you get the role's id and not the name of the role you can add the role with the role's id.
client.on("message", message =>{
if (message.content.startsWith("+")) {
var args = message.content.split(' ');
if (args.length !== 1) {
message.reply('invalid argument count passed');
return;
}
if (!message.member ||!message.guild) {
message.reply('can only be used in guilds');
return;
}
console.log(`message is created -> ${message}`);
const { guild } = message;
var passrole = args[0];
var roleid = passrole.substring(1);
// If you get the role's id then you won't need this
var role = message.guild.roles.cache.find((role) => role.name == roleid);
if (!role) {
message.reply('this role does not exist');
console.log('role does not exist');
return;
}
console.log('role found');
console.log(target);
message.member.roles.add(role);
// If you get the role's id use this:
message.member.roles.add(roleid);
console.log('role added');
});
Related
I want to make an unban command, but I still get some errors along the way and I don't know what to do.
TypeError: message.member.hasPermissions is not a function that is my error that i get
Please help me. I am a beginner at discord.js and this is my unban.js code:
const Discord = require('discord.js');
const client = new Discord.Client();
const embed = new Discord.MessageEmbed()
.setColor('#0B15A3')
module.exports = {
name: 'unban',
description: "This unbans a user",
execute(message, args, client, Discord) {
if (message.member.hasPermissions("BAN_MEMBERS") ){
if (!isNaN(args[0])) {
const bannedMember = message.guild.members.cache.get(args[0]) // Get the `member` property instead to recall later.
var reason = args.slice(1).join(" ");
if(!reason) {
reason = "No reason given!"
}
if (bannedMember) {
bannedMember
message.guild.members.unban(bannedMember.id, reason)
.then(() => {
embed.setDescription(`Successfully unbanned **${bannedMember.user.tag}**`); // `user` is undefined.
message.channel.send(embed);
})
.catch(err => {
embed.setDescription('I was unable to unban the member');
message.channel.send(embed);
console.error(err);
});
} else {
embed.setDescription("That user isn't in this guild!");
message.channel.send(embed);
}
} else {
embed.setDescription("You need to provide an user ID to unban");
message.channel.send(embed);
}
} else {
embed.setDescription("You do not have `BAN_MEMBERS` permissions to unban this member");
message.channel.send(embed);
}
}
}
and this is my index.js code:
const Discord = require('discord.js');
const client = new Discord.Client({ partials: ["MESSAGE", "CHANNEL", "REACTION" ]});
const prefix = '-';
const fs = require('fs');
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(`${client.user.tag} is online!`);
client.user.setPresence({
status: 'online',
activity: {
name: "Prefix: -",
type: "PLAYING"
}
});
});
client.on('message', message =>{
if(!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ +/);
const command = args.shift().toLowerCase();
if(command === 'ping'){
client.commands.get('ping').execute(message, args);
} else if(command === 'invite'){
client.commands.get('invite').execute(message, args, Discord);
} else if(command === 'help'){
client.commands.get('help').execute(message, args, Discord);
} else if(command === 'clear'){
client.commands.get('clear').execute(message, args);
} else if(command === 'nuke'){
client.commands.get('nuke').execute(message, args, Discord);
} else if(command === 'supersecretrules'){
client.commands.get('supersecretrules').execute(message, args, Discord);
} else if(command === 'support'){
client.commands.get('support').execute(message, args, Discord);
} else if(command === 'kick'){
client.commands.get('kick').execute(message, args);
} else if(command === 'ban'){
client.commands.get('ban').execute(message, args);
} else if(command === 'unban'){
client.commands.get('unban').execute(message, args);
}
});
client.login('token');
Can you help me? Thanks in advance!
You made a typo mistake. It is hasPermission() and not hasPermissions():
const Discord = require('discord.js');
const client = new Discord.Client();
const embed = new Discord.MessageEmbed()
.setColor('#0B15A3')
module.exports = {
name: 'unban',
description: "This unbans a user",
execute(message, args, client, Discord) {
if (message.member.hasPermission("BAN_MEMBERS") ){
if (!isNaN(args[0])) {
const bannedMember = message.guild.members.cache.get(args[0]) // Get the `member` property instead to recall later.
var reason = args.slice(1).join(" ");
if(!reason) {
reason = "No reason given!"
}
if (bannedMember) {
bannedMember
message.guild.members.unban(bannedMember.id, reason)
.then(() => {
embed.setDescription(`Successfully unbanned **${bannedMember.user.tag}**`); // `user` is undefined.
message.channel.send(embed);
})
.catch(err => {
embed.setDescription('I was unable to unban the member');
message.channel.send(embed);
console.error(err);
});
} else {
embed.setDescription("That user isn't in this guild!");
message.channel.send(embed);
}
You have made a simple typography error. The correct function name is GuildMember#hasPermission.
Change:
message.member.hasPermissions("BAN_MEMBERS")
To:
message.member.hasPermission("BAN_MEMBERS")
i have a problem sending text from yaml. Saving text works but sending does not. Here's the code:
const { Message, MessageEmbed } = require("discord.js")
const { channel } = require('./kanal')
const db = require('quick.db')
module.exports = {
name: "reklama",
guildOnly: true,
description:
"Change guild prefix. If no arguments are passed it will display actuall guild prefix.",
usage: "[prefix]",
run(msg, args, guild) {
if (!guild) {
const guld = new MessageEmbed()
.setTitle("Błąd!")
.setColor("RED")
.setDescription("Tą komende można tylko wykonać na serwerze!")
.setThumbnail('https://emoji.gg/assets/emoji/3485-cancel.gif')
.setTimestamp()
.setFooter(`${msg.author.tag} (${msg.author.id})`, `${msg.author.displayAvatarURL({dynamic: true})}`)
msg.channel.send(guild)
}
const { settings } = client
const prefixArg = args[0]
if (!settings.get(guild.id)) {
settings.set(guild.id, { prefix: null })
}
if (!prefixArg) {
let Reklama = client.settings.get(guild.id).Reklama
let Kanal = client.settings.get(guild.id).Kanał
const embed = new MessageEmbed()
.setTitle(`Informacje o serwerze: ${msg.guild.name}`)
.addField("Treść reklamy:", Reklama)
.addField("Kanał do wysyłania reklam:", Kanal)
msg.channel.send(embed)
}
setInterval(() => {
Kanal.send(`${Reklama}`)
}, 1000)
},catch(e){
console.log(e)
}
}
Here is a part of command handler:
const args = msg.content.slice(length).trim().split(" ")
const cmdName = args.shift().toLowerCase()
const cmd =
client.commands.get(cmdName) ||
client.commands.find(
(cmd) => cmd.aliases && cmd.aliases.includes(cmdName),
)
try {
cmd.run(msg, args)
} catch (error) {
console.error(error)
}
})
}
The problem is that when I start the bot, it shows me such an error:
let Reklama = client.settings.get(guild.id).Reklama
^
TypeError: Cannot read property 'id' of undefined
The problem is you don't pass the guild variable to your run method. You call cmd.run(msg, args) but run accepts three parameters.
You can either pass the guild or get it from the msg like this:
module.exports = {
name: 'reklama',
guildOnly: true,
description:
'Change guild prefix. If no arguments are passed it will display actuall guild prefix.',
usage: '[prefix]',
run(msg, args) {
// destructure the guild the message was sent in
const { guild } = msg;
if (!guild) {
const embed = new MessageEmbed()
.setTitle('Błąd!')
.setColor('RED')
.setDescription('Tą komende można tylko wykonać na serwerze!')
.setThumbnail('https://emoji.gg/assets/emoji/3485-cancel.gif')
.setTimestamp()
.setFooter(
`${msg.author.tag} (${msg.author.id})`,
`${msg.author.displayAvatarURL({ dynamic: true })}`,
);
return msg.channel.send(embed);
}
const { settings } = client;
const prefixArg = args[0];
if (!settings.get(guild.id)) {
settings.set(guild.id, { prefix: null });
}
if (!prefixArg) {
let Reklama = client.settings.get(guild.id).Reklama;
let Kanal = client.settings.get(guild.id).Kanał;
const embed = new MessageEmbed()
.setTitle(`Informacje o serwerze: ${msg.guild.name}`)
.addField('Treść reklamy:', Reklama)
.addField('Kanał do wysyłania reklam:', Kanal);
msg.channel.send(embed);
}
setInterval(() => {
Kanal.send(`${Reklama}`);
}, 1000);
},
catch(e) {
console.log(e);
},
};
Why is reaction.message not defined? I have guild in other files and it work fine. Error: TypeError: Cannot read property 'guild' of undefined. And the error is here: message.guild.channels
module.exports = (client, Discord, chalk, message, args) => {
const channelId = '799339037306912808'
const getEmoji = (emojiName) =>
client.emojis.cache.find((emoji) => emoji.name === emojiName)
const emojis = {
golden_ticket: 'rules',
}
const handleReaction = (reaction, user, add) => {
if (user.id === '799652033509457940') {
return
}
const emoji = reaction._emoji.name
const { guild } = reaction.message
const userName = user.username
const userId = guild.members.cache.find((member) => member.id === user.id)
const categoryId = '802172599836213258';
if (add) {
reaction.users.remove(userId)
message.guild.channels
.create(`${userName}`, {
type: 'text',
permissionOverwrites: [
{
allow: 'VIEW_CHANNEL',
id: userId
}
],
})
.then((channel) => {
channel.setParent(categoryId)
})
} else {
return;
}
}
client.on('messageReactionAdd', (reaction, user) => {
if (reaction.message.channel.id === channelId) {
handleReaction(reaction, user, true)
}
})
}
can someone help me fix this error? It's causing me some critical damage.
const Discord = require('discord.js');
const config = require('./config.json');
const bot = new Discord.Client();
const cooldowns = new Discord.Collection();
const fs = require('fs');
bot.commands = new Discord.Collection();
fs.readdir('./commands/', (err, files) => {
if (err) console.log(err);
let jsfile = files.filter((f) => f.split('.').pop() === 'js');
if (jsfile.length <= 0) {
console.log('No Commands fonud!');
return;
}
jsfile.forEach((f, i) => {
let props = require(`./commands/${f}`);
console.log(`${f} loaded!`);
bot.commands.set(props.help.name, props);
});
fs.readdir('./events/', (error, f) => {
if (error) console.log(error);
console.log(`${f.length} Loading events...`);
f.forEach((f) => {
const events = require(`./events/${f}`);
const event = f.split('.')[0];
client.on(event, events.bind(null, client));
});
});
});
let statuses = ['By LeRegedit#1281', 'Prefix => !', 'V1.0', 'Coming Soon'];
bot.on('ready', () => {
console.log(bot.user.username + ' is online !');
setInterval(function() {
let status = statuses[Math.floor(Math.random() * statuses.length)];
bot.user.setPresence({ activity: { name: status }, status: 'online' });
}, 10000);
});
bot.on('message', async (message) => {
if (message.author.bot) return;
if (message.channel.type === 'dm') return;
let content = message.content.split(' ');
let command = content[0];
let args = content.slice(1);
let prefix = config.prefix;
let commandfile = bot.commands.get(command.slice(prefix.length));
if (commandfile) commandfile.run(bot, message, args);
if (!message.content.startsWith(prefix)) return;
});
bot.login(config.token);
Type Error: Cannot read property 'name' of undefined
I'm trying to create a discord bot that connects to a Roblox account that I made.
I'm trying to create a command that will shout a message in a group, but there's a problem at the login and I can't figure out how to fix the problem.
let roblox = require('noblox.js');
const { Client } = require("discord.js");
const { config } = require("dotenv");
const client = new Client({
disableEveryone: true
});
config({
path: __dirname + "/.env"
});
let prefix = process.env.PREFIX
let groupId = groupid;
client.on("ready", () => {
console.log("I'm Ready!");
function login() {
roblox.cookieLogin(process.env.COOKIE)
}
login()
.then(function () {
console.log(`Logged in to ${username}`);
})
.catch(function (error) {
console.log(`Login error: ${error}`);
});
client.on("message", async message => {
console.log(`${message.author.username} said: ${message.content}`);
if (message.author.bot) return;
if (message.content.indexOf(prefix) !== 0) return;
const args = message.content.slice(prefix.length).trim().split(/ +/g);
const command = args.shift().toLowerCase();
if (command === "shout") {
if (!args) {
return;
message.reply("You didn't specify a message to shout.")
}
const shoutMSG = args.join(" ");
roblox.shout(groupId, shoutMSG)
.then(function() {
console.log(`Shouted ${shoutMSG}`);
})
.catch(function(error) {
console.log(`Shout error: ${error}`)
});
}
})
client.login(process.env.TOKEN);
It gives me the error:
Shout error: Error: Shout failed, verify login, permissions, and message
At the first you don`t close you client.on('ready') state.
if (!args) {
return;
message.reply("You didn't specify a message to shout.")
}
This funcyion will never reply, because you use return, before reply.
Your groupId looks like undefined, because you declarate it let groupId = groupid;, so this is the one way, why got you got this error.
let roblox = require('noblox.js');
const { Client } = require("discord.js");
const { config } = require("dotenv");
const client = new Client({
disableEveryone: true
});
config({
path: __dirname + "/.env"
});
let prefix = process.env.PREFIX
let groupId = groupid;
client.on("ready", () => {
console.log("I'm Ready!");
})
function login() {
roblox.cookieLogin(process.env.COOKIE)
}
login()
.then(function () {
console.log(`Logged in to ${username}`);
})
.catch(function (error) {
console.log(`Login error: ${error}`);
});
client.on("message", async message => {
console.log(`${message.author.username} said: ${message.content}`);
if (message.author.bot) return;
if (message.content.indexOf(prefix) !== 0) return;
const args = message.content.slice(prefix.length).trim().split(/ +/g);
const command = args.shift().toLowerCase();
if (command === "shout") {
if (!args) return message.reply("You didn't specify a message to shout.")
const shoutMSG = args.join(" ");
roblox.shout(groupId, shoutMSG)
.then(function() {
console.log(`Shouted ${shoutMSG}`);
})
.catch(function(error) {
console.log(`Shout error: ${error}`)
});
}
})
client.login(process.env.TOKEN);