MongoDb update statment - javascript

I'm currently trying to update a document in mongoDb. I'm new to mongo and reading the documentation didn't help me at all + I'm not getting any errors
My code
const Guild = require('../schemas/GuildSchema')
module.exports = {
name: 'whitelist',
description: "whitelist",
async execute(bot, message, args, PREFIX, Discord, settings, fs) {
if (message.author.id != "173347297181040640") {
return message.channel.send("Sorry only Bacio001 can whitelist!")
}
if (!args[1]) {
return message.channel.send("No guild id given!")
}
try {
Guild.findOneAndUpdate(
{ guildid: args[1]},
{ $set: { whitelisted : true } }
)
} catch (e) {
console.log(e);
}
let guild = bot.guilds.cache.get(args[1]);
message.channel.send(`Whitelisted ${guild.id} with the name ${guild.name} !`)
}
}
https://gyazo.com/a58a9d8175a8a38674b32a2776fa48cb

So I ended up finding the issue I had to await the Guild.findOneAndUpdate
const Guild = require('../schemas/GuildSchema')
module.exports = {
name: 'whitelist',
description: "whitelist",
async execute(bot, message, args, PREFIX, Discord, settings, fs) {
if (message.author.id != "173347297181040640") {
return message.channel.send("Sorry only Bacio001 can whitelist!")
}
if (!args[1]) {
return message.channel.send("No guild id given!")
}
try {
await Guild.findOneAndUpdate(
{ guildid: args[1]},
{ whitelisted : true }
)
} catch (e) {
console.log(e);
}
let guild = bot.guilds.cache.get(args[1]);
message.channel.send(`Whitelisted ${guild.id} with the name ${guild.name} !`)
}
}

Related

I cannot have ".add(role)" and ".remove(role)" at the same line of code || Discord.js V.14

So, here is my command:
const {GuildMember, Embed, InteractionCollector, CommandInteraction} = require("discord.js");
module.exports = {
name: "interactionCreate",
execute(interaction, client) {
if (interaction.isChatInputCommand()) {
const command = client.commands.get(interaction.commandName);
if (!command) {
interaction.reply({ content: "This command does NOT exist any more!", ephemeral: true });
}
command.execute(interaction, client);
} else if (interaction.isButton()) {
const { customId } = interaction;
if(customId == "verify") {
const role = interaction.guild.roles.cache.get("1060524965427953684"); //Community Role ID
const role_remove = interaction.guild.roles.cache.get('1065321229625606215'); //Unverified Role ID
return interaction.member.roles
.remove(role_remove)
.add(role)
.then((member) =>
interaction.reply({
content: `${role} has been assigned to you!`,
ephemeral: true,
})
)
}
} else {
return;
}
},
};
I want it just like that: When someone clicks the Verify Button: 1)First give the Verified Role and 2)Remove the Unverified Role. But when I click the "Verification" Button it sends me an error saying:
TypeError: interaction.reply(...).add is not a function.
If there is anyone that can help me, please, reply. Thanks!
Thanks to #user19513069, The correct answer (Line of code) is:
const {GuildMember, Embed, InteractionCollector, CommandInteraction} = require("discord.js");
module.exports = {
name: "interactionCreate",
execute(interaction, client) {
if (interaction.isChatInputCommand()) {
const command = client.commands.get(interaction.commandName);
if (!command) {
interaction.reply({ content: "This command does NOT exist any more!", ephemeral: true });
}
command.execute(interaction, client);
} else if (interaction.isButton()) {
const { customId } = interaction;
if(customId == "verify") {
const role = interaction.guild.roles.cache.get("1060524965427953684"); //Community Role ID
const role_remove = interaction.guild.roles.cache.get('1065321229625606215'); //Unverified Role ID
**interaction.member.roles
.remove(role_remove)
.then((member) =>
member.roles
.add(role)
.then((member2) =>
interaction.reply({
content: `${role} has been assigned to you!`,
ephemeral: true,
})));**
}
} else {
return;
}
},
};

'Interaction Failed' when trying to use button command

