How can I attach a file to a message? - discord.js

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}`)
}

Related

How do i add a commands where it unban an user id from all the servers the bot is in

So i have tried this but it says "ReferenceError: member is not defined", can you guys help me fixing it please, i already have a command to ban someone from all the servers the bot is in but i don't know how to do for unban-all, so here is my code so you can guys take a look, i'm pretty new in discord.js so sorry if my code looks bad
const { MessageEmbed } = require('discord.js');
/**
*
* #param {import('discord.js').Client} client
* #param {import('discord.js').Message} message
* #param {string} args
*
*/
exports.run = async (client, message, args) => {
const targetID = args[0];
const reason = args.slice(0).join(' ')
const dm_messagev2 = new MessageEmbed()
.setColor("#02fa49")
.setTitle(":no_entry: BAN :no_entry:")
.addField("**Message :**", `${member.user.tag} Vous avez été déban-all de Storm-Community.`)
.addField("**Raison : **", `${reason || 'Aucune raison définie.'}`)
.addField("**Autheur : **", `${message.author.username}.`)
.setFooter("Bot by Roka | 1.1")
member.send({ embeds: [dm_messagev2]})
setTimeout(function(){
client.guilds.cache.forEach(a => a.members.unban(targetID)).then(() => {
const embedv3 = new MessageEmbed()
.setColor("#02fa49")
.setTitle(":white_check_mark: Succès")
.addField("**Message :**", `${member.user.tag} as été déban-all de la communauté.`)
.addField("**Raison : **", `${reason || 'Aucune raison définie.'}`)
.addField("**Auteur : **", `${message.author.username}.`)
.setFooter("Bot by Roka | 1.1")
message.channel.send({ embeds: [embedv3]});
});
}, 2000);
/* const dmembed = new MessageEmbed()
.setTitle("You have been banned from all the servers i am in")
.setDescription('Your Crime was `${reason}`. If you want to apeal, You may join [Appeal Server by Clicking here](https://discord.gg/ZWWYy37atN)')
.setColor("#FF0000")
message.targetID.send(embed)*/
};
exports.info = {
name: 'unbanall', // Command name
description: 'Clears a specific amount of messages in a channel', // Command description
category: 'mod',
icon: '🧹',
usage: '<count>' // Command usage
};
exports.config = {
args: true, // Whether this command should require one or more arguments
guildOnly: true, // Whether the command should be used in a guild or not
permissions: {
user: ['MANAGE_MESSAGES'], // Required guild permissions for the user to use this command (must be a valid permission flag)
bot: ['MANAGE_MESSAGES'], // Required guild permissions for the bot to run this command (must be a valid permission flag)
},
aliases: ['uball', 'unban-all', 'débanall', 'déban-all', 'deban-all', 'debanall'], // Aliases
disabled: false, // Whether this command is disabled or not
};```
It looks as if your Reference Error is coming from
member.send({ embeds: [dm_messagev2]})
I'm not quite sure why you need this for an unban as it seems to be a notice of a ban. Assuming its just leftover code...
As for unbanning all your banned members, you can access these bans through this method!
guild.bans.fetch();

How to not process commands in discord.py if the channel if private?

My code :
#commands.Cog.listener()
async def on_message(self, message):
if message.author.id == self.bot.user.id:
return
if message.channel.type == discord.ChannelType.private:
await message.channel.send("Vous devez être dans un serveur pour realiser cette commande !")
return
but it doesn't work, it's recognise that is was a private channel and it send the right message but it also process the command and send the answer ...
Don't include bot.process_commands(message) in the if code block which runs if the channel is private. Try this:
#commands.Cog.listener()
async def on_message(self, message):
if message.author.id == self.bot.user.id:
bot.process_commands(message)
return
if message.channel.type == discord.ChannelType.private:
await message.channel.send("Vous devez être dans un serveur pour realiser cette commande !")
return
#Don't add bot.process_commands(message) here.
Don't add bot.process_commands(message) outside the if block because if you do then it will run even if it is private.

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

Discord.js Errors in pay command

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

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
}

Resources