hello guys iam trying to make self role and nickname change command but its not working i dont know where is the problem i earn the role but name not changing can someone tell me what is wrong on my code
client.on('message', (message,member )=> {
if (message.content.toLowerCase() === '*Test') {
if(!message.channel.guild) return;
message.member.addRole(message.guild.roles.find(role => role.name === "Test"));
let member = message.member; //message.guild.members.cache.get(user.id);
let nick = "[PRO] "
// message.guild.member(r=>r.setNickname(nick + r.user.username));
member.setNickname(nick + member.user.username);
}
});
To set Discord nickname. You can use message.member.setNickname("new member") .
as example :
if you want to create #setnick [nickname] and [nickname] is your args.
and you can use this example with role for member
client.on('message', async message => {
let messageArray = message.content.split(" ");
let args = messageArray.slice(1);
var argresult = message.content.split(` `).slice(1).join(' ');
if(message.channel.type === "dm" || message.author.bot) return;
if(message.content.toLowerCase().startsWith('#setnick')) {
if(!message.guild.me.hasPermission('MANAGE_NICKNAMES')) return message.reply('I dont have Permission to do this action.!');
try {
if(!args[0]) {
message.member.setNickname(message.author.username)
} else {
message.member.setNickname(argresult, "Member wants to change nickname")
}
} catch(error) {
return console.error('[ SET_NICKNAME ] Error')
}
}
})
Related
EDIT: ColinD solved my problem but now the message doesn't delete and I have no idea why the message wont delete because its worked for me before with bots
Code:
const discord = require('discord.js')
const newEmbed = require('embedcord')
const randomHex = require('random-hex')
module.exports = (client, message, options) => {
let links = require('./links.json')
let foundLink = false
let banReason = (options && options.banReason) || 'Sent a phishing link.'
let logs = (options && options.logs)
let member = message.mentions.members.first()
for(var i in links) {
if(message.content.toLowerCase().includes(links[i])) foundLink = true
}
if(foundLink) {
if(message.author.hasPermission('ADMINISTRATOR'))
return
message.delete()
member.ban({reason: banReason})
const embed = newEmbed(
'**Member Banned**',
`${randomHex.generate()}`,
`Member was banend for ${options.banReason}`
)
logs.send(embed)
}
}
Your return position might be preventing anything below if from running try changing this
if (foundLink) {
if (message.author.hasPermission('ADMINISTRATOR')) return;
const embed = newEmbed(
'**Member Banned**',
`${randomHex.generate()}`,
`Member was banend for ${options.banReason}`
);
message.delete();
member.ban({
reason: banReason
});
logs.send(embed);
}
Or this if you want if/else
if (foundLink) {
if (message.author.hasPermission('ADMINISTRATOR')) {
return;
} else {
const embed = newEmbed(
'**Member Banned**',
`${randomHex.generate()}`,
`Member was banend for ${options.banReason}`
);
message.delete();
member.ban({
reason: banReason
});
logs.send(embed);
}
}
EDIT: ColinD solved my problem but now the message doesn't delete and I have no idea why the message wont delete because its worked for me before with bots
foundLink variable is unnecessary, you can move your code inside the loop.
Use message.member.hasPermission() instead of message.author.hasPermission().
Example code for v12.5.3(Message Event):
client.on('message', (message) => {
if (message.author.bot) return; // Ignore bot messages
const { member, channel, guild } = message; // Get the message author, channel, and guild
if (!member || !channel || !guild) return; // Ignore messages without a member, channel or guild
const { links } = require('./links.json'); // Get links from json file
for (let i = 0; i < links.length; i++) { // Check if the message contains a link in the links.json file
if (message.content.toLowerCase().includes(links[i])) { // If the message contains a link
if (member.hasPermission('ADMINISTRATOR')) return; // If the member has the administrator permission, don't ban them
const banReason = 'Sent a phishing link'; // Reason for the ban
message.delete(); // Delete the message
guild.member(member).ban({ reason: banReason }); // Ban the member
channel.send(`${member.displayName} has been banned for sending a phishing link.`) // Send a message to the channel
break;
}
}
})
Tried to venture in to the realm of making discord bots. Followed along with a fairly simple tutorial, tweaking it along the way to fit what I was trying to make. The bot originally worked, but I went back in to add the "Mistake" command, and suddenly it's not working. I added in console.log pretty much everywhere, trying to figure out how far everything was getting.
When I start the bot, it will spit out the "Bot Online" log. When I input a command, it will spit out the "Commands" log, but it won't register the command at all. I've tried looking for any minor typos, missing brackets, etc... but I just can't seem to figure out what's gone wrong. I'm hoping that someone here can help! Thank you!
const Discord = require('discord.js');
const config = require('./config.json');
const client = new Discord.Client();
const SQLite = require('better-sqlite3');
const sql = new SQLite('./scores.sqlite');
client.on('ready', () => {
console.log('Bot Online');
const table = sql.prepare("SELECT count(*) FROM sqlite_master WHERE type='table' AND name = 'goals';").get();
if (!table['count(*)']) {
sql.prepare('CREATE TABLE goals (id TEXT PRIMARY KEY, user TEXT, guild TEXT, goals INTEGER);').run();
sql.prepare('CREATE UNIQUE INDEX idx_goals_id ON goals (id);').run();
sql.pragma('synchronous = 1');
sql.pragma('journal_mode = wal');
}
//Statements to get and set the goal data
client.getGoals = sql.prepare('SELECT * FROM goals WHERE user = ? AND guild = ?');
client.setGoals = sql.prepare('INSERT OR REPLACE INTO goals (id, user, guild, goals) VALUES (#id, #user, #guild, #goals);');
});
client.on('message', (message) => {
if (message.author.bot) return;
let goalTotal;
if (message.guild) {
goalTotal = client.getGoals.get(message.author.id, message.guild.id);
if (!goalTotal) {
goalTotal = {
id: `${message.guild.id}-${message.author.id}`,
user: message.author.id,
guild: message.guild.id,
goals: 0,
};
}
}
if (message.content.indexOf(config.prefix) !== 0) return;
const args = message.content.slice(config.prefix.length).trim().split(/ +/g);
const command = args.shift().toLowerCase();
console.log('Commands');
if (command === 'Goals') {
console.log('Goals');
return message.reply(`You Currently Have ${goalTotal.goals} Own Goals.`);
}
if (command === 'OwnGoal') {
console.log('Own Goal');
const user = message.mentions.users.first() || client.users.cache.get(args[0]);
if (!user) return message.reply('You must mention someone.');
let userscore = client.getGoals.get(user.id, message.guild.id);
if (!userscore) {
userscore = {
id: `${message.guild.id}-${user.id}`,
user: user.id,
guild: message.guild.id,
goals: 0,
};
}
userscore.goals++;
console.log({ userscore });
client.setGoals.run(userscore);
return message.channel.send(`${user.tag} has betrayed his team and now has a total of ${userscore.goals} own goals.`);
}
if (command === 'Mistake') {
console.log('Mistake');
const user = message.mentions.users.first() || client.users.cache.get(args[0]);
if (!user) return message.reply('You must mention someone.');
let userscore = client.getGoals.get(user.id, message.guild.id);
if (!userscore) {
return message.reply('This person has no Rocket Bot activity.');
}
if (userscore === 0) {
return message.reply('This player currently has no goals.');
}
if (userscore > 0) {
userscore.goals--;
}
console.log({ userscore });
client.setGoals.run(userscore);
return message.channel.send(`${user.tag} was falsely accused and now has a total of ${userscore.goals} own goals.`);
}
if (command === 'Leaderboard') {
console.log('Leaderboard');
const leaderboard = sql.prepare('SELECT * FROM goals WHERE guild = ? ORDER BY goals DESC;').all(message.guild.id);
const embed = new Discord.MessageEmbed()
.setTitle('Rocket Bot Leaderboard')
.setAuthor(client.user.username, client.user.avatarURL())
.setDescription('Total Goals Scored Against Own Team:')
.setFooter('Rocket Bot')
.setThumbnail('https://imgur.com/a/S9HN4bT')
.setColor('0099ff');
for (const data of leaderboard) {
embed.addFields({
name: client.users.cache.get(data.user).tag,
value: `${data.goals} goals`,
inline: true,
});
}
return message.channel.send({ embed });
}
if (command === 'RocketHelp') {
console.log('Help');
return message.reply(
'Rocket Bot Commands:' +
'\n' +
'!Goals - See How Many Goals You Have Scored Against Your Own Team' +
'\n' +
'!OwnGoal - Tag Another Player With # To Add One To Their Total' +
'\n' +
'!Mistake - Tag Another Player With # To Subtract One From Their Total' +
'\n' +
'!Leaderboard - Show The Current Leaderboard'
);
}
});
client.login(config.token);
You are improperly splitting the message content. You added g to the regex by accident.
Correct line:
const args = message.content.slice(config.prefix.length).trim().split(/ +/);
Because of improper args split, it could not find any command at all, hence no console log was invoked after Commands.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 2 years ago.
Improve this question
I have some code that detects when someone enters the command role and gives them the role with the name of the first argument passed to the command (args[0]). For example, the bot would try to detect something like !role nameOfTheRole, which would give the user the role with the name nameOfTheRole.
However, the code is not working and I'm not sure why. Here is what I have mnaged to get so far:
var cmdmap = {
role: gimmerole
}
function gimmerole(member, args, message) {
var memb = message.member() //<------- ERROR
const role = memb.guild.roles.find(r => r.name == args[0])
memb.roles.add(role)
}
client.on('message', (msg) => {
var cont = msg.content,
author = msg.member,
chan = msg.channel,
guild = msg.guild
if (author.id != client.user.id && cont.startsWith(config.prefix)) {
var invoke = cont.split(' ')[0].substr(config.prefix.length),
args = cont.split(' ').slice(1)
console.log(invoke, args)
if (invoke in cmdmap) {
cmdmap[invoke](msg, args)
}
}
})
I have made a few modifications to your code:
I changed the line function gimmerole(member, args, message) { to function gimmerole(message, args) {, as in the line cmdmap[invoke](msg, args);, you are calling it with the message object and the arguments, so the message was getting assigned to member instead and message would have been undefined.
I changed message.member() to message.member, as member is a property of message, not a method.
I also changed the code that parses the message and splits it into a command and arguments so that it's a lot cleaner.
Added a sanity check (if (!role) return console.log(`The role "${args[0]}" does not exist`);) to make the bot log to the console if the role does not exist.
Changed args[0] to args.join(' ') to enable roles with spaces to be specified.
var cmdmap = {
role: gimmerole
};
function gimmerole(message, args) {
const member = message.member;
const role = message.guild.roles.cache.find(r => r.name === args.join(' '));
if (!role) return console.log(`The role "${args.join(' ')}" does not exist`);
member.roles.add(role);
}
client.on('message', (msg) => {
var cont = msg.content,
author = msg.member,
chan = msg.channel,
guild = msg.guild;
if (author.id !== client.user.id && cont.startsWith(config.prefix)) {
const [invoke, ...args] = cont.slice(config.prefix.length).trim().split(' ');
console.log(invoke, args);
if (invoke in cmdmap) {
cmdmap[invoke](msg, args);
}
}
})
There is the Discord.js Guide that you can use if you want something to follow along with. It is really helpful and detailed.
I have noticed you're improperly trying to find a role. In order to get a full roles collection, you will need to use the cache method of message.guild.roles, resulting in the line:
const roleObject = memb.guild.roles.cache.find(...);
var cmdmap = {
role: gimmerole
};
function gimmerole(message, args) {
const member = message.member;
const role = message.guild.roles.cache.find(r => r.name === args.join(' '));
if (!role) return console.log(`The role "${args.join(' ')}" does not exist`);
member.roles.add(role);
}
client.on('message', (msg) => {
var cont = msg.content,
author = msg.member,
chan = msg.channel,
guild = msg.guild;
if (author.id !== client.user.id && cont.startsWith(config.prefix)) {
const [invoke, ...args] = cont.slice(config.prefix.length).trim().split(' ');
console.log(invoke, args);
if (invoke in cmdmap) {
cmdmap[invoke](msg, args);
}
}
}
Credits to Deamon Beast
I was working on a command for a discord.js bot, and whilst making a command command (which turns commands on/off), I've been encountering errors.
When I use the .hasPermission function, I get the error encountered in the title:
TypeError: message.author.hasPermission is not a function
I do not believe it's a problem with my code, as the constructor works on other commands, but I'm open to suggestions. My code is below:
module.exports = {
name: 'module',
description: 'Turn commands on/off',
execute(message, args) {
// required
const Discord = require('discord.js');
const db = require('quick.db')
var randomExt = require('random-ext');
//required end
var commands = ['changelog','invite','prefix','balance','bankrob','beg','deposit','gamble','job','rob','work','afk','avatar','botinfo','serverinfo','userinfo','level','setlevel','ban','kick','mute','purge','unban','unmute','warn','warnings']
let user = message.author;
let commandSelect;
const permissionEmbed = new Discord.MessageEmbed()
.setTitle('You dont have permission to do this')
const commandFail = new Discord.MessageEmbed()
.setTitle('There is no command with that name!')
const argsError = new Discord.MessageEmbed()
.setTitle('Usage: `command <command> <on/off>`')
const completeEmbed = new Discord.MessageEmbed()
.setTitle(`Command \`${args[0]}\` is now \`${args[1]}\``)
if (!message.author.hasPermission('ADMINISTRATOR')) {
return message.channel.send(permissionEmbed);
} else if (user.hasPermission('ADMINISTRATOR')) {
if (!args[0] || !args[1]) {
return message.channel.send(argsError);
} else if (args[0] != 'on' && args[0] != 'off') {
return message.channel.send(argsError);
}
for (i = 0; i > commands.length; i++) {
if (args[0] == commands[i]) {
return commandSelect = commands[i];
}
}
if (commandSelect = null || commandSelect == undefined) {
return message.channel.send(commandFail);
} else {
db.set(`${message.guild.id}.${commandSelect}`, 'false')
return message.channel.send(completeEmbed);
}
}
},
};
I also think it's worth mentioning that when I run the command with arguments, p!command ban off, I get the error TypeError: Discord.MessasgeEmbed is not a constructor instead.
message.author returns a User and message.member returns a GuildMember; the author of the message as a guild member.
Discord Users don't have permissions, guild members have. You can only check if a member has certain permissions, so you need to change your code to:
if (!message.member.hasPermission('ADMINISTRATOR')) {
return message.channel.send(permissionEmbed);
}
// you don't need else or else if as this part is only executed if member
// is an administrator
if (!args[0] || !args[1]) {
return message.channel.send(argsError);
} else if (args[0] != 'on' && args[0] != 'off') {
return message.channel.send(argsError);
}
// ...
I have a !!userinfo command and I am trying to get it to where I can #anyone and it shows there info how I have everything else working but then I came up to this problem here is the error.
UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'map' of undefined
I have looked it up no answer, but I did come up with something it said that it usually means that is unpopulated but I don't know how to get it in there.
const Discord = module.require("discord.js");
const fs = require("fs");
const userdata = JSON.parse(fs.readFileSync('commands/storage/userdata.json', 'utf8'));
module.exports.run = async (bot, message, args) => {
let member;
if (message.mentions.users > 0) {
member = message.mentions.user.size()
} else {
member = message.author
}
let user;
if (message.mentions.users > 0) {
user = message.mentions.user.size()
} else {
user = message.author
}
embed = new Discord.RichEmbed()
.setAuthor(message.member.username)
.setDescription("Users Info", true)
.setColor("#64FF00", true)
.addField("Full Username:", `${message.member.username}${message.member.discriminator}`, true)
.addField("ID:", message.member.id, true)
.addField("Created at:", message.member.createdAt, true)
.addField("Status:", `${user.presence.status}`, true)
.addField("Game:", `${user.presence.game}`, true)
.addField("Roles", member.roles.map(r => `${r}`).join('|'), true);
message.channel.send(embed);
}
module.exports.help = {
name: "userinfo"
}
I Would like it so I can #anyone and there info comes up
You can easily make the first part:
let member;
if (message.mentions.users > 0) {
member = message.mentions.user.size()
} else {
member = message.author
}
let user;
if (message.mentions.users > 0) {
user = message.mentions.user.size()
} else {
user = message.author
}
into:
const user = message.mentions.users.first() || message.author;
const member = message.mentions.members.first() || message.member;
if(!member) return message.channel.send('This command can only be run in a guild!')
Also you want to change the embed bit to:
let embed = new Discord.RichEmbed()
.setAuthor(user.tag)
.setDescription("Users Info", true)
.setColor("#64FF00", true)
.addField("Full Username:", user.tag , true)
.addField("ID:", user.id, true)
.addField("Created at:", user.createdAt, true)
.addField("Status:", user.presence.status , true)
.addField("Game:", user.presence.game ? user.presence.game : 'none' , true)
.addField("Roles", member.roles.map(r => `${r}`).join(' | '), true);
message.channel.send(embed);
I believe the problem lies with how you assign a value to the variable member. Adding to that, I think you have some redundant code since you have a variable member and a variable user which you give a value with the same code.
Below you can find your code which I've rewritten. Give it a go and let me know what the result is.
module.exports.run = async (bot, message, args) => {
let guildMember;
if (message.mentions.members.first()) {
guildMember = message.mentions.members.first();
} else {
guildMember = message.member;
}
// We need the User object aswell for different properties
const user = guildMember.user;
let embed = new Discord.RichEmbed()
.setAuthor(user.username)
.setDescription("Users Info", true)
.setColor("#64FF00", true)
.addField("Full Username:", `${user.username}${user.discriminator}`, true)
.addField("ID:", user.id, true)
.addField("Created at:", user.createdAt, true)
.addField("Status:", `${user.presence.status}`, true)
.addField("Game:", `${user.presence.game}`, true)
.addField("Roles", guildMember.roles.map(r => `${r}`).join('|'), true);
message.channel.send(embed);
}
This sets member to a number
member = message.mentions.user.size()
Since member is now a number, trying to access member.roles results in undefined. And since undefined does not have a .map method, you see that exception.