i am having a problem that whenever i type the +warn <#user> then everything goes well , lets take an example that i want to warn any user so i'll type +warn <#user> and then it will show a embed by saying that your are banned by this this and you are banned from this this and also shows that how many warns the user now have and lets also take that he have 1 warn till now, and now warn another user by typing +warn <#user> and then it will show the thing blah blah blah but.. when the bot shows that how many warns the second user have then it will show the same value of warn as the first user like this warns(of the first user): 1 but when with the second user it shows warns(of the second user): 2 and even the second user have 0 warns but it will show 2 and when you retry to warn the first user it will show 3 warns idk why
code:-
const config = require("../config.json");
const Database = require("#replit/database")
const db = new Database()
const { MessageEmbed, username } = require('discord.js')
exports.run = async (client, message, args, Discord) => {
let reason = args.slice(1).join(" ")
if (!reason) reason = "No reason provided"
const user = message.author.id
let warns = await db.get(`warns_${message.author.id}`)
let member = message.mentions.members.first()
if (!member) return message.reply("Please mention a user to warn")
const wembed = new MessageEmbed()
.setTitle(`You have been warned`)
.setDescription(`You have been warned by ${message.author.username}\nFrom the server of: ${message.guild.name}\nWith the reason: ${reason}\nNow you have ${warns} warns`)
if (!member === member.user.bot) {
member.send({embeds: [wembed]})
} else {
message.channel.send(`unable to send dm to ${member}`)
}
const embed = new MessageEmbed()
.setTitle(`Warn to ${member}`)
.setDescription(`${member} has been warned successfully warned\n\n${member} have now ${warns}\nReason: ${reason}`)
message.channel.send({embeds: [embed]})
await db.set(`warns_${message.author.id}`, warns + 1)
member.send({embeds: [wembed]})
}
exports.conf = {
aliases: ['warning']
};
exports.help = {
name: "warn"
};```
Related
I am attempting to create a kick command for a bot and its working fine however when the bot logs the embed it doesn't display the data in the variable but [object Object]
The Embed Output
My code is as following
exports.run = async (client, message, args) => {
const username = message.mentions.members.first().user.username; //gets the first mentioned users username
let member = message.mentions.members.first();
if(!member) return message.reply("Please mention a valid member of this server");
if(!member.kickable) return message.reply("I cannot kick this member!");
const reason = args.slice(1).join(' ');
const kickedmessage = new MessageEmbed() //embed to send to a logs channel
.setColor('#1773BA')
.setTitle('User Kicked')
.setDescription({username} + "had been kicked for " + {reason})
;
client.channels.cache.get("771835493305286688").send(kickedmessage)//output the embed
member.kick(reason);
I am using discord.js v12
exports.run = async (client, message, args) => {
const username = message.mentions.members.first().user.username; //gets the first mentioned users username
let member = message.mentions.members.first();
if (!member) return message.reply("Please mention a valid member of this server");
if (!member.kickable) return message.reply("I cannot kick this member!");
const reason = args.slice(1).join(" ");
const kickedmessage = new MessageEmbed() //embed to send to a logs channel
.setColor("#1773BA")
.setTitle("User Kicked")
.setDescription(username + "had been kicked for " + reason);
client.channels.cache.get("771835493305286688").send(kickedmessage); //output the embed
member.kick(reason);
};
I am trying to find out how to make a command that detects a channel from separate guilds (etc. $setwelcome #channel). I have made the command but, instead of setting it for one guild its setting it for all guilds. this is my code
client.on('guildMemberAdd', member => {
console.log("New member joined.");
console.log(`Matching on joinChannel: ${joinChannel}`);
const channelID = joinChannel.toString().match(/\d+/)[0];
const channel = member.guild.channels.cache.get(channelID);
console.log(`Fetched channel with ${channelID}`);
// Do nothing if the channel wasn't found on this server
if (!channel){
console.log("The joinChannel does not exist.");
}else{
// Send the message, mentioning the member
channel.send(`Welcome to the server, ${member}`);
member.roles.add(member.guild.roles.cache.find(i => i.name === 'member'));
}
});
/*const channel = member.guild.channels.cach.find((ch) => {
console.log(ch.name);
return ch.name === joinChannel;*/
client.on('guildMemberRemove', member =>{
console.log(`Matching on joinChannel: ${joinChannel}`);
const channelID = joinChannel.toString().match(/\d+/)[0];
const channel = member.guild.channels.cache.get(channelID);
console.log(`Fetched channel with ${channelID}`);
// Do nothing if the channel wasn't found on this server
if (!channel) return;
// Send the message, mentioning the member
channel.send(`Goodbye ${member}, we will miss you :cry:`);
})
client.on("message", message => {
if (!message.author.bot){
const content = message.content;
if (content.toLowerCase().startsWith(`${prefix}setwelcome`)){
joinChannel = content.substring((`${prefix}setwelcome`).length).trim();
console.log(`Join channel changed to ${joinChannel}`);
}
}
});
I guess you could use JSON, best in a database, or different file:
//how the JSON should look like
{
"G123456789012345678": "123456789012345678"
}
//first part is the guild ID, second, is the id the channel you choose
Now you have to somehow modify this data, for this I will use fs, which assumes that this is in the file system. I’ll reference it as if it was in the same folder, and is named: welcomeChannels.json
const fs = require('fs');
//maybe other "requires"
client.on('message', msg => {
//checking message content etc
let ChansString = fs.readFileSync('./welcomeChannels.json');
let chans = JSON.parse(ChansString);
//you can get the channel for the guild with chans['G'+guild.id]
chans['G'+msg.guild.id] = msg.mentions.channels.first().id || msg.channel.id;
fs.writeFileSync('./welcomeChannels.json', JSON.stringify(chans));
})
//use chans[`G${guild.id}`] to get the welcome channel id
Warning: this could fill up your storage. You should use a database instead.
I'm someone who just got into coding recently.
I'm trying to create a Discord bot that can do custom roles that can allow a user of that custom role to edit its hex or name.
There's also the creation of a role creator that also assigns the mentioned user the role.
My problem is that I've encountered an issue with the role creation + assignment and the commands that allow the user to edit their role.
Here are the problems:
(node:6288) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'get' of undefined for the role creator command
When I try to use the commands that allow the user to customize their roles, the commands don't work, or to be more specific, they don't activate.
I do believe that the codes I'm using could be outdated, therefore if that is the case, please give me the exact location and the right code.
Here are some pictures of the codes. I've pasted the codes below, but I'm a bit new to this forum, so please pay attention to the separating pieces like "Role Customization Code:" to distinguish which one's which. For some reason, the module.exports aren't going in there. Please describe and let me know a solution to these problems in a specific way since I am a newbie at this topic.
Role creation command + assignment error.
Role creation command + assignment code part 1.
Role creation command + assignment code part 2.
Role customization code part 1.
Role customization code part 2.
Role customization code part 3.
Role creation + assignment code:
const Discord = module.require("discord.js");
const guild = require("./config.json");
module.exports.run = async (bot, message, args) => {
const query = bot.db;
function embedFail(text) {
let embed = new Discord.RichEmbed().setColor("#ff0000").setDescription(text);
return embed;
}
function embedSuccess(text) {
let embed = new Discord.RichEmbed().setColor("#7CFC00").setDescription(text);
return embed;
}
if (!args[0]) return message.channel.send("Please specify a user to add!");
let toAdd = message.guild.members.get(args[0]) || message.guild.members.get(message.mentions.users.first().id);
let rolejoin = args.slice(1).join(" ");
let myRole = message.guild.roles.cache.get((val) => val.name.toLowerCase() === rolejoin.toLowerCase());
if (!toAdd) return message.channel.send("User not found!");
if (!rolejoin) return message.channel.send("Please specify a role to add!");
let botRole = message.guild.members.get(bot.user.id).highestRole;
let isPosition = botRole.comparePositionTo(myRole);
if (isPosition <= 0) return message.channel.send(embedFail("This role is higher than me, I cannot add this role!"));
let res = await query(`SELECT * FROM user_roles WHERE role_id='${myRole.id}'`);
if (res[0]) {
await query(`DELETE FROM user_roles where role_id='${myRole.id}'`);
toAdd.removeRole(myRole);
message.channel.send(embedSuccess(`Removed role ${myRole.name} from ${toAdd.user.username}`));
} else if (!res[0]) {
await query(`INSERT INTO user_roles (guild_id, user_id, role_id) VALUES ('${message.guild.id}',${toAdd.id},'${myRole.id}')`);
toAdd.addRole(myRole);
message.channel.send(embedSuccess(`Adding role ${myRole.name} to ${toAdd.user.username}`));
}
};
Role Customization Code:
const Discord = module.require("discord.js");
const guild = require("./config.json");
module.exports.run = async (bot, message, args, db) => {
const query = bot.db;
function embedFail(text) {
let embed = new Discord.RichEmbed().setColor("#ff0000").setDescription(text);
return embed;
}
function embedSuccess(text) {
let embed = new Discord.RichEmbed().setColor("#7CFC00").setDescription(text);
return embed;
}
let res = await query(`SELECT * FROM user_roles WHERE guild_id = '${message.guild.id}' AND user_id = '${message.author.id}'`);
if (!args[0]) {
if (!res[0]) return message.channel.send(embedFail("You do not have a role!"));
let myRole = message.guild.roles.cache.find(res[0].role_id);
let assignNames = "";
let embed = new Discord.RichEmbed()
.setAuthor(`Current role assigned to ${message.author.username}`, message.guild.iconURL)
.setColor(myRole.hexColor)
.addField(`Name`, `${myRole.name}`, true)
.addField(`Colour`, `${myRole.hexColor}`, true);
message.channel.send(embed);
} else {
if (!res[0]) return message.channel.send(embedFail("You do not have a role!"));
let myRole = message.guild.roles.cache.find(res[0].role_id);
if (!myRole) {
await query(`DELETE FROM user_roles where guild_id = '${message.guild.id}' AND role_id = '${res[i].role_id}' and user_id = '${res[i].user_id}'`);
return message.channel.send(embedFail("You do not have a role!"));
}
switch (args[0]) {
case "name":
let name = args.slice(1).join(" "),
oldName = myRole.name;
await myRole.setName(name);
await message.channel.send(embedSuccess(`You have changed ${oldName}'s name to ${name}!`));
break;
case "color":
case "color":
let hexCode = args[1],
oldHex = myRole.hexColor;
await myRole.setColor(hexCode);
await message.channel.send(embedSuccess(`You have changed ${myRole.name}'s color from ${oldHex} to #${hexCode}!`));
break;
}
}
};
I want to send an error message saying that the user already has the role if they do in an addrole command.My current command is:
const { MessageEmbed } = require("discord.js");
module.exports = {
name: "addrole",
description: "adds a role to a member",
execute: async (message , args) => {
if (!message.member.hasPermission("MANAGE_ROLES")) return message.channel.send("Invalid Permissions")
let member = message.mentions.members.first();
let role = message.mentions.roles.first();
if (!member)
return message.reply("Please mention a valid member of this server");
if (!role) return message.reply("please mention a valid role of this server");
const highest = message.member.roles.highest;
if(highest.comparePositionTo(role) <= 0)
return message.channel.send(`You cannot add roles equal/higher to that member's highest role`)
let addroleembed = new MessageEmbed()
.setTitle(`:white_check_mark: ${role.name} has been added to ${member.user.tag}`)
.setFooter(`Action performed by ${message.author.tag}`)
.setColor('77B255')
addroleembed.setTimestamp();
member.roles.add(role);
message.channel.send(addroleembed)
}}
I have tried using
if(!message.member.roles.cache.some(r=>[`${role.name}`].includes(r.name)))
and
if (member.roles.has(role.id) {
But neither of these seem to work, Anyone know the reason behind this? If I can't use either of these methods, Can you suggest me a solution?
You are so close!
All you need is cache when using has()
member.roles.cache.has(<RoleID>);
Learn More Here
You need to combine your two tries.
if(message.member.roles.cache.has("role ID") {
//rest of your code
}
I have this command on my bot where you can mute someone using the command g!mute where the 'user' is mentioned using #. However, if you don't mention e.g GeoGeo instead of #GeoGeo, it causes the bot to crash. I know you need to put .catch(console.error); somewhere, but I'm not sure where. Thanks in advance. The Error is
let person = message.guild.member(message.mentions.users.first() || message.guild.members.get(args[1]))
^
TypeError: message.guild.members.get is not a function
Code:
const Discord = require('discord.js');
const ms = require('ms');
module.exports = {
name: 'mute',
description: "this is mute command",
execute(message, args){
if(!message.member.roles.cache.find(r => r.name ==="Staff", "Head Staff", "Owner", "Co-Owner")) return message.channel.send(`YOU DO NOT HAVE PERMISSION TO DO THAT`)
let members = args[0];
if(!members) return message.reply("g!mute <user> <time>")
let person = message.guild.member(message.mentions.users.first() || message.guild.members.get(args[1]))
if(!person) return message.reply("That person is not in the server!");
let mainrole = message.guild.roles.cache.find(role => role.name === "Fans");
let muterole = message.guild.roles.cache.find(role => role.name === "muted");
if(!muterole) return message.reply("That role does not exist");
let time = args[1];
if(!time){
return message.reply("g!mute <user> <time>");
}
person.roles.remove(mainrole.id);
person.roles.add(muterole.id);
const embed = new Discord.MessageEmbed()
.setTitle ("Muted:")
.setDescription (`${person.user.tag} has now been muted for ${ms(ms(time))}`)
.setColor(0x01B8FF)
message.channel.send(embed);
setTimeout(function(){
person.roles.add(mainrole.id)
person.roles.remove(muterole.id)
const embed = new Discord.MessageEmbed()
.setTitle ("Muted:")
.setDescription (`${person.user.tag} has been unmuted`)
.setColor(0x01B8FF)
message.channel.send(embed);
}, ms(time));
}
}
When faced with an error like: TypeError: message.guild.members.get is not a function
The logical thing to do is check the docs to see that message.guild.members really has a function named get. Here's the docs: https://discord.js.org/#docs/main/stable/class/GuildMemberManager
No get. But there is a cache like you use elsewhere in the code. Just by checking over the docs you can tell that your existing code is wrong (it's outdated) and you need to use cache like you do elsewhere in your code:
message.guild.members.cache.get(args[1])