My bot says it doesnt have permissions to kick/ban - node.js

I am making a Discord bot in js. Yesterday i finished some work on the bot's ban command and it worked normally. Today I wake up, don't modify anything and when I try it again, it says that it does not have permission. Nothing was changed and noone changed the permissions of the bot, it still has administrator. The error message:
(node:2490) UnhandledPromiseRejectionWarning: DiscordAPIError: Missing Permissions
at RequestHandler.execute (/home/runner/AUN/node_modules/discord.js/src/rest/RequestHandler.js:154:13)
at processTicksAndRejections (internal/process/task_queues.js:97:5)
at async RequestHandler.push (/home/runner/AUN/node_modules/discord.js/src/rest/RequestHandler.js:39:14)
My code is (a bit long):
const Discord = require("discord.js");
const dp = require('discord-prefix');
const lang = require('../language_manager');
const settings = require('discord-server-settings');
module.exports = (message, client) => {
if (!message.member.permissions.has("BAN_MEMBERS")) return message.reply("You do not have the permission to ban users");
if (!message.guild.me.hasPermission("BAN_MEMBERS")) return message.reply("I do not have permission to ban users");
let prefix = dp.getPrefix();
if(dp.getPrefix(message.guild.id)){
prefix = dp.getPrefix(message.guild.id);
}
var langchar = settings.getSetting('lang', message.guild.id)
const args = message.content.slice(prefix.length).trim().split(' ');
const command = args.shift().toLowerCase();
var noerror = true;
const member = getUserFromMention(args[0]);
const reason = args[1] || lang.get('ban_no_reason', langchar);
const embed1 = new Discord.MessageEmbed()
.setAuthor('AUN', 'https://drive.google.com/uc?export=view&id=129_JKrVi3IJ6spDDciA5Y5sm4pjUF7eI')
.setTitle(lang.get('ban_title', langchar))
.setColor('#ed3f2c')
.setDescription(lang.get('ban_noone_banned', langchar))
.setTimestamp()
.setFooter('Ping: ' + client.ws.ping + ' | '+prefix+command);
const embed = new Discord.MessageEmbed()
.setTitle(lang.get('ban_you_title', langchar))
.setAuthor("AUN", "https://drive.google.com/uc?export=view&id=129_JKrVi3IJ6spDDciA5Y5sm4pjUF7eI")
.setColor(0x00AE86)
.setDescription(lang.get('ban_you_part1', langchar)+message.guild.name+lang.get('ban_you_part2', langchar)+message.member.name+lang.get('ban_you_part3', langchar)+reason)
.setFooter("Ping: "+client.ws.ping+" | AUN discord bot")
.setTimestamp();
if (!member) {
embed1.setTitle(lang.get('ban_error', langchar))
.setDescription(lang.get('ban_no_mention', langchar))
.setColor('#bd1300');
noerror = false;
}
if(noerror){
embed1.setDescription(lang.get('ban_banned_part1', langchar)+member.tag+lang.get('ban_banned_part2', langchar));
member.send(embed);
}
message.channel.send(embed1);
try{
return message.guild.member(member).ban();
}catch (e){
return;
}
function getUserFromMention(mention) {
if (!mention) return;
if (mention.startsWith('<#') && mention.endsWith('>')) {
mention = mention.slice(2, -1);
if (mention.startsWith('!')) {
mention = mention.slice(1);
}
return client.users.cache.get(mention);
}
}
}
Please if you have any idea what is going on, tell me

You should check if you can actually ban the member.
You can check this with
GuildMember#manageable

Related

Discord.js - TypeError: Cannot read properties of undefined (reading 'commands')

