So im making a ban slash command using .addUserOption but when i try to get the permissions from the .addUserOption so that the bot doesnt crash when trying to ban an admin i get an error. I already know why, you cant get permissions from a user, only a GuildMember, so how would i go from user to GuildMember?
CODE: (if needed)
const { SlashCommandBuilder } = require('#discordjs/builders');
const { MessageEmbed } = require('discord.js')
module.exports = {
data: new SlashCommandBuilder()
.setName("ban")
.setDescription("Bans the specified user!")
.addUserOption((option) =>
option
.setName("user")
.setDescription('Who do you want to ban?')
.setRequired(true)
)
.addStringOption((option) =>
option
.setName('reason')
.setDescription("Whats the reason youre banning this user?")
),
async execute(client, interaction) {
if (client.cooldowns.has(interaction.user.id)) {
let cooldownEmbed = new MessageEmbed()
.setTitle("Please wait for the cooldown to end.")
.setDescription("This is so that the bot doesnt overload")
.setColor("RED")
.setFooter("The cooldown is 5 sec")
.setTimestamp()
interaction.reply({ embeds: [cooldownEmbed], ephemeral: true });
} else {
const user = interaction.member
const permission = user.permissions.has('BAN_MEMBERS');
let embed = new MessageEmbed()
.setTitle("❌️ | You dont have the permissions to use this command.")
if(!permission)
return interaction.reply({embeds: [embed]})
const tgt = interaction.options.getUser('user')
let permsEmbed = new MessageEmbed()
.setTitle("The user you are trying to ban is an Administrator!")
.setColor("RED")
if (tgt.permissions.has('BAN_MEMBERS')) return interaction.reply({ embeds: [permsEmbed]})
const reason = interaction.options.getString('reason') || "No reason specified"
client.cooldowns.set(interaction.user.id, true);
setTimeout(() => {
client.cooldowns.delete(interaction.user.id);
}, client.COOLDOWN_SECONDS * 1000);
}
}
}
I checked CollinD's suggestion and i managed to fix the problem. Heres the code if anyone else runs into this problem and needs an answer.
CODE:
const tgt = interaction.options.getUser('user');
let permsEmbed = new MessageEmbed()
.setTitle('The user you are trying to ban is an Administrator!')
.setColor('RED');
const guildMember = interaction.guild.members.cache.get(tgt.id);
if (guildMember.permissions.has('BAN_MEMBERS'))
return interaction.reply({ embeds: [permsEmbed] });
Related
i have been trying to make a leaveserver code for my bot, but i always get the error message Cannot read properties of undefined (reading 'send') I really wanna know why it always says the error messages! Please help me! Thanks!
const Discord = require("discord.js")
const rgx = /^(?:<#!?)?(\d+)>?$/;
var self = this
const OWNER_ID = require("../../config.json").OWNER_ID;
module.exports = {
name: "leaveserver",
description: "leavs a server",
run: async (client, message, args) => {
if (!OWNER_ID)
return message.channel.send("This command is Owner Only")},
async run(message, args) {
const guildId = args[0];
if (!rgx.test(guildId))
return message.channel.send("Please Provide a valid server id!")
const guild = message.client.guild.cache.get(guildId);
if (!guild) return message.channel.send(message, 0, 'Unable to find server, please check the provided ID');
await guild.leave();
const embed = new MessageEmbed()
.setTitle('Leave Guild')
.setDescription(`I have successfully left **${guild.name}**.`)
.setFooter(message.member.displayName, message.author.displayAvatarURL({ dynamic: true }))
.setTimestamp()
.setColor(message.guild.me.displayHexColor);
message.channel.send({embeds: [embed]});
}
}
Try this code
const {
MessageEmbed
} = require("discord.js")
const rgx = /^(?:<#!?)?(\d+)>?$/;
const OWNER_ID = require("../../config.json").OWNER_ID;
module.exports = {
name: "leaveserver",
description: "leaves a server",
run: async (client, message, args) => {
const guildId = args[0];
const guild = message.client.guilds.cache.get(guildId);
if (!OWNER_ID) return message.channel.send("This command is Owner Only");
if (!rgx.test(guildId)) return message.channel.send("Please Provide a valid server id!")
if (!guild) return message.channel.send(message, 0, 'Unable to find server, please check the provided ID');
await guild.leave();
const embed = new MessageEmbed()
.setTitle('Leave Guild')
.setDescription(`I have successfully left **${guild.name}**.`)
.setFooter({
text: message.member.displayName,
iconURL: message.author.displayAvatarURL({
dynamic: true
})
})
.setTimestamp()
.setColor(message.guild.me.displayHexColor)
message.channel.send({
embeds: [embed]
})
}
}
Removed the duplicated async run(message, args) {
Try to do this:
const client = new Discord.Client({intents:
["GUILDS", "GUILD_MESSAGES"]});
client.on("message" , msg => {
await guild.leave();
const embed = new MessageEmbed()
.setTitle('Leave Guild')
.setDescription(`I have successfully left **${guild.name}**.`)
.setFooter(msg.member.displayName, msg.author.displayAvatarURL({ dynamic: true }))
.setTimestamp()
.setColor(msg.guild.me.displayHexColor);
msg.channel.send({embeds: [embed]});
})
first issue: all the embeds in my code stopped working - no matter what command I try to run if it has an embed in it I get the error: DiscordAPIError: Cannot send an empty message
second issue: I'm currently programming a mute command with a mongoDB database, it puts everything I need it in the database however if I try to mute someone it ends up only muting them for 1s by default, basically completely ignoring the second argument. heres what I want the command to do: when you mute someone you need to provide the user id and a time (works in ms) + reason then it puts it in the data base.
here's the code: [P.S. Im not getting an error message, it just doesnt work properly like I want it to]
const mongo = require('../mongo.js')
const muteSchema = require('../schemas/mute-schema.js')
const Discord = require('discord.js')
const ms = require ("ms")
module.exports = {
commands: 'mute',
minArgs: 2,
expectedArgs: "<Target user's #> <time> <reason>",
requiredRoles: ['Staff'],
callback: async (message, arguments) => {
const target = message.mentions.users.first() || message.guild.members.cache.get(arguments[0])
if (!target) {
message.channel.send('Please specify someone to mute.')
return
}
const { guild, channel } = message
arguments.shift()
const mutedRole = message.guild.roles.cache.find(role => role.name === 'muted');
const guildId = message.guild.id
const userId = target.id
const reason = arguments.join(' ')
const user = target
const arg2=arguments[2]
const mute = {
author: message.member.user.tag,
timestamp: new Date().getTime(),
reason,
}
await mongo().then(async (mongoose) => {
try {
await muteSchema.findOneAndUpdate(
{
guildId,
userId,
},
{
guildId,
userId,
$push: {
mutes: mute,
},
},
{
upsert: true,
}
)
} finally {
mongoose.connection.close()
}
})
message.delete()
user.roles.add(mutedRole)
setTimeout(function() {
user.roles.remove(mutedRole)
}, ms(`${arg2}`));
try{
message.channel.send(`works`)
}
catch(error){
const embed3 = new Discord.MessageEmbed()
.setDescription(`✅ I Couldn't DM them but **${target} has been muted || ${reason}**`)
.setColor('#004d00')
message.channel.send({ embeds: [embed3] });
}
},
}
djs v13 has a new update where you need to send embeds like this:
const exampleEmbed = new Discord.MessageEmbed()
.setTitle('example')
.setDescription('example')
.setColor('RANDOM')
message.channel.send({embed: [exampleEmbed]});
I am making a ban command with confirmation thingy. I use buttons and
MessageComponentCollector for it. However it fails and outputs the error. Here's my code:
var bu1tton = new Discord.MessageButton()
.setStyle(`SUCCESS`)
.setEmoji(`872905464797605938`)
.setLabel(`Proceed`)
.setCustomId("proceed")
var bt1 = new Discord.MessageButton()
.setStyle("DANGER")
.setEmoji(`872905464747286598`)
.setLabel(`Cancel`)
.setCustomId("back")
var row = new Discord.MessageActionRow()
.addComponents([bu1tton, bt1])
const confirmation = interaction.followUp({
embeds: [new Discord.MessageEmbed().setTitle(`Are you sure?`).setColor("RED").setDescription(`Are you sure you want to ban **${target.user.tag}** for ${reason}?\nThis action will be automatically canceled in 10 seconds if you do not select any option.`).setFooter(interaction.guild.name)],
components: [row]
})
const filter = ( inter ) => inter.user.id === interaction.user.id
const collector = confirmation.createMessageComponentCollector({ filter, time: 10000 })
collector.on('collect', async interaction => {
if(interaction.customId === "proceed") {
interaction.deferReply()
await interaction.followUp({
content: `**${interaction.user.tag}** banned **${target.user.tag}**.\nReason: *${reason}*.`
})
const reportChannel = interaction.guild.channels.cache.get(log_channel)
const messageLink = `https://discord.com/channels/${interaction.guild.id}/${interaction.channel.id}/${interaction.id}`;
let logchat = new Discord.MessageEmbed()
.setAuthor(`${interaction.user.tag} (${interaction.user.id})`, interaction.user.displayAvatarURL())
.setDescription(`**<:target:890913045126213633> Member:** ${target.user} (${target.user.id})\n**<:law:913487126576914502> Action:** Ban\n**<:decision:890913045537235005> Reason:** ${reason}\n**<:link:907511618097803284> Link:** [Click here](${messageLink})`)
.setColor('RED')
.setFooter(`ID: ${uuidv4()}`)
.setTimestamp();
const log = await reportChannel.send({
embeds: [logchat]
})
const data = log.embeds[0]
let dmembed = new Discord.MessageEmbed()
.setTitle("You have been banned from Rice Farm #11")
.setDescription(`If you find this ban abusive or wrong, please proceed to [Ban Appeal page](https://ricesupport.brizy.site/).`)
.addField("Moderator", `${interaction.user}`)
.addField("Reason", `${reason}`)
.setColor("RED")
.setFooter(`${data.footer.text}`)
.setTimestamp();
await target.send({
embeds: [dmembed]
}).catch((err) => console.log(err));
await target.ban({
reason: `Banned by ${interaction.user.tag} | Reason: ${reason}`,
days: num
}).catch((err) => console.log(err));
}
if(interaction.customId === "back") {
interaction.deferReply()
interaction.message.delete()
}
})
collector.on('end', async interaction => {
})
It sends the embed with components, but the collector obviously won't create.
Here's the full error:
[Error Handling System] Unhandled Rejection/Catch
TypeError: confirmation.createMessageComponentCollector is not a function
at Object.run (/PC/184395345943/slash/Moderation/ban.js:114:36) Promise {
<rejected> TypeError: confirmation.createMessageComponentCollector is not a function
at Object.run (/PC/184395345943/slash/Moderation/ban.js:114:36)
}
I tried changing confirmation.createMessageComponentCollector(...) line to confirmation.message.createMessageComponentCollector(...), but it output almost the same error:
confirmation.message.createMessageComponentCollector() - undefined
This made me confusing. Thank you in advance! <3
followUp returns a Promise <(Message|APIMessage )>, see for example this doc. So you need to await on it:
const confirmation = await interaction.followUp({
...
This is reaction roles button command it working but after i restart the bot it say This interaction failed how can i fix it? is it impossible? i was use simplydjs it working but i can't change the message,when user got thier roles the bot will send message and i want change it but i can't so i use collect and it not working after i restart the bot so that why i ask this question.
const Command = require("../Structures/Command.js");
const Discord = require('discord.js');
const { MessageButton } = require('discord.js');
module.exports = new Command({
name: "reactionrolebuttons",
description: "reaction role but button",
async run(message, args, client, interaction, collect) {
let embed = new Discord.MessageEmbed()
.setTitle("Ping Roles:")
.setColor("#0099ff")
.setDescription("`Click some button bellow if you want get notified!`")
const row = new Discord.MessageActionRow()
.addComponents(
new MessageButton()
.setCustomId('Acm')
.setLabel('Announcement')
.setStyle('SECONDARY')
.setEmoji("📰"),
new MessageButton()
.setCustomId('Gv')
.setLabel('Giveaways')
.setStyle('SECONDARY')
.setEmoji("🎉")
)
const m = await message.channel.send({ embeds: [embed], components: [row] });
const iFilter = i => i.user.id === message.author.id;
const collector = m.createMessageComponentCollector({ filter: iFilter, time: 60000 })
collector.on('collect', async i => {
if (i.customId === 'Acm') {
const role = message.guild.roles.cache.get("901353036759310386");
if (i.member.roles.cache?.has('901353036759310386')) {
i.member.roles.remove('901353036759310386')
i.reply({ content: `${role} was removed from you`, ephemeral: true });
} else {
i.member.roles.add('901353036759310386')
i.reply({ content: `${role} was added to you`, ephemeral: true });
}
} else if (i.customId === 'Gv') {
const role = message.guild.roles.cache.get("901370872827346975");
if (i.member.roles.cache?.has('901370872827346975')) {
i.member.roles.remove('901370872827346975')
i.reply({ content: `${role} was removed from you`, ephemeral: true });
} else {
i.member.roles.add('901370872827346975')
i.reply({ content: `${role} was added to you`, ephemeral: true });
}
}
})
}
});
on your filter dont forget to add await i.deferUpdate()
Also your collector doesnt seem a bit using await anymore, if u wanna use async just add await too.
At collector
await i.reply("......")
on your filter
const filter = async i => {
await i.deferUpdate()
return i.customId && i.user.id === message.author.id;
}
[Edit]
Also you need to end the collector after user clicked the button
await i.reply..........
await collector.stop("complete")
If you wanna continue to use that button for next interaction you dont need collector btw,
Just wrap the the condition on the interactionCreate event
client.on("interactionCreate", async (interaction) => {
if (!interaction.isButton()) return;
if(interaction.customId === "Acm") {
\\Your code here
}
})
I want to edit a existing embed in discord.js. But Im getting the error that message.edit is not a function.
Code:
await mongo().then(async mongoose => {
const results = await applicationSchema.findOneAndDelete({
guildId: guildId,
applicationId: applicationId
})
for (const application of results.applications) {
const { applicationId, userId, appliedfor } = application
user22 = bot.users.cache.get(userId);
let acceptembed = new Discord.MessageEmbed()
.setColor(colours.maincolour)
.setDescription(`Lieber <#${userId}>! Deine Bewerbung wurde angenommen!`)
user22.send(acceptembed)
// m = reaction.messages.cache.fetch(applicationId);
// m.edit(null, { embed: output });
let message = bot.channels.cache.get('823554343827013652').messages.fetch(applicationId)
await message.edit()
}
})
The message you are sending should be put in .edit() as it would for .send(). Please note that this does not add to the message, but instead replaces it.
bot.channels.cache.get('823554343827013652').messages.fetch(applicationId)
.then(message => message.edit(acceptembed));