Discord.js mongoose registering 2 warnings instead of one - discord.js

I am having issues across all the commands that share the same system as this one below.
All commands like ban, mute, kick are identical to this one and act the same in the mongoose part.
Take a look below, in the given code block.
const warnDoc = new WarningModel({
guildID: message.guild.id,
memberID: member.id,
warnings: [reason],
moderator: [message.member.id],
date: [Date.now()],
})
warnDoc.warnings.push(reason)
warnDoc.moderator.push(message.member.id)
warnDoc.date.push(Date.now())
await warnDoc.save().catch(err => console.log(err))
message.delete(message.author);
const logs = message.guild.channels.cache.find(channel => channel.name === "albot-mod-system");
if (!logs)
return console.log(`No logs channel exists in ${message.guild.name}`)
let warnembed = new Discord.MessageEmbed()
.setTitle(`Moderation | Audit Log`)
.addField("**Member**", `${member}`)
.addField("**Action**", "Warn")
.addField("**Reason**", `${reason ? `${reason}` : ''}`)
.addField("**Warning Count**:", `${warnDoc.warnings.length}`)
.setTimestamp(message.createdAt)
.setFooter(message.member.displayName, message.author.displayAvatarURL({ dynamic: true }))
.setColor(`#000000`)
logs.send(warnembed);
member.send(`You were warned in **${message.guild.name}** for: **${reason}**.`);
let warnEmbed2 = new MessageEmbed()
.setAuthor(`Moderation`)
.setDescription(`${member} has been warned successfully with the reason: ${reason}`)
.setTimestamp(message.createdAt)
.setFooter(message.member.displayName, message.author.displayAvatarURL({ dynamic: true }))
.setColor(`#000000`)
message.channel.send(warnEmbed2);
}
}
This is my warn command and when i run it, it normally gives 1 warning, but instead registers two. This issue came out of nowhere and it is confusing.
Anyone know the root issue of this?
Stuff ive tried:
Try a older mongoose version, no luck.
Play around with the mongoose parts in the code, no luck.
Revert to older versions of the command, no luck.
I honestly do not know what is causing this.

You're initializing WarningModel with a warnings array (warnings: [reason]) and pushing to it again with the same reason. Remove the push call.
Remove
warnDoc.warnings.push(reason)
You should also remove the following lines since moderator and date values are set while initializing the document.
warnDoc.moderator.push(message.member.id)
warnDoc.date.push(Date.now())

Related

.awaitMessageComponent() in an ephemeral reply and then editing it

I have been trying to implement an interaction collector as per the discord.js guide, but the guide does not explain much of anything and the pieces I have puzzled together from other sources do not fit together. Here's the example from the guide:
message.awaitMessageComponent({ filter, componentType: 'SELECT_MENU', time: 60000 })
.then(interaction => interaction.editReply(`You selected ${interaction.values.join(', ')}!`))
.catch(err => console.log(`No interactions were collected.`));
It took me a day to figure out that you can define a message object like so:
message = await interaction.channel.send(content: 'text', components: >select menu<)
That works to run .awaitMessageComponent() and to grab the input from the select menu, however interaction.editReply() gives an error: INTERACTION_NOT_REPLIED
Moreover, I need it to be a reply anyway, however
message = await interaction.reply(content: 'text', components: >select menu<)
leaves message as undefined, so of course I cannot run .awaitMessageComponent() on it.
So I do not understand what I am supposed to do to do what that guide is doing.
I would very much appreciate any insight into this issue.
Unfortunately all other guides (usually on collectors) also start with a .send() message and most other resources go way over my head, as I have no real background in coding/scripting.
EDIT:
As Malik Lahlou points out, you can assign the reply by including the fetchReply:option, like so:
message = await interaction.reply({ components: [select menu], fetchReply: true })
However that still does not allow the guide's code to run (error INTERACTION_NOT_REPLIED, so after some more research I finally found a way to use .awaitMessageComponent() and applied to the guide's example it would look like this:
await interaction.reply({ components: [select menu], ephemeral: true });
const collectedSelect = await interaction.awaitMessageComponent({ filter, componentType: 'SELECT_MENU', time: 60000 })
.then(interaction => interaction.editReply(`You selected ${interaction.values.join(', ')}!`))
.catch(err => console.log(`No interactions were collected.`));
Simple answer, add the fetchReply option when replying to the interaction :
const message = await interaction.reply({
// content : ...,
// components : ...,
fetchReply: true
})
Another way would be to use interaction.fetchReply after awaiting the reply but it's better to directly give it as a parameter so discord.js does this stuff for us :D Here's an example on the official discord.js guide

Code to remove role using command on discord.js (repl.it)

what code should I use to remove a specific role?
(I'm using repl.it and I'm new to it, there's no error, I just need a code. I have also tried doing this
if(message.content.toLowerCase() === ">mcroleremove") { let role2 = message.guild.roles.cache.find(role => role.name === "Flop SMP Members") message.member.role.remove(role2) message.channel.send('We may hope you to see again on the SMP!') }
No error have occurred but it doesn't work when I use the ">mcroleremove" command, even If I use the command, no errors have showed.
Thanks.
It probably didn't work because there is no role exactly named Flop SMP Members (maybe a typo or a none-trimmed space). Try using the role's id instead. It's much more efficient and useful ! (Or maybe you don't have the GUILD_MEMBERS)
First check if you have it :
const client = new Discord.Client({ intents: [
"GUILD_MEMBERS",
"GUILD_MESSAGES"
"GUILDS"
]})
If, even after using that it doesn't work, then try fetching the role:
client.on('message',async message =>{
if(message.content.toLowerCase() === ">mcroleremove"){
let role = await message.guild.roles.fetch("id of your role")
return message.member.roles.remove(role2)
.then(() => message.reply('We may hope you to see again on the SMP!'))
.catch(console.error)
}
})

cant make an error statement to dm users discord.js

I tried putting a catch error if the user didn't get the message but for some reason, I get an error
client.on('guildMemberAdd', member => {
const linkId = pool.createLink(member.id);
const embed = new Discord.MessageEmbed()
.setTitle('reCAPTCHA Verification')
.setDescription(`To gain access to this server you must solve a captcha. The link will expire in 15 minutes.\nhttp://${domain == '' ? 'localhost:8050' : domain}/verify/${linkId}`)
.setColor('YELLOW');
member.send(embed)
} catch (e) {
console.log(`Error adding role to user ${discordId}.`)
}
get an error missing ","
added "," }, catch (e) {
and then I get Argument expression expected.
The Problem
The error is probably because your code is not formatted properly at all? You have a function member => {} and then you have a catch immediately following the function, and you never even close your client.on() parentheses.
Your program properly understanding entirely incorrect syntax is as infeasible as speaking gibberish to someone who speaks a different language and expecting them to understand you. When learning a new language, you need to be aware of new grammar rules, vocabulary, and more that may differ immensely from your own primary language. This is true of programming languages as well; javascript is very flexible, but your program will not be able to decipher immensely inaccurate syntax (which is the equivalent of gibberish to the program).
Please try to learn more about try/catch statements, javascript functions, syntax errors, and proper syntax. This is an immensely simple formatting issue, and questions like this one really should not be present on StackOverflow. Looking at some basic javascript tutorials, doing some quick research (perhaps even looking at some bot examples), and/or doing a single Google search could have solved your problem within seconds.
The Solution
This is the proper, more accurate syntax:
client.on('guildMemberAdd', member => {
const linkId = pool.createLink(member.id);
const embed = new Discord.MessageEmbed()
.setTitle('reCAPTCHA Verification')
.setDescription(`To gain access to this server you must solve a captcha. The link will expire in 15 minutes.\nhttp://${domain == '' ? 'localhost:8050' : domain}/verify/${linkId}`)
.setColor('YELLOW');
member.send(embed).catch(() => {console.log("Couldn't send message.")});
});
This is, of course, assuming that the formatting was the actual issue and you didn't just format it poorly when adding the code to your question. If it was only poorly formatted in your question and properly formatted in your actual code, then the issue isn't even present in the code you provided (in which case your question cannot even be answered, unless you provide the proper code).
i am getting an error
DiscordAPIError: Cannot send messages to this user
at RequestHandler.execute (C:\Users\Administrator\Desktop\GRPIL-BOT\src\DiscordVerification-master\DiscordVerification-master\node_modules\discord.js\src\rest\RequestHandler.js:154:13)
at processTicksAndRejections (node:internal/process/task_queues:93:5)
at async RequestHandler.push (C:\Users\Administrator\Desktop\GRPIL-BOT\src\DiscordVerification-master\DiscordVerification-master\node_modules\discord.js\src\rest\RequestHandler.js:39:14) {
method: 'post',
path: '/channels/790342794140975115/messages',
code: 50007,
httpStatus: 403
}
which
try {
const linkId = pool.createLink(member.id);
const embed = new Discord.MessageEmbed()
.setTitle('reCAPTCHA Verification')
.setDescription(`To gain access to this server you must solve a captcha. The link will expire in 15 minutes.\nhttp://${domain == '' ? 'localhost:8050' : domain}/verify/${linkId}`)
.setColor('YELLOW');
member.send(embed)
} catch (e) {
console.log(`Error adding role to user ${discordId}.`)
}
should avoid the error

How do you find a channel using its name in Discord.js?

I tried using this to find a channel named "information" and to send a message in it:
let channel = message.guild.channels.cache.find(channel => channel.name.toLowerCase() === 'information')
channel.send('test')
And using that code resulted in this error:
let channel = message.guild.channels.cache.find(channel => channel.name.toLowerCase() === 'information')
^
TypeError: message.guild.channels.cache.find is not a function
I tried npm install discord.js to update the package, but it still didn't work. I also tried client.channels.cache.find, But it ended up receiving the same error. Am I doing something wrong here?
According to the docs you're doing it right ...
but according to reddit, there is no need to call cache and you can just call :
let channel = message.guild.channels.find(
channel => channel.name.toLowerCase() === "information"
)
this corresponds to what i am doing with my bot, and this worked a few months ago
guild.channels.array().filter(c => c.name === 'General')
Seems like guild.channels is already a collection, don't know if it's a mistake in the Documentation or if it's a really recent version that changed that ...
[edit] found the problem
in the documentation, there are two versions (up in the toolbar) v12 (default) and v11
it seems like they added the .cache in the v12, but maybe this one is not on npm already.
they have an alert about breaking changes that links to this page
where they explain how to switch to v12 https://discordjs.guide/additional-info/changes-in-v12.html
You have to write it like this:
let channel = message.channel.guild.channels.cache.find((channel) => channel.name.toLowerCase() === `information`
I think it didn't work because you need brackets around the variable channel.

How can I find the reason for a ban through discord audit logs? (Using Discord.js)

What I'm trying to do is make a log for my bot, (you know, something to record server events as they happen), and I've been doing alright so far, but I just can't seem to figure out how to get the reason for a ban/kick or whatever else can record reasons. I've checked the documentation, and I just can't really figure out what some of the stuff there means. There isn't really code to show off, because I have no clue where to start here, and it's about time I ask somewhere for help.
Edit: I do know where to start, I can find the audit log entry, but I can't get the reason for the entry
You can use guild.fetchAuditLogs()
const guild = client.guilds.cache.get('Guild_ID')
const fetchedBan = await guild.fetchAuditLogs({ user: 'User_ID), type: 'MEMBER_BAN_ADD' })
You can also use message.guild instead of const guild = client.guilds.cache.get('Guild_ID')
To get the reason for the latest ban of that member
const banReason = fetchedBan.entries.first().reason

Resources