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

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.

Related

Send Token erc20 usign Web3.js( Private Key. Account unloked. SignTransaction )

If send to Avax but not my Erc20 Token. Thank you for your help
First we get the url of the rcp.
Then we create an instance of web3.js.
Then with our private key you create an account.
We create an instance of our contract by passing it the abi and the address of the contract as parameters.
We estimate the gas with estimateGas passing it an object that indicates the function of the abi that is going to be used, the address of the contract, to whom it is going to be sent.
We create a transfer object
We obtain the balance to know the initial balance
We sign the transaction with our private key
We send the transaction
We get the bottom line
My code
`
const transferToeknErc20 = async () => {
const amount = '1000000000000000';
const jsonInterface = [{"inputs":[],"stateMutability":....
const contractAddress = '0x7B9...';
const privateKeyWallet = '14f...';
const chainId = 43113;
const address_to = '0x86...';
//NODE
const NODE_URL = "https://api.avax-test.network/ext/bc/C/rpc";
//WEB3
const web3Global = new Web3( new Web3.providers.HttpProvider(NODE_URL));
//Creamos una cuenta con la llave privada
const account = web3Global.eth.accounts.privateKeyToAccount(privateKeyWallet);
//CONTRACT
const contract = new web3Global.eth.Contract(jsonInterface, contractAddress);
//////////////////////////////////////////////////////////////////////////////
let estimateGas = await web3Global.eth.estimateGas({
value: '0x0', // Only tokens
data: contract.methods.transfer(address_to, amount).encodeABI(),
from: account.address,
to: address_to
});
//////////////////////////////////////////////////////////////////////////////
const transactionObject = {
value:'0x0',
data:contract.methods.transfer(address_to, amount).encodeABI(),
from: account.address,
to: address_to,
gas:web3Global.utils.toHex(Math.round(estimateGas * 1.10)),
gasLimit:web3Global.utils.toHex(Math.round(estimateGas * 1.10)),
chainId,
}
//get balanace
let balance = await contract.methods.balanceOf(account.address).call();
console.log('balance init', balance)
//Sing
const signText = await web3Global.eth.accounts.signTransaction(transactionObject, privateKeyWallet);
//Send Transaction
const reciep = await web3Global.eth.sendSignedTransaction(signText.rawTransaction);
//get balanace
balance = await contract.methods.balanceOf(account.address).call();
console.log('balance end', balance)
return null;
///////////////////////////////////////////////////////////////////////////////////////
}
`

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

Economy leaderboard command: undefined

I am making a discord economy/currency bot, and this is the leaderboard command. It works, but whenever I run the command !leaderboard, I don't get any of the user's tags, I just get the undefined#0000. I would like my leaderboard command to show the users with the highest amount of currency.
const { MessageEmbed } = require('discord.js');
const db = require('quick.db');
module.exports = {
name: "leaderboard",
description: 'server\'s $ leaderboard',
aliases: ['lb'],
}
module.exports.run = async (message) => {
let money = db.all().filter(data => data.ID.startsWith(`money_`)).sort((a, b) => b.data - a.data);
if (!money.length) {
let noEmbed = new MessageEmbed()
.setAuthor(message.member.displayName, message.author.displayAvatarURL())
.setColor("BLUE")
.setFooter("No leaderboard")
return message.channel.send(noEmbed)
};
money.length = 10;
var finalLb = "";
for (var i in money) {
let currency1;
let fetched = await db.fetch(`currency_${message.guild.id}`);
if (fetched == null) {
currency1 = '🎱'
} else {
currency1 = fetched
}
if (money[i].data === null) money[i].data = 0
finalLb += `**${money.indexOf(money[i]) + 1}. ${message.guild.members.cache.get(money[i].ID.split('_')[1]) ? message.guild.members.cache.get(money[i].ID.split('_')[1]).tag : "undefined#0000"}** - ${money[i].data} ${currency1}\n`;
};
const embed = new MessageEmbed()
.setTitle(message.guild.name)
.setColor("BLUE")
.setDescription(finalLb)
.setTimestamp()
.setFooter('Command: !help for currency commands')
message.channel.send(embed);
}
Try following code:
let money = db.all().filter(data => data.ID.startsWith(`money_${message.guild.id}`)).sort((a, b) => b.data - a.data)
money.length = 10;
var finalLb = "";
for (var i in money) {
finalLb += `**${money.indexOf(money[i])+1}. ${client.users.cache.get(money[i].ID.split('_')[1]) ? client.users.cache.get(money[i].ID.split('_')[1]).tag : "Unknown User#0000"}** - ${money[i].data}\n`;
}
const embed = new Discord.MessageEmbed()
.setAuthor(`Global Coin Leaderboard!`, message.guild.iconURL())
.setColor("#7289da")
.setDescription(finalLb)
.setFooter(client.user.tag, client.user.displayAvatarURL())
.setTimestamp()
message.channel.send(embed);
I personally use above code for my bot and it works pretty well for me.
Try putting the client.login('token') at the bottom of your code. Maybe the bot can't find the user tag's because of that?

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
}

How to solve error "Invalid view" in registration function?

I am having an error during the registration of a recruiter for the application I am working for
here is the error I am having in the network while sending the form information :
code:500
error: "Invalid view."
message: "Erreur lors de la création du compte"
here is the code
public function personnal(AccountCreateRequest $request)
{
try {
$http = new \GuzzleHttp\Client;
$exists = false;
$userData = $request->input('user');
$userData['password'] = bcrypt($userData['password']);
$userData['gender'] = ($userData['title'] === 'M.') ? 'm' : 'f';
if (array_get($userData, 'ref')) {
$user = User::where('ref', $userData['ref'])->firstOrFail();
$user->fill($userData);
$exists = true;
} else {
$userData['ref'] = User::generateId();
$user = new User($userData);
}
$user->source = 'website';
$user->optin_platform = 1;
if ($user->role === 'seeker') {
$user->is_active = 1;
$user->save();
$seeker = new UserSeeker([
'registration_date' => Carbon::now(),
'available_in' => 1,
'token' => bin2hex(uniqid(rand())),
'resume_path' => $request->input('seeker.resume_path'),
'resume_date' => Carbon::now(),
]);
$seeker = $user->seeker()->save($seeker);
$seeker->location()->associate(Address::create($request->input('location')))->save();
} else {
$user->is_active = 0;
$user->save();
// $size = $request->input('company.size', $request->session()->get('info'));
$companyData = $request->input('company');
$company = Company::create($companyData);
$recruiter = $user->recruiter()->save(new UserRecruiter([
'company_id' => $company->id,
]));
}
DB::commit();
$this->json['response'] = ['ref' => $user->ref];
$this->json['code'] = $this->code['created'];
dd($this->json);
} catch (MissingParamsException $e) {
DB::rollback();
$this->setError($e, $e->getMessage(), 'missing');
} catch (\Exception $e) {
DB::rollback();
$this->setError($e, 'Erreur lors de la création du compte');
} finally {
return ($this->response());
}
I resolve my issue by changing the is_active parameters to 1

Resources