When I execute the command in discord the bot reply's with a button that says "Subscribe!", once you click it, about 3 seconds later it just says "Interaction Failed" with no console error. I have been looking at this for an hour now and trying to figure it out myself, but I've gotten past that point and I need help.
sub-yt.js;
module.exports = {
data: {
name: "sub-yt",
},
async execute(interaction, client) {
await interaction.reply({
content: `https://youtube.com/duanetv`,
});
},
};
interactionCreate.js;
module.exports = {
name: "interactionCreate",
async execute(interaction, client) {
if (interaction.isChatInputCommand()) {
const { commands } = client;
const { commandName } = interaction;
const command = commands.get(commandName);
if (!command) return;
try {
await command.execute(interaction, client);
} catch (error) {
console.error(error);
await interaction.reply({
content: `interactionCreate has failed.`,
ephemeral: true,
});
}
} else if (interaction.isButton()) {
const { buttons } = client;
const { customId } = interaction;
const button = buttons.get(customId);
if (!button) return new Error("Button failed.");
try {
await button.execute(interaction, client);
} catch (err) {
console.error(err);
}
}
},
};
handleComponents.js;
const { readdirSync } = require("fs");
module.exports = (client) => {
client.handleComponent = async () => {
const componentFolders = readdirSync(`./src/components`);
for (const folder of componentFolders) {
const componentFiles = readdirSync(`./src/components/${folder}`).filter(
(file) => file.endsWith(".js")
);
const { buttons } = client;
switch (folder) {
case "buttons":
for (const file of componentFiles) {
const button = require(`../../components/${folder}/${file}`);
buttons.set(button.data.name, button);
}
break;
default:
break;
}
}
};
};

messageReactionAdd isn't firing despite proper setup Discord.js

Entire file below. I've been trying for an ungodly amount of time to get a reaction roles command working. Currently using MongoDB and everything is setup properly no errors my schema has worked properly as well there are no issues. Despite everything working I cannot get my event to fire at all with multiple revisions. Any help would be phenomenal on this one as I am too new to all of this to figure it out for myself...
const Schema = require('../reactions');
const Discord = require('discord.js');
const { client, intents } = require('..')
module.exports = {
name: 'messageReactionAdd',
run: async (reaction, message, user) => {
if (reaction.message.partial) await reaction.message.fetch();
if (reaction.partial) await reaction.fetch();
const { guild } = reaction.message;
if (!guild) return;
if (!guild.me.permissions.has("MANAGE_ROLES")) return;
isEmoji = function(emoji) {
const e = Discord.Util.parseEmoji(emoji);
if (e.id === null) {
return {
name: e.name,
id: e.id,
animated: e.animated,
response: false
}
} else {
return {
name: e.name,
id: e.id,
animated: e.animated,
response: true
}
}
}
const member = guild.members.cache.get(user.id);
await Schema.findOne({
guild_id: guild.id,
msg_id: reaction.message.id
}, async (err, db) => {
if (!db) return;
if (reaction.message.id != db.msg_id) return;
const data = db.rcs;
for (let i in data) {
if (reaction.emoji.id === null) {
if (reaction.emoji.name === data[i].emoji) {
member.roles.add(data[i].roleId, ['reaction role']).catch(err => console.log(err));
}
} else {
if (reaction.emoji.id === data[i].emoji) {
member.roles.add(data[i].roleId, ['reaction role']).catch(err => console.log(err));
}
}
}
});
},
};```
Intents
You need the GUILD_MESSAGE_REACTIONS in your client

Discord.js ban command ban reason

Im trying to get a ban command and im using my pervious kick command as a sort of template, i cant quite get the ban reason to work, im assuming thats the only issue the code is below.
const Discord = require('discord.js')
module.exports.run = async (bot, message, args) => {
if (!message.member.hasPermission('BAN_MEMBERS')) return message.reply('**No permission**')
const user = message.mentions.users.first();
if (user) {
const member = message.guild.member(user);
if (member) {
member
.ban('no reason')
.then(() => {
message.channel.send(`${user.tag} Has been banned`)
})
.catch(err => {
message.reply('Unable');
console.error(err);
});
} else {
message.reply("Error");
}
} else {
message.reply("You forgot to mention someone");
}
};
module.exports.help = {
name: "ban"
}
You must supply the correct parameters for .ban()
in this case .ban({reason: 'no reason'})
so your corrected code is
if (!message.member.hasPermission("BAN_MEMBERS"))
return message.reply("**No permission**");
const user = message.mentions.users.first();
if (user) {
const member = message.guild.member(user);
if (member) {
member
.ban({ reason: "no reason" })
.then(() => {
message.channel.send(`${user.tag} Has been banned`);
})
.catch((err) => {
message.reply("Unable");
console.error(err);
});
} else {
message.reply("Error");
}
} else {
message.reply("You forgot to mention someone");
}
also, please supply errors in future and look for Other information beforehand.
Adding on, a lot of that will not work in V13
if (!message.member.permissions.has("BAN_MEMBERS"))
return message.reply("**You do not have the proper permissions.**");
const user = message.mentions.users.first();
if (user) {
const member = message.guild.members.cache.get(user.id);
if (member) {
member
.ban({ reason: "no reason" })
.then(() => {
message.channel.send(`${user.tag} Has been banned`);
})
.catch((err) => {
message.reply(`Unable to ban User. \`\`\`${err}\`\`\` `);
console.error(err);
});
} else {
message.reply("Error");
}
} else {
message.reply("You forgot to mention someone, <#${message.author.id}>");
}
// © Ahmed1Dev
const Discord = require('discord.js')
module.exports.run = async (bot, message, args) => {
if (!message.member.hasPermission('BAN_MEMBERS')) return message.reply('**No permission**')
const user = message.mentions.users.first();
let reason = args.slice(2).join(' ');
if (user) {
const member = message.guild.member(user);
if (member) {
member
.ban('no reason')
.then(() => {
message.channel.send(`${user.tag} Has been banned`)
})
.catch(err => {
message.reply('Unable');
console.error(err);
});
} else {
message.reply("Error");
}
} else {
message.reply("You forgot to mention someone");
}
};
module.exports.help = {
name: "ban"
}
// © Ahmed1Dev

