DiscordAPIError 10007 unknown member - javascript

how to fix this DiscordAPIError 10007 unknown member
async execute(interaction) {
const { channel, options } = interaction;
const user = options.getUser("target");
const reason = options.getString("reason") || `\`ไม่ได้กรอกเหตุผล\``;
const member = await interaction.guild.members.fetch(user.id);
const errEmbed = new EmbedBuilder()
.setTitle("**Mibow so cutest**")
.setDescription(`คุณไม่สามารถใช้คำสั่งนี้กับ \`${user.username}\` ยศอาจจะสูงกว่าหรือเท่ากับตัวคุณ.`)
.setColor(0xf44336)
.setTimestamp();
if (member.roles.highest.position >= interaction.member.roles.highest.position)
return interaction.reply({ embeds: [errEmbed], ephemeral: true });
await member.ban({ reason });
How to fix this error, thanks very much

Related

DiscordJS v13 Cannot read properties of undefined (reading 'channels')

Code:
const config = require('../../config.json');
const Discord = require('discord.js');
module.exports = async(guild, bannerURL, client) => {
const logChannel = await client.channels.cache.get(config.log_channel_id);
if (!logChannel) return;
const embed = new Discord.MessageEmbed()
.setAuthor({ name: guild.name, iconURL: guild.iconURL() })
.setDescription(`**${guild.name} has banner now!**`)
.setImage(bannerURL)
.setColor(config.colour)
.setTimestamp()
return logChannel.send({ embeds: [embed] })
}
When adding a banner to the server it gives the error Unhandled Rejection: TypeError: Cannot read properties of undefined (reading 'channels')
The other logging files have the exact same line of code const logChannel = await client.channels.cache.get(config.log_channel_id); and it works fine
Adding console.log(client) before const logChannel returns undefined
This code below works after we troubleshot the issue.
banner.js
module.exports = {
name: 'banner',
description: 'emit update',
devs: true,
run: async (guild, message) => {
guild.emit('guildBannerAdd', message.member);
message.channel.send('Done ...');
},
};
guildBannerAdd.js
const config = require('../../config.json')
const Discord = require('discord.js')
module.exports = async (client, member) => {
const guild = client.guilds.cache.get(config.serverID)
const logChannel = client.channels.cache.get(config.log_channel_id);
if (!logChannel) return;
const embed = new Discord.MessageEmbed()
.setAuthor({
name: guild.name,
iconURL: guild.iconURL()
})
.setDescription(`**${guild.name} has banner now!**`)
.setImage(guild.bannerURL())
.setColor(config.colour)
.setTimestamp();
return logChannel.send({
embeds: [embed]
});
}

TypeError: command.run is not a function

I'm kinda new to coding and i cannot figure this out. im trying to add permission handler and when i run a slash command, it responds within the error given below.
error:
D:\VS Code\######\events\interactionCreate.js:9
command.run(client, inter)
^
TypeError: command.run is not a function
code (interactionCreate):
const { MessageEmbed, Message, Interaction } = require("discord.js")
const client = require("../index").client
client.on('interactionCreate', async inter => {
if(inter.isCommand()) {
const command = client.commands.get(inter.commandName);
if(!command) return;
command.run(client, inter)
if (command.help?.permission) {
const authorPerms = inter.channel.permissionsFor(inter.member);
if (!authorPerms || !authorPerms.has(command.permission)) {
const noPerms = new MessageEmbed()
.setColor('RED')
.setDescription(`bruh no perms for ya: ${command.permission}`)
return inter.editReply({embeds: [noPerms], ephemeral: true})
.then((sent) =>{
setTimeout(() => {
sent.delete()
}, 10000)
})
return;
}
}
}
}
)
this is how one of my command file looks like, its a handler which goes "commands > moderation > ban.js"
const { MessageEmbed, Message } = require("discord.js")
module.exports.run = async (client, inter) => {
const user = inter.options.getUser('user')
let BanReason = inter.options.getString('reason')
const member = inter.guild.members.cache.get(user.id)
if(!BanReason) reason = 'No reason provided.'
const existEmbed = new MessageEmbed()
.setColor('#2f3136')
.setDescription('<:pending:961309491784196166> The member does not exist in the server.')
const bannedEmbed = new MessageEmbed()
.setColor('#46b281')
.setDescription(`<:success:961309491935182909> Successfully banned **${user.tag}** from the server with the reason of: **${BanReason}**.`)
const failedEmbed = new MessageEmbed()
.setColor('#ec4e4b')
.setDescription(`<:failed:961309491763228742> Cannot ban **${user.tag}**. Please make sure I have permission to ban.`)
if(!member) return inter.reply({ embeds: [existEmbed]})
try {
await inter.guild.members.ban(member, { reasons: BanReason })
} catch(e) {
return inter.reply({ embeds: [failedEmbed]})
}
inter.reply({ embeds: [bannedEmbed]})
}
module.exports.help = {
name: 'ban',
permission: 'BAN_MEMBERS'
}
btw inter = interaction

Cannot read properties of undefined (reading 'send') (Discord.js v13)

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]});
})

Discord.js: TypeError: confirmation.createMessageComponentCollector is not a function

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({
...

Command is working, but also getting 'interaction failed' at the same time?

Title might be a little confusing so here's a screenshot of what's happening when I type a command:
It works, but then it fails at the same time. I get no errors from this interaction. Here's my code:
const { SlashCommandBuilder } = require("#discordjs/builders");
const { MessageEmbed } = require("discord.js");
module.exports = {
data: new SlashCommandBuilder()
.setName("suggest")
.setDescription("Send your suggestion to the specified channel")
.addStringOption((option) =>
option
.setName("suggestion")
.setDescription("Your suggestion")
.setRequired(true)
),
async execute(interaction) {
let suggestion = interaction.options.getString("suggestion");
const embed = new MessageEmbed()
.setColor("#0099ff")
.setTitle(`New suggestion by ${interaction.member.displayName}`)
.setDescription(`${suggestion}`);
await interaction.channel
.send({
embeds: [embed],
})
.then(function (interaction) {
interaction.react(`👍`).then(interaction.react(`👎`));
});
},
};
Try deferring the reply. More info on it here
For example,
const wait = require('util').promisify(setTimeout);
client.on('interactionCreate', async interaction => {
if (!interaction.isCommand()) return;
if (interaction.commandName === 'ping') {
await interaction.deferReply();
await wait(4000);
await interaction.editReply('Pong!');
}
});

Categories