How to find out if the message author is an element of my mongo database - javascript

EDIT: THIS IS FIXED!
I apparently forgot to reroute my mongoose connection to my Atlas!
I'm making a premium feature in my bot, that allows users to play music. Only thing wrong is that I can't find out how to find the message author's id in the database!

.findOne() returns promise that will resolve to the document if it's found, otherwise null. This means you can simply check if it's not null, you don't need to check if the IDs are the same. That's already checked by Mongoose.
Don't forget that you need to await the results if you're using promises.
try {
const premiumMember = await premiumSchema
.findOne({ userID: message.author.id })
.exec();
if (!premiumMember) {
return message.reply('You are not a premium user!');
}
const VC = message.member.voice.channel;
if (!VC)
return message.reply(
'You are not in a VC! Please join one and redo the command!',
);
const connection = await VC.join();
const dispatcher = connection
.play(ytdl(args[0]))
.on('finish', () => {
VC.leave();
message.channel.send(`${message.author}, your song has ended!`);
})
.on('error', (error) => {
console.log(error);
message.channel.send('There was an error playing this song');
});
dispatcher.setVolumeLogarithmic(5 / 5);
} catch (err) {
console.log(err);
}

use await before query like this:
const id = await premiumSchema.findOne({
userID: message.author.id
})
after that implement the business logic with == if you want to check the type ===
if(id.userID == message.author.id) {
return message.reply('You are not a premium user!')
}

Related

MongoDB findOneAndDelete() will not delete the specified query-- I can't quite figure out why?

I'm trying to write a Discord.JS bot that lists and removes specific channels/threads using MongoDB's Model and Schema functionality. I've gotten everything else figured out, the actual message deletion, channel deletion, and everything else I needed for the remove function, but for some reason prompting MongoDB to delete the ChatListing schema using ids specified doesn't work.
case 'remove':
modal.setTitle('Remove a Listing');
const listingIDInput = new TextInputBuilder()
.setCustomId('listingIDInput')
.setLabel(`What's the ID of your listing?`)
.setPlaceholder('EX... 14309')
.setMinLength(5)
.setStyle(TextInputStyle.Short)
.setRequired(true);
const rmrow = new ActionRowBuilder().addComponents(listingIDInput);
modal.addComponents(rmrow);
await interaction.showModal(modal);
try {
await interaction.awaitModalSubmit({ time: 120_000 }).then( (interaction) => {
const listingToRemove = interaction.fields.getTextInputValue('listingIDInput');
ChatListing.findOne({ GuildID: guild.id, ListingID: listingToRemove }, async(err, data) =>{
if(err) throw err;
if(!data) return;
if(data.MemberID == member.id) {
const channel = await guild.channels.cache.get(data.Channel);
const msg = await channel.messages.fetch(data.MessageID);
msg.delete();
var id = data._id;
ChatListing.findByIdAndDelete({_id: mongoose.Types.ObjectId(id)});
embed.setTitle('Listing successfully removed.')
.setColor('Green')
.setDescription('⚠️ | Your chat listing has been removed successufully. We\'re sorry to see it go! | ⚠️')
.setTimestamp();
await interaction.reply({ embeds: [embed], ephemeral: true });
} else {
embed.setTitle('You aren\'t the owner of the listing!')
.setColor('Red')
.setDescription('You aren\'t capable of removing this listing because you aren\'t the user that posted it.')
.setTimestamp();
await interaction.reply({ embeds: [embed], ephemeral: true });
}
});
});
} catch (err) {
console.error(err);
}
break;
This is just the snippet in the switch case used for the slash command I've built around this functionality, and the case for listing removal.
It doesn't cause any errors in the console, however when I check the database, the test listing I put up is still there and doesn't seem to go.
Is there anything I'm doing wrong? Wherever I've looked I can't quite seem to find anything that solves this problem for me. Is the reason it's not working because it's listed within a ChatListing.findOne() function? If so, how can I modify it to work outside of that function and still keep the removal functionality?
Try using findOneAndDelete and use the returned Promise to handle success or failure:
ChatListing.findOneAndDelete({_id: mongoose.Types.ObjectId(id)})
.then(() => {
embed.setTitle('Listing successfully removed.')
.setColor('Green')
.setDescription('⚠️ | Your chat listing has been removed successufully. We\'re sorry to see it go! | ⚠️')
.setTimestamp();
interaction.reply({ embeds: [embed], ephemeral: true });
})
.catch(error => {
console.error(error);
});

DiscordJs - Member undefined when remove reaction first

im trying to make a basic bot add/remove role when add/remove reaction from a post on discord.
The code works if i add the role first and then remove it, but lets say i already have the role and restart the script. When i remove the reaction the script gives me the error saying:
"Cannot read properties of undefined (reading 'roles')"
client.on('messageReactionRemove', async (reaction, user) => {
if (reaction.partial) {
try {
await reaction.fetch();
} catch (error) {
console.error('Something went wrong when fetching the message:', error);
return;
}
}
if (reaction.message.id != pinnedMsg) {
return;
}
var role = reaction.message.guild.roles.cache.find(role => role.name === "ROLENAME");
const guild = reaction.message.guild;
const member = await guild.members.cache.find(member => member.id === user.id);
member.roles.remove(role); }); //var member is undefined here
You need to fetch members with <Guild>.members.fetch because they are not cached. Don't forget to use await when needed, to find in cache it's not necessary.
Example for your case:
await guild.members.fetch();
const member = guild.members.cache.find(member => member.id === user.id);

discord.js give role when react - no reply error in the discord server