Discord.js currency to command handler

I am trying to move all of my currency/shop commands/ Sequelize database into the command handler from index.js (works perfectly in index.js file) but I am running into issues transferring data from the index.js file into the individual command files. Any help on how to properly integrate the index.js commands into the command handler would be greatly appreciated. I realize this is a lot to go through but it would really mean a lot to me if anyone was able to help me out
index.js:
Reflect.defineProperty(currency, 'add', {
value: async function add(id, amount) {
const user = currency.get(id);
if (user) {
user.balance += Number(amount);
return user.save();
}
const newUser = await Users.create({ user_id: id, balance: amount });
currency.set(id, newUser);
return newUser;
},
});
Reflect.defineProperty(currency, 'getBalance', {
value: function getBalance(id) {
const user = currency.get(id);
return user ? user.balance : 0;
},
});
client.once('ready', async () => {
const storedBalances = await Users.findAll();
storedBalances.forEach(b => currency.set(b.user_id, b));
console.log(`Logged in as ${client.user.tag}!`);
});
client.on('message', async message => {
if (message.author.bot) return;
currency.add(message.author.id, 1);
if (!message.content.startsWith(prefix)) return;
const input = message.content.slice(prefix.length).trim();
if (!input.length) return;
const [, command, commandArgs] = input.match(/(\w+)\s*([\s\S]*)/);
if (command === 'balance') {
const target = message.mentions.users.first() || message.author;
return message.channel.send(`${target.tag} has ${currency.getBalance(target.id)}💰`);
} else if (command === 'buy') {
const item = await CurrencyShop.findOne({ where: { name: { [Op.like]: commandArgs } } });
if (!item) return message.channel.send('That item doesn\'t exist.');
if (item.cost > currency.getBalance(message.author.id)) {
return message.channel.send(`You don't have enough currency, ${message.author}`);
}
const user = await Users.findOne({ where: { user_id: message.author.id } });
currency.add(message.author.id, -item.cost);
await user.addItem(item);
message.channel.send(`You've bought a ${item.name}`);
} else if (command === 'shop') {
const items = await CurrencyShop.findAll();
return message.channel.send(items.map(i => `${i.name}: ${i.cost}💰`).join('\n'), { code: true });
} else if (command === 'leaderboard') {
return message.channel.send(
currency.sort((a, b) => b.balance - a.balance)
.filter(user => client.users.cache.has(user.user_id))
.first(10)
.map((user, position) => `(${position + 1}) ${(client.users.cache.get(user.user_id).tag)}: ${user.balance}💰`)
.join('\n'),
{ code: true }
);
}
});
converting balance command to balance.js
balance.js:
const { currency, getBalance, id, tag } = require('../index.js');
module.exports = {
name: "balance",
description: "checks balance",
execute(message) {
const target = message.mentions.users.first() || message.author;
message.channel.send(`${target.tag} has ${currency.getBalance(target.id)}💰`);
},
};
error:
TypeError: Cannot read property 'getBalance' of undefined
Command Handler
client.on('message', message => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ +/);
const commandName = args.shift().toLowerCase();
const command = client.commands.get(commandName)
|| client.commands.find(cmd => cmd.aliases && cmd.aliases.includes(commandName));
if (!command) return;
if (command.guildOnly && message.channel.type !== 'text') {
return message.reply('I can\'t execute that command inside DMs!');
}
if (command.args && !args.length) {
let reply = `You didn't provide any arguments, ${message.author}!`;
if (command.usage) {
reply += `\nThe proper usage would be: \`${prefix}${command.name} ${command.usage}\``;
}
return message.channel.send(reply);
}
if (!cooldowns.has(command.name)) {
cooldowns.set(command.name, new Discord.Collection());
}
const now = Date.now();
const timestamps = cooldowns.get(command.name);
const cooldownAmount = (command.cooldown || 3) * 1000;
if (timestamps.has(message.author.id)) {
const expirationTime = timestamps.get(message.author.id) + cooldownAmount;
if (now < expirationTime) {
const timeLeft = (expirationTime - now) / 1000;
return message.reply(`please wait ${timeLeft.toFixed(1)} more second(s) before reusing the \`${command.name}\` command.`);
}
}
timestamps.set(message.author.id, now);
setTimeout(() => timestamps.delete(message.author.id), cooldownAmount);
try {
command.execute(message, args);
} catch (error) {
console.error(error);
message.reply('there was an error trying to execute that command!');
}
});
the bot sends an error from the command handler as seen above
EDIT: Cherryblossom's post seems to work. i have 1 more issue with immigrating the buy command though I dont know how to make the async work as async doesnt work in command handler. here is what i tried
const { currency, CurrencyShop} = require('../index.js');
const item = await CurrencyShop.findOne({ where: { name: { [Op.like]: commandArgs } } });
if (!item) return message.channel.send('That item doesn\'t exist.');
if (item.cost > currency.getBalance(message.author.id)) {
return message.channel.send(`You don't have enough currency, ${message.author}`);
}
const user = await Users.findOne({ where: { user_id: message.author.id } });
currency.add(message.author.id, -item.cost);
await user.addItem(item);
message.channel.send(`You've bought a ${item.name}`);```
What's happening is that in balance.js, currency is undefined. You need to export currency from index.js:
module.exports = { currency }
Also, in balance.js, you don't need to (and actually can't) import/require properties of other objects (getBalance, tag, id). Sorry if that doesn't make sense but basically you only need to require currency:
const { currency } = require('../index.js')
Edit
await can only be used in an async function. Edit the execute function so it is like this:
async execute(message) {
// your code here
}
When calling execute, use await. You'll need to make the message handler async as well:
client.on('message', async message => {
// code...
try {
await command.execute(message, args);
} catch (error) {
console.error(error);
message.reply('there was an error trying to execute that command!');
}
}

Categories

Resources