Discord.js Errors in pay command - discord

I'm facing a problem for a few days in the "pay" command in my little economy system, what I'm trying to do is, when executing the command for example "pay #user 2k" it recognizes as just "2 coins ", how can I make a shortcut to 2k answer for 2000 and so on? I'll leave the code snippet below for understanding, and if you have any ideas it will be very helpful!
const user =
this.client.users.cache.get(args[0]) || message.mentions.users.first();
const doc = await this.client.database.users.findOne({
idU: message.author.id,
});
const money = parseInt(args[1]);
if (!user)
return message.quote(
`Você deve mencionar para quem deseja enviar dinheiro.`
)
if (!money)
return message.quote(
`Você deve inserir quanto deseja enviar.`
)
if (user.id === message.author.id)
return message.quote(
`Você não pode enviar dinheiro para si mesmo.`
)
if (isNaN(money) || money <= 0)
return message.quote(`Dinheiro inválido ou não reconhecido.`);
if (money > doc.bank)
return message.quote(
`Você não me informou a quantidade de dinheiro ou não possui essa quantia!`
)
const target = await this.client.database.users.findOne({ idU: user.id });
```

Here is a little translator:
function translateNum(str) {
var nums = str.match(/[0-9]+[kmbt]/i);
if(!nums) return parseInt(str);
var check = nums[0].toLowerCase();
var num = parseInt(check);
if(check) {
var letter = check.slice(check.length-1);
if(letter === 'k') return num*1000;
if(letter === 'm') return num*1000000;
if(letter === 'b') //... until t (trillion) if you want that
return 0; //in case an error occurs
} else {
return parseInt(str);
}
}
And now just run translateNum('2k') and it should work and return 2000 instead of 2. Any errors? Tell me!
Explanation:
str would be the number string of course, and when you put str.match(), it checks for a number, or multiple numbers followed by either k, m, b or t. Then, the rest gives out different responses depending on the letter. If there is no match with str.match(), it returns the string as a number. Also, the i modifier makes it case insensitive, so you can do 2K, or 2k

Related

Cannot read properties of null (reading 'hasPermission') discord.js

I have coded a discord bot but i have a problem, when i execute my command it shows me a error.
Error:
if (!message.member.hasPermission("ADMINISTRATOR"))
TypeError: Cannot read properties of null (reading 'hasPermission')
Code where the error comes up:
if (command === "add") {
if (!message.member.hasPermission("ADMINISTRATOR"))
return message.reply("Desoler, vous ne pouvez pas effectuer cette commande car vous n'ette pas administrateur");
var fs = require("fs");
let messageArray = message.content.split(" ");
let args = messageArray.slice(1);
var account = args[0]
var service = args[1]
const filePath = __dirname + "/" + args[1] + ".txt";
fs.appendFile(filePath, os.EOL + args[0], function (err) {
if (err) return console.log(err);
message.channel.send("Terminer !")
});
I already tried to replace hasPermission with permissions.has but it still does not work.
Define your client like that
const { Client } = require('discord.js');
const client = new Client({ intents: 32767 });
Also make sure intents are enabled in the developer portal and use GuildMember#permissions.has

"Cannot read property 'cache' of undefined" when I check a member role

I want to make a mute command for my Discord bot but that create errors:
C:\Program Files\nodejs\node.exe .\index.js
|------ Bot on ------|
index.js:22
Uncaught TypeError: Cannot read property 'cache' of undefined
No debugger available, can not send 'variables'
Process exited with code 1
I want to check if the user who is mentionned has already the mute role and if the executor has an admin role. But that create this error.
My code:
bot.on("message", async message => {
if(message.content.startsWith(prefix + "mute")){
let User = message.mentions.users.first();
let time = message.content.split(" ").slice(2)
let reason = message.content.split(" ").slice(3)
if(!reason){ let reason = "aucune"}
if(!time || !User) return message.reply("Veuillez entrer une commande valide !\n" + prefix + "mute #user <temps> <raison>")
let dUser = User.id
if(dUser == message.author.id) return message.reply("Vous ne pouvez pas vous mute vous même !")
if(isNaN(time[0]) || time < 1) return message.reply("Veuillez entrer une valeur chiffrée et supérieur à 1 !")
let muterole = "793840735266013205"
che
if(User.roles.cache.has(muterole)) return message.reply("Ce membre est déjà mute !")
if(!message.author.roles.cache.has("783758067111428126" || "783758066138218577")) return message.reply("Vous n'avez pas la permission d'utiliser cette commande !")
if(User.roles.cache.has("783758067111428126" || "783758066138218577")) return message.reply("Vous ne pouvez pas mute un membre du staff !")
let emb = new Discord.MessageEmbed()
.setTitle(Mute)
.setDescription(User.username + " a bien été mute par " + message.author.username + " pendant " + time[0] + " secondes pour la raison suivante : " + reason)
.setColor("#E74C3C")
pendant " + time[0] + " secondes pour la raison suivante : " + reason)
User.roles.add(muterole)
setTimeout(() => {
User.roles.remove(muterole)
let reply = new Discord.MessageEmbed()
.setDescription(User + " a bien été unmute !")
.setColor("#E74C3C")
message.guild.channels.cache.get("795063422386569298").send(reply)
let mp = new Discord.MessageEmbed()
.setDescription("Vous avez été unmute de " + guild)
.setColor("#E74C3C")
message.author.send(mp)
}, time[0] = 60000
)}
})
Don’t worry about French words.
Your code is not going to do what you want it to do, because you messed up some parts. User will be the first mentioned user that can be found in your arguments. So if you mention the user right at the first position of your arguments, it will be at index 0. That is because the arguments get stored in an array and arrays always starts at index 0. That means now your following arguments have to be at index 1 and 2. So you can change your time and reason into:
let time = message.content.split(" ").slice(1);
let reason = message.content.split(" ").slice(2).join(" ");
Make sure you use .join(" ") at your reason, that will allow you to add multiple words for the reason. The next mistake is in the if-statement where you ask if there is no reason. You create a new variable inside the statement, which makes no sense. You just have to do:
if(!reason){ reason = "aucune"; }
Now if there is no reason provided the reason will be aucune.
If you want to ask if a user has the mute role already, you can use a GuildMember Object. That would look like this:
if(message.guild.member(User).roles.cache.has(muterole)) return message.reply("Ce membre est déjà mute !")
After that if-statement you ask if a user has certain roles and if he don't has this roles, he has no permission. Something like that should always be the first line of code of such a command and it should look like this:
if(!message.author.roles.cache.has("783758067111428126") || !message.author.roles.cache.has("783758066138218577")) return message.reply("Vous n'avez pas la permission d'utiliser cette commande !")
The same procedure with the following if-statement:
if(User.roles.cache.has("783758067111428126") || User.roles.cache.has("783758066138218577")) return message.reply("Vous ne pouvez pas mute un membre du staff !")
Then in your embed you are using time[0], although time is not an array. It just has to be time.
Your code should look like this now:
bot.on("message", async message => {
if(message.content.startsWith(prefix + "mute")){
if(!message.author.roles.cache.has("783758067111428126") || !message.author.roles.cache.has("783758066138218577")) return message.reply("Vous n'avez pas la permission d'utiliser cette commande !")
let User = message.mentions.users.first();
if(User.roles.cache.has("783758067111428126") || User.roles.cache.has("783758066138218577")) return message.reply("Vous ne pouvez pas mute un membre du staff !")
let time = message.content.split(" ").slice(2)
let reason = message.content.split(" ").slice(3)
if(!reason){ reason = "aucune"; }
if(!time || !User) return message.reply("Veuillez entrer une commande valide !\n" + prefix + "mute #user <temps> <raison>")
let dUser = User.id
if(dUser == message.author.id) return message.reply("Vous ne pouvez pas vous mute vous même !")
if(isNaN(time) || time < 1) return message.reply("Veuillez entrer une valeur chiffrée et supérieur à 1 !")
let muterole = "793840735266013205"
if(message.guild.member(User).roles.cache.has(muterole)) return message.reply("Ce membre est déjà mute !")
let emb = new Discord.MessageEmbed()
.setTitle(Mute)
.setDescription(User.username + " a bien été mute par " + message.author.username + " pendant " + time + " secondes pour la raison suivante : " + reason)
.setColor("#E74C3C")
User.roles.add(muterole)
setTimeout(() => {
User.roles.remove(muterole)
let reply = new Discord.MessageEmbed()
.setDescription(User + " a bien été unmute !")
.setColor("#E74C3C")
message.guild.channels.cache.get("795063422386569298").send(reply)
let mp = new Discord.MessageEmbed()
.setDescription("Vous avez été unmute de " + message.guild)
.setColor("#E74C3C")
message.author.send(mp)
}, time
)}
})

send error message or without permission on the channel

My bot is having some problems with some servers, the problem is Missing Permissions, it happens when the bot tries to do a function that it does not have permission on the server, and to alert the users of the bot that it does not have permission to execute the command on the server, I put 2 functions so that it warns the member that it does not have enough permission, but it is not advancing because the bot does not send the message on the channel saying that it does not have permission
The first function where he tells the member that he is not allowed to create the invitation is
in if (!message.guild.member(bot.user).hasPermission('CREATE_INSTANT_INVITE')) { return message.channel.send('I am not allowed to create invitations.');}
And the second is
in } catch (e) { console.log(e) return message.reply(`The following error occurred :( \`${e.message}\` add the required permission \`MANAGE_INVITES\`.`);
const ms = require('parse-ms')
const { DiscordAPIError, MessageEmbed } = require("discord.js");
const { invalid } = require("moment");
module.exports = {
name: "jogar",
description: "Set the prefix of the guild!",
category: "economia",
run: async (bot, message, args) => {
if (!message.guild.member(bot.user).hasPermission('CREATE_INSTANT_INVITE')) { return message.channel.send('Eu não\ tenho permissão para fazer isso!');
}
const { chunk } = require('../../functionsss');
let guild = bot.guilds.cache.get("759003907858104350");
let emoji = guild.emojis.cache.find(emoji => emoji.name === 'loading');
let emoji2 = guild.emojis.cache.find(emoji => emoji.name === 'check');
if(!message.member.voice.channel) return message.reply(`Você precisa está conectado ao um canal de voz para procurar partida!`)
const voiceChannels = message.guild.channels.cache.filter(c => c.type === 'voice');
let count = 0;
const vo = message.member.voice.channel.members.size
for (const [id, voiceChannel] of voiceChannels) count += voiceChannel.members.size;
let membro = message.author;
let newInfo = args.join(' ');
if (!newInfo) return message.reply('Insira o codigo da sala do among! **a!jogar BCETYJ**');
if (newInfo.length > 6) return message.channel.send(`**Max \`6\` Caracteres permitidos!**`);
let newsInfo = chunk(newInfo, 42).join('\n');
let embed = new Discord.MessageEmbed();
try {
let channel = message.member.voice.channel;
channel.createInvite({
maxAge: 3600, // 0 = infinite expiration
maxUses: 10 // 0 = infinite uses
})
.then(invite=>{
embed
.setTitle(`${emoji} Procurando partida..`)
.setColor('RANDOM')
.setTimestamp()
.setDescription(`Pessoal <#${membro.id}> está procurando mais gente para jogar!
\n<:info:775212992895254548> **Informações:**
**・Canal:** ${channel}
**・Codigo:** ${newsInfo}
**・Jogadores:** ${vo}
\n[Entrar na partida](https://discord.gg/${invite.code})`)
.setThumbnail('https://attackofthefanboy.com/wp-content/uploads/2020/09/Among-Us-3.jpg')
message.channel.send(embed)
message.react("✅");
})
} catch (e) {
console.log(e)
return message.reply(`The following error occurred :( \`${e.message}\` add the required permission \`MANAGE_INVITES\`.`);
}}}```
I've had this problem before and I spent hours troubleshooting. I eventually figured out that it was the way that I was looking for permissions. Discord.js v12 has added many changes to this type of function. I suggest changing
(!message.guild.member(bot.user).hasPermission('CREATE_INSTANT_INVITE'))
to
(!message.guild.me.hasPermission("Create_Instant_Invite"){
//rest of your code
}

Why this bot is failing at 'user.hasPermission()'?

I developed a bot. This is my code:
const Discord = require('discord.js')
const client = new Discord.Client()
client.on('ready', () => {
console.log(`Bot ready!`)
})
const filterNum = (str) => {
const numericalChar = new Set(["|","&","!","?",":","<","=",">","(",")","/","*","-","+",".","0","1","2","3","4","5","6","7","8","9"])
str = str.split("").filter(char => numericalChar.has(char)).join("");
return str;
}
client.on('message',(msg)=>{
user = msg.author
msg1 = msg.content
msg1 = msg1.toLowerCase()
msg1 = msg1.replace(new RegExp(/[àáâãäå]/g),"a")
msg1 = msg1.replace(new RegExp(/[èéêë]/g),"e")
msg1 = msg1.replace(new RegExp(/[ìíîï]/g),"i")
msg1 = msg1.replace(new RegExp(/[òóôõö]/g),"o")
msg1 = msg1.replace(new RegExp(/[ùúûü]/g),"u")
msg1 = msg1.replace(new RegExp(/[ýÿ]/g),"y")
try{
if(msg.content.startsWith("/kick")){
if(user.hasPermission(['KICK_MEMBERS', 'BAN_MEMBERS'])){
member = msg.mentions.members.first()
if(member.hasPermission(['KICK_MEMBERS', 'BAN_MEMBERS'])){
msg.channel.send("No se puede kickear a un staff.")
}else{
member.kick().then((member) => {
msg.channel.send("Kickeado exitosamente.")
}).catch(() => {
msg.channel.send("Acceso denegado.")
})
}
}else{
msg.channel.send("/kick "+user)
}
}
}catch(e){
msg.channel.send(e.message)
}
if(msg.content.startsWith("/calc")){
try{
operation=msg.content.split("/calc")[1]
operation=filterNum(operation)
result=eval(operation)
msg.channel.send("```"+operation+"≡"+result+"```")
}catch(e){
msg.channel.send(e.message)
}
}
if(!msg.content.startsWith("/calc")&&!msg.content.startsWith("/kick")&&msg.content.startsWith("/")){
msg.reply(`
Comando desconocido. Aquí tienes la lista de comandos:
/kick miembro: Expulsa a un miembro de la sala.
/calc operación: Calcula una operación matemática.
`)
}
})
client.login('token')
And this is the error:
user.hasPermission is not a function
I tried to change it to another command and it didn't worked. I tried to show msg.author, and it's undefined, but strangely, msg.author.bot is defined as a boolean. It's weird. Looks like a problem with discord.js API. I cant show the token because someone can utilize my bot into his purposes, but, anywhere.
What can I do? Thanks for helping.
The hasPermission() function can only be used on a member object. So you need to change user = msg.author to user = msg.member.

How can I attach a file to a message?

I want my bot to forward a file to the mentioned user when using the command, the problem is that I don't know how to do it.
if (command === "file") {
if (message.channel.id != "700038969253167125") return;
message.delete();
message.channel.send(`> <#${message.author.id}> ✅`)
let filejoin = args.join(" ");
if (!filejoin)
client.channels.cache.get('700052786909282344').send(`:information_source: **|** Ha llegado un nuevo archivo (<#${message.author.id}>)\n\n"${filejoin}"`);
if (message.author.bot) return;
client.channels.cache.get('700052786909282344').send(`:information_source: **|** Ha llegado un nuevo archivo (<#${message.author.id}>)\n\n"${filejoin}"`).then(async m => {
});
}
You can send files using the .send() method.
As you stated in the comments of this answer, you want the file attached to the message containing the command to be sent to you. You can do that like so:
const user = client.users.cache.get("YOUR_ID")
if (message.attachments.array().length) {
message.attachments.forEach((attachment) => user.send({ files: [ attachment ] }))
user.send(`These files were sent by ${message.author.tag}`)
}

Resources