I wanted do a discord bot, and wanted it to give a role when someone reacts with an emoji, but it doesn't responsed.
My code, for now, looks like this:
client.on('messageReactionAdd', async (reaction, user) => { //here the bot adds the reaction
if (reaction.partial) {
try {
await reaction.fetch()
} catch (error) {
return console.error('error');
}
}
const guild = client.guilds.cache.get("server-id");
const role = guild.roles.cache.get("role-id");
const member = reaction.message.guild.member(user);
if (reaction.message.id !== 'text-message-id') return;
else if(reaction.emoji.name === "😎") {
if (member.roles.cache.has(fem)) return;
else
member.roles.add(role)
}
})
and
client.on('messageReactionRemove', async (reaction, user) => { //here the bot removes the reaction
if (reaction.partial) {
try {
await reaction.fetch()
} catch (error) {
console.error('error')
return
}
}
const guild = client.guilds.cache.get("server-id");
const role = guild.roles.cache.get("role-id")
const member = reaction.message.guild.member(user)
if (reaction.message.id !== 'text message id') return
else if (reaction.emoji.name === "😎") {
if (member.roles.cache.has(fem))
member.roles.remove(role)
}
});
I don't know what happened, but I thing has a version error (of
discord.js) Someone can help me?
I wanted to a RPG server, when the player reacts to a emoji, a role
of Wizard or Warrior is add...
I can't say for sure if it will fix your error, but here's a few things you should apply to your code:
Make sure you enabled partials in your startup file:
const { Client } = require('discord.js');
const client = new Client({ partials: ['MESSAGE', 'CHANNEL', 'REACTION'] });
Check if user is partial:
if(user.partial) await user.fetch();
Restructure your try block:
try {
if(reaction.partial) await reaction.fetch();
if(user.partial) await user.fetch();
}
Await the role to be added:
if (reaction.message.id !== 'text-message-id') return;
else if(reaction.emoji.name === "😎") {
if (member.roles.cache.has(fem)) return;
else await member.roles.add(role);
}
You have to await this, because roles.add() returns a promise
Also...
if you're planning to add some more messages / reactions you can use a switch for this.
Example:
// Listen for messages
switch(reaction.message.id) {
case 'your message id':
if(reaction.emoji.name === '👍') {
// Your code, if the user reacted with 👍
}
break;
case 'another message id':
// if you want to listen for multiple reactions, you can add a switch for that
// too
switch(reaction.emoji.name) {
case '😂':
// your code if user reacted with 😂
break;
case '❌':
// your code if user reacted with ❌
break;
default:
break;
}
default:
break;
}
Note:
Of course you don't have to use a switch / switches because for some people it's a bit confusing / not clean. You can manage this with if / if else statements too, but if this is getting more and more I'd recommend using a switch
The rest of your code looks fine, so I hope this will fix your problem :)
You can also take a look at my code, handling this event

Discord.js bot will not perform .then

I am trying to create a reaction message, but whenever I try to use a console.log in the .then it only executes it once the message is deleted.
async execute(message) {
const role = message.guild.roles.cache.find(r => r.name == 'Founder');
if (!role) return message.channel.send(`**${message.author.username}**, role not found`);
await message.delete();
const filter = (reaction) => reaction.emoji.name === '✅';
const ReactionMessage = await message.channel.send('React to this message to get the Founder role');
ReactionMessage.react('✅');
ReactionMessage.awaitReactions(filter, { max: 10, time: 15000 })
.then(collected => console.log(collected.size))
.catch(err => console.error(err));
}
My end game is to have it add a role to all of those users who react to it, but it won't even console.log the collected size until I delete the message. Anyone able to help me get this working?
The awaitMessages() will only resolve once either the message is deleted or the time has run out. What you can do instead is make a reactionCollector and wait for the collect event.
Here is some resources: https://discordjs.guide/popular-topics/collectors.html#reaction-collectors, https://discord.js.org/#/docs/main/stable/class/Message?scrollTo=createReactionCollector
Try replacing console.log(collected.size) with console.log(collected) and see how that works out.

How to add permissions to user to channel by command? Discord.js

How to give permissions to a specific channel by command? Sorry, I’m new at discord.js so any help would be appreciated.
const Discord = require('discord.js');
module.exports = {
name: 'addrole',
run: async (bot, message, args) => {
//!addrole #user RoleName
let rMember =
message.guild.member(message.mentions.users.first()) ||
message.guild.members.cache.get(args[0]);
if (!rMember) return message.reply("Couldn't find that user, yo.");
let role = args.join(' ').slice(22);
if (!role) return message.reply('Specify a role!');
let gRole = message.guild.roles.cache.find((r) => r.name === role);
if (!gRole) return message.reply("Couldn't find that role.");
if (rMember.roles.has(gRole.id));
await rMember.addRole(gRole.id);
try {
const oofas = new Discord.MessageEmbed()
.setTitle('something')
.setColor(`#000000`)
.setDescription(`Congrats, you have been given the role ${gRole.name}`);
await rMember.send(oofas);
} catch (e) {
message.channel.send(
`Congrats, you have been given the role ${gRole.name}. We tried to DM `
);
}
},
};
You can use GuildChannel.updateOverwrites() to update the permissions on a channel.
// Update or Create permission overwrites for a message author
message.channel.updateOverwrite(message.author, {
SEND_MESSAGES: false
})
.then(channel => console.log(channel.permissionOverwrites.get(message.author.id)))
.catch(console.error);
(From example in the discord.js docs)
Using this function, you can provide a User or Role Object or ID of which to update permissions (in your case, you can use gRole).
Then, you can list the permissions to update followed by true, to allow, or false, to reject.
Here is a full list of permission flags you can use
This method is outdated and doesn't work on V13+ the new way is doing this:
channel.permissionOverwrites.edit(role, {SEND_MESSAGES: true }
channel.permissionOverwrites.edit(member, {SEND_MESSAGES: true }

Categories