I'm coding a Discord Bot in JavaScript, but I have this error when I launch the bot !
I don't find because I check the "application.commands" box!
Here's the full error message:
I don't know how I can resolve the problem :(
I try to invite my bot another time, but it doesn't work :(
The error message who makes problems :
node:events:491
throw er; // Unhandled 'error' event
^
TypeError: Cannot read properties of undefined (reading 'commands')
at Client.<anonymous> (/home/container/index.js:72:51)
at Client.emit (node:events:513:28)
at WebSocketManager.triggerClientReady (/home/container/node_modules/discord.js/src/client/websocket/WebSocketManager.js:385:17)
at WebSocketManager.checkShardsReady (/home/container/node_modules/discord.js/src/client/websocket/WebSocketManager.js:368:10)
at WebSocketShard.<anonymous> (/home/container/node_modules/discord.js/src/client/websocket/WebSocketManager.js:194:14)
at WebSocketShard.emit (node:events:513:28)
at WebSocketShard.checkReady (/home/container/node_modules/discord.js/src/client/websocket/WebSocketShard.js:511:12)
at WebSocketShard.onPacket (/home/container/node_modules/discord.js/src/client/websocket/WebSocketShard.js:483:16)
at WebSocketShard.onMessage (/home/container/node_modules/discord.js/src/client/websocket/WebSocketShard.js:320:10)
at WebSocket.onMessage (/home/container/node_modules/ws/lib/event-target.js:199:18)
Emitted 'error' event on Client instance at:
at emitUnhandledRejectionOrErr (node:events:394:10)
at process.processTicksAndRejections (node:internal/process/task_queues:84:21)
Node.js v18.12.0
The default code :
const { Client, GatewayIntentBits, Message, version, MessageFlags } = require("discord.js");
const { SlashCommandBuilder} = require("#discordjs/builders");
const { EmbedBuilder } = require('discord.js');
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMessages
]
})
//const { REST, Routes } = require('discord.js');
const {clientId, skorflexID, guildId, token, hostRole, multiplayerAnnouncementRole, fortniteLogo, rebootLogo, basicFortniteImage, sept, un, quatre, trois, modoID } = require('./config.json');
const announce = new SlashCommandBuilder()
.setName("announce")
.setDescription("This command will send a embed message to announce your hosting !")
.addStringOption(option => option
.setName("version")
.setDescription("Put the version of Fortnite you want to host")
.setRequired(true))
.addStringOption(option => option
.setName("radmin_ip")
.setDescription("Put your Radmin IP here (without the 'open')")
.setRequired(true));
const clear = new SlashCommandBuilder()
.setName("clear")
.setDescription("This command will delete a number of messages in one second !")
.addIntegerOption(option => option
.setName("number")
.setDescription("Put the number of messages who will be deleted !")
.setRequired(true))
const say = new SlashCommandBuilder()
.setName("say")
.setDescription("The bot will say your message")
.addStringOption(option => option
.setName("message")
.setDescription("Type your message !")
.setRequired(true))
const thumbnail = new SlashCommandBuilder()
.setName("thumbnail")
.setDescription("The bot send you the thumbnail of a YouTube video")
.addStringOption(option => option
.setName("id")
.setDescription("You can find the ID in the link after the << watch?v= >>")
.setRequired(true))
client.on("ready", async () => {
client.guilds.cache.get("1027595307187441664").commands.create(thumbnail);
client.guilds.cache.get(guildId).commands.fetch();
client.guilds.cache.get(guildId).commands.cache.map(command => {
command.delete();
});
console.log("Le bot est lancé et prêt à l'utilisation !");
});
client.on("interactionCreate", interaction => {
if(interaction.isCommand()){
// announce ou announcement
if(interaction.commandName === "announce" || interaction.commandName === "announcement"){
let version1 = interaction.options.getString("version")
let radmin_ip1 = interaction.options.getString("radmin_ip")
let image = basicFortniteImage;
if( version1 != undefined && radmin_ip1 != undefined ){
if(version1 ==="7.30" || version1 ==="7.3" || version1 ==="7.2"|| version1 ==="7.1"|| version1 ==="7"){
image = sept;
}else if(version1 == "1.7.2"){
image = un;
}else if(version1 =="3.5"){
image = trois;
}else if(version1 =="4.5"){
image = quatre;
}
const exampleEmbed = new EmbedBuilder()
.setColor(0xFFA3F8)
.setTitle("**Multiplayer Announcement**")
.setDescription("<#"+interaction.user.id+"> is hosting rn in **"+ version1 + "**\n\n - To join, write this in the fortnite console : \n\n> `open "+ radmin_ip1 +"`\n\n To open the fortnite console you need to press the ² button or if it's doesn't work press ` ")
.setImage(image)
.setFooter({ text: 'Hosted with Reboot Launcher', iconURL: rebootLogo})
.setThumbnail(fortniteLogo)
.setTimestamp()
.setFields({name: "To join", value: 'you need to be connected on **RADMIN VPN**'})
if(interaction.member.roles.cache.some(e => e.id == hostRole)){
interaction.channel.send("<#&"+multiplayerAnnouncementRole+">")
interaction.reply({embeds: [exampleEmbed]});
}else{
interaction.reply({ content: "You don't have the Host role !", ephemeral: true });
}
}
}
if(interaction.commandName === "clear"){
var number = interaction.options.getInteger("number")
if(interaction.member.roles.cache.some(e => e.id == modoID)){
if(number >= 1 && number <= 100){
interaction.channel.bulkDelete(number);
interaction.reply({content: number + " messages has been deleted correctly !", ephemeral: true});
}else{
interaction.reply({content: "To use the clear command, your number will be over 1 and under 100 ! Please retry", ephemeral: true});
}
}
}
if(interaction.commandName === "say"){
let message2 = interaction.options.getString("message");
if(interaction.member.roles.cache.some(e => e.id == modoID)){
interaction.reply({content: "."})
interaction.deleteReply();
interaction.channel.send({content: message2})
}else if(interaction.member.roles.cache.some(i => i.id != modoID)){
interaction.reply({content: "You are not a moderator !", ephemeral: true})
}
}
if(interaction.commandName === "thumbnail"){
var ytID = interaction.options.getString("id");
interaction.reply({content: "."})
interaction.deleteReply();
interaction.channel.send({content: "https://img.youtube.com/vi/"+ ytID +"/maxresdefault.jpg"})
}
}
})
client.login(token);
it's referring to this line here:
client.guilds.cache.get("1027595307187441664").commands.create(thumbnail);
Basically client.guilds.cache.get("1027595307187441664") is undefined and did not return a result.

Having problems using weather-js

Some monthes ago I followed a tutorial to code a bot that shows weather forecast depending on a stated location. This bot is using weather-js package, but since recently, no matter if I host my bot or launch it through the console, it's working when it wants to, and not working for some locations.
Here is what contains my index.js :
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.on("ready")....
.....
client.on('messageCreate', async message => {
if (!message.content.startsWith(prefix)) return;
let args = message.content.slice(prefix.length).split(" ");
let command = args.shift().toLowerCase()
if (command === "weather") {
client.commands.get("weather").execute(message, args, Discord, weather)
}
});
and what my weather.js contains:
var weather = require('weather-js');
const Discord = require('discord.js');
module.exports = {
name: 'weather',
description: "Used to get the weather of a place",
execute(message, args, Discord, weather) {
const city = args[0]
weather.find({search: args.join(" "), degreeType: "C"}, function(error, result){
if (error) return message.channel.send(error)
if (!city) return message.channel.send("You must specify a location please!")
if (result === undefined || result.length === 0) return message.channel.send("**Invalid location**")
let current = result[0].current
let location = result[0].location
const embed = new Discord.MessageEmbed()
.setTitle(`Weather forecast for ${current.observationpoint}`)
.setDescription(current.skytext)
.setThumbnail(current.imageUrl)
.setColor("RANDOM")
.setTimestamp()
.addField("Temperature: ", current.temperature + "°C", true)
.addField("Wind Speed: ", current.winddisplay, true)
.addField("Humidity: ", `${current.humidity}%`, true)
.addField("Timezone: ", `UTC${location.timezone}`, true)
message.channel.send({ embeds: [embed]});
})
}
}
I always got that same error when it doesn't work:
throw new DiscordAPIError(data, res.status, request);
^
DiscordAPIError: Cannot send an empty message
at RequestHandler.execute (/home/container/node_modules/discord.js/src/rest/RequestHandler.js:350:13)
at processTicksAndRejections (node:internal/process/task_queues:96:5)
at async RequestHandler.push (/home/container/node_modules/discord.js/src/rest/RequestHandler.js:51:14)
at async TextChannel.send (/home/container/node_modules/discord.js/src/structures/interfaces/TextBasedChannel.js:175:15) {
There's even some locations that were working before, but that suddenly stopped working for any reason!
Has someone had the same problems with weather-js, or is it coming from the code?
Thank you by advance!
One of your line on embed should be a null. That's why its throwing an error. To prevent this. You can use an OR operator.
const embed = new Discord.MessageEmbed()
.setTitle(`Weather forecast for ${current.observationpoint || "NO DATA"}`)
.setDescription(`${current.skytext || "NO DATA"}`) //Using a direct call can cause an error.
.setThumbnail(current.imageUrl) //If this part is the culprit let me know
.setColor("RANDOM")
.setTimestamp()
.addField("Temperature: ", `${current.temperature || "NO DATA"} °C`, true)
.addField("Wind Speed: ", `${current.winddisplay || "NO DATA"}`, true)
.addField("Humidity: ", `${current.humidity || "NO DATA"}%`, true)
.addField("Timezone: ", `UTC${location.timezone || "NO DATA"}`, true)
message.channel.send({ embeds: [embed]});
The || symbols is a OR operator.

Discord bot can not read files with commands

I put this into my code:
const pmie = require("./commands/pmie.js");
and I made directory commands and put file "pmie.js" in there
This is code in file pmie.js:
const Disocrd = require("discord.js");
const client = new Disocrd.Client();
const prefix = ""
client.on("message", (message)=>{
if(!message.content.startsWith(prefix)) return;
if(message.content.startsWith(prefix + "pmie")){
let author = message.member;
let role = message.guild.roles.find('name', "Founder");
if(author.roles.has(role.id)){
message.reply("You have Permission.");
return
}else{
message.reply("You don't have permission");
}
}
})
But bot does not do anything when I use "pmie" command, what's wrong?
To fix that you would need something like this.
pmie.js:
module.exports = function (client, message, Discord, prefix) {
if(!message.content.startsWith(prefix)) return;
if(message.content.startsWith(prefix + "pmie")){
let author = message.member;
let role = message.guild.roles.find('name', "Founder");
if(author.roles.has(role.id)){
message.reply("You have Permission.");
return
}else{
message.reply("You don't have permission");
}
}
Your main javascript file:
client.on('message', message => {
const pmie = require("./commands/pmie.js")
pmie(client, message, Discord, prefix)
})
Hopefully this solves your issue.

im new to making discord bots with node.js, i am having trouble with an error, it says that message is not defined in line 14 and 18

const Discord = require('discord.js');
const client = new Discord.Client()
const prefix = '+';
client.once('ready' , () => {
console.log('MemeStrifer is online')
});
client.on('message', message => {
if(message.content.startsWith(prefix) ||message.author.bot) return;
const args = message.content.slice(prefix.lenght).split(/+/);
const command = args.shift().toLowerCase();
if(command === 'blackhumour'){
message.channel.send('What is the difference between a kid and a bowling ball? when you put your fingers in one it doesnt scream');
} else if (command === 'sex') {
message.channel.send('no you f***ing pervert');
}
});
client.login('***');
Sorry if I am making any stupid errors, I just started yesterday by a YouTube video.
here,try this:
client.on('message', message =>{
if(message.content.startsWith(prefix) ||message.author.bot) return;
const args = message.content.slice(prefix.lenght).split(/+/);
const command = args.shift().toLowerCase();
if(command === 'blackhumour'){
message.channel.send('What is the difference between a kid and a bowling ball? when you put your fingers in one it doesnt scream');
} else if(command === 'sex'){
message.channel.send('no you fucking pervert');
}
});

Discord.js TypeError: Cannot read property 'prefix' of undefined

I get the following error...
Error: connect ECONNREFUSED 127.0.0.1:5432
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1146:16)
(node:8232) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'prefix' of undefined
When using a command from my bot. I think the issue is with the bot's main file.
The following code block is where I believe the error is coming from.
function startsWithPrefix(str, prefix) { if (str.slice(0, prefix.length).toLowerCase() == prefix.toLowerCase()) return true; }
// Execute when the bot sees a message
client.on('message', async msg => {
// Initialize guild settings on first message
if (msg.guild && !Settings[msg.guild.id]) {
const pool = new Pool();
try {
const res = await pool.query('SELECT prefix FROM settings WHERE guild_id = $1', [msg.guild.id]);
if (res.rows[0]) { Settings[msg.guild.id] = res.rows[0]; }
else {
Settings[msg.guild.id] = {
prefix: 'a!' // Default setting
};
}
} catch (err) { console.log(err.stack); }
finally { pool.end(); }
}
// Exit if msg doesn't start with prefix
if (msg.guild && !startsWithPrefix(msg.content, Settings[msg.guild.id].prefix)) { return; }
// Exit if msg was sent by a bot
if (msg.author.bot) { return; }
// Exit + Reply with a helpful message if msg was dm-ed to this bot
if (msg.channel.type == 'dm') { return await msg.reply(`I got nothin' for ya buddy :pensive:\nI think you meant to type that in the **Among Us LFG** server :+1:`); }
// Separate the command from the arguments
const words = msg.content.split(' ');
const cmdName = words[0].toLowerCase().slice(Settings[msg.guild.id].prefix.length);
const cmd = client.cmds.get(cmdName) || client.cmds.get(client.aliases.get(cmdName));
const args = words.slice(1);
// Run the command
if (cmd) cmd.run(client, msg, args);
});
// Start the bot
client.login(discordToken);
EDIT: seems like Settings[msg.guild.id] is undefined, However I define it as
let Settings = {};
exports.Settings = Settings;
at the start of the code dunno whats wrong
I think you can try to define the prefix with a const like this:
const prefix = '!'

Resources