How to make an if statement in javascript using sqlite - javascript

So i recently made this code with a warn command in discord js but there's a problem my if statement doesn't work like i wanted it to be and i wanted it to be if value doesn't exists return message.channel.send("This user has no records!"); Because i never tried using sqlite on javascript and i only know sqlite on c#
const con = require("../../sql.js");
con.all(`SELECT * FROM warnings WHERE username = ? AND userID = ?`, User.tag, User.id, (err, rows) => {
rows.forEach(r => {
if (!rows) {
message.channel.send("NO U");
}
else {
let moderator = (r.moderator);
let modID = (r.modID);
let reason = (r.reason);
let time = (r.time);
let Avatar = User.displayAvatarURL();
let Embed = new MessageEmbed()
.setTitle(`User warnings!`)
.setDescription(
`These is all the warnings which have been issued to ${User.tag}!`)
.setColor(`RED`)
.setThumbnail(Avatar)
.addFields({
name: "Moderator",
value: `${moderator}`,
inline: true
}, {
name: "Username",
value: `${User.tag}`,
inline: true
}, {
name: "Reason",
value: `${reason}`,
inline: true
}, {
name: "When was warned",
value: `${time}`,
inline: true,
});
message.channel.send(Embed).then(msg => {
msg.delete({
timeout: 15000
});
message.delete({
timeout: 3000
});
})
}
})
})

Move the if statement outside of the forEach loop.
Before:
rows.forEach(r => {
if (!rows) {
message.channel.send("NO U");
}
After:
if (rows.length === 0) {
return message.channel.send("NO U");
}
rows.forEach(r => {
As pointed out in other comments, change !rows to rows.length === 0 since the library returns an empty array when no rows are found.

I'd refactor things so there's a separate function that turns an user and the row from the database into a MessageEmbed.
That way it's easy to first try and map any warnings there are to messages, then look at whether any got generated, and if not, send out the other message.
Note that even empty arrays are truthy in JavaScript, so you'll need to check for .length.
const con = require("../../sql.js");
function warningRowToMessage(User, row) {
const { moderator, reason, time } = row;
return new MessageEmbed()
.setTitle(`User warnings!`)
.setDescription(`These is all the warnings which have been issued to ${User.tag}!`)
.setColor(`RED`)
.setThumbnail(User.displayAvatarURL())
.addFields(
{
name: "Moderator",
value: `${moderator}`,
inline: true,
},
{
name: "Username",
value: `${User.tag}`,
inline: true,
},
{
name: "Reason",
value: `${reason}`,
inline: true,
},
{
name: "When was warned",
value: `${time}`,
inline: true,
},
);
}
con.all(`SELECT * FROM warnings WHERE username = ? AND userID = ?`, User.tag, User.id, (err, rows) => {
const replyMessages = rows.map((r) => warningRowToMessage(User, r));
if (!replyMessages.length) {
message.channel.send("NO U");
return;
}
message.delete({
timeout: 3000,
});
replyMessages.forEach(async (replyMessage) => {
const msg = await message.channel.send(replyMessage);
msg.delete({
timeout: 15000,
});
});
});

Related

Making a discord bot and getting 0.name[BASE_TYPE_REQUIRED]: This field is required error

Main bot file
const {
Client,
GatewayIntentBits,
Routes,
EmbedBuilder,
ActivityType,
} = require('discord.js');
const { token, clientId, guildId } = require('../config.json');
const { REST } = require('#discordjs/rest');
const client = new Client({
intents: [
GatewayIntentBits.Guilds,
GatewayIntentBits.GuildMembers,
GatewayIntentBits.DirectMessages,
GatewayIntentBits.GuildBans,
GatewayIntentBits.GuildMessages,
GatewayIntentBits.MessageContent,
],
});
const { UrlCommand } = require('../Commands/UrlCommand.json');
client.on('ready', (client) => {
console.log(`${client.user.username}#${client.user.discriminator} running`);
client.user.setPresence({
activities: [{ name: 'connections', type: ActivityType.Watching }],
});
});
client.on('interactionCreate', async (interaction) => {
if (!interaction.isChatInputCommand()) return;
if (interaction.commandName === 'url') {
console.log(`called ${interaction.commandName} command`);
const urlEmbed = new EmbedBuilder()
.setColor('0x0099FF')
.setTitle('LEPSES')
.setURL('https://lepses.com')
.setAuthor({
name: 'LEPSES Bot',
// TODO: replace icon
iconURL:
'https://upload.wikimedia.org/wikipedia/commons/thumb/8/89/Latin_capital_letter_L_with_descender.svg/497px-Latin_capital_letter_L_with_descender.svg.png',
})
.setDescription('You choose, we connect!')
.addFields(
// TODO : add more data in the fields
{ name: 'Regular field title', value: 'Some value here' },
{ name: '\u200B', value: '\u200B' },
{
name: 'Inline field title',
value: 'Some value here',
inline: true,
},
{
name: 'Inline field title',
value: 'Some value here',
inline: true,
}
);
await interaction.reply({ embeds: [urlEmbed] });
}
if (interaction.commandName === 'clear') {
if (interaction.options.get('amount') >= 5000) {
interaction.reply('You cannot delete more than 5000 messages');
} else {
try {
const amount = interaction.options.getInteger('amount');
const Channel = interaction.channel;
if (amount) {
Channel.bulkDelete(amount, true);
await interaction.reply(`${amount} messages purged`);
} else {
Channel.bulkDelete(50, true);
await interaction.reply(`50 messages purged`);
}
} catch (err) {
console.log(err.message);
}
}
}
});
const rest = new REST({ version: '10' }).setToken(token);
async function main() {
// const commands = [];
const commands = [UrlCommand];
try {
console.log(
`Started refresing application ${commands.length} commands`
);
await rest.put(Routes.applicationGuildCommands(clientId, guildId), {
body: commands,
});
client.login(token);
} catch (error) {
console.log('ERROR=================================================');
console.log(error.message);
console.log('ERROR=================================================');
}
}
main();
URL Command in json file
{
"name": "url",
"description": "Visit us now!!"
}
Url command was in the main file earlier but now I'm moving older commands to external files to make the code smaller and easier to change in the future. But as soon as the code runs it shows BASE_TYPE_REQUIRED error. It runs normally if I declare commands as an empty array. What do I do?
You have to write the exported command in JavaScript as well. JSON is a storage file type. Try refering to discord.js command handling guide and see if it helps you.

MongoDB won't create a messageCount value

so I'm making a message count command with discord.js and MongoDB but the "messageCount" value just never gets created. I searched it up and looked at docs but I couldn't find what was wrong.
Codes:
message-counter.js file:
const mongo = require("mongoose")
const schema = require("./schemas/rank/message-count-schema")
module.exports = client => {
client.on('messageCreate', async (message) => {
const { author } = message
const { id } = author
mongo.connect(
process.env.MONGO_URI,
{ keepAlive: true }
)
const dataQuery = await schema.findOne({ _id: id })
if (!dataQuery) {
const newSchem = schema(
{
_id: id
},
{
$setOnInsert: { messageCount: 1 }
},
{
$inc: { messageCount: 1 }
},
{
upsert: true
}
)
await newSchem.save()
}
else {
dataQuery.updateOne(
{
$inc: { messageCount: 1 }
},
{
upsert: true
}
)
}
})
}
message-count-schema.js file:
const mongoose = require('mongoose');
const messageCountSchema = new mongoose.Schema({
_id: {
type: String,
required: true
},
messageCount: {
type: Number,
required: true
}
})
module.exports = mongoose.model('message-count', messageCountSchema);
Can someone tell me what's wrong and how to fix it? I'm not asking to be spoon fed, just what's wrong.
The thing is $setOnInsert is only valid for update operations when the upsert value is set to true. It exists in these methods => updateOne(), updateMany, findAndModify(). In this case, when it not an update operation, the $setOnInsert doesn't run which is why your data doesn't have the messageCount value.
Like caladan said before, and adding to that you need .findbyId() if you want to use _id, is your message count is per user or per guild?
if per user you can add to your schema a userID String item and use
const member = await message.mentions.members.first() || message.guild.members.cache.get(args[0]) || message.author;
const dataQuery = await schema.findOne({ UserID: member.id })
const messagecount = dataQuery.messageCount;
console.log(messagecount)
If per guild, you can add GildId item in your schema, and use:
const dataQuery = await schema.findOne({ GuildId: message.guild.id })
const messagecount = dataQuery.messageCount;
console.log(messagecount)

Why is my kick command only giving errors?

Wassup people. I am working on some admin commands. At this moment it's going to be a kick command. But it's only giving errors. If you remove a line or change anything, it will infect the code in another place.
That's what I am struggling with.
Here's my code:
const { Client, Intents } = require("discord.js");
const discord = require("discord.js");
const { MessageEmbed, Collection, Permissions } = require("discord.js");
module.exports = {
name: "kick",
description: "Kicks a specific member",
admin: true,
usage: "[Target] [Reason] [Messages]",
options: [
{
name: "Target",
description: "Provide A User To Kick.",
type: "USER",
required: true,
},
{
name: "Reason",
description: "Provide A Reason For The Kick.",
type: "STRING",
required: true,
},
],
async execute(message, args, client) {
const target = message.mentions.members.first();
const reason = args.slice(1, args.length - 1).join(" ");
console.log("Target: ");
const embed = new MessageEmbed().setTitle("There seems to be a error to execute this command").setColor("RED").setDescription("Are you sure you got the right permission? And are you providing a reason?");
if (!message.member.permissions.has(Permissions.FLAGS.KICK_MEMBERS))
return message.reply({ embeds: [embed] }).catch((err) => {
console.log(err);
});
if (target.id === message.member.id)
return message.reply({
embeds: [new MessageEmbed().setTitle("There seems to be a error to execute this command").setColor("RED").setDescription("Why would you kick yourself?")],
ephemeral: true,
});
if (target.permissions.has(Permissions.FLAGS.KICK_MEMBERS)) {
return message.reply({
embeds: [new MessageEmbed().setColor("RED").setDescription("You can't kick this person.")],
});
}
const DMEmbed = new MessageEmbed().setTitle(`You've Been Kicked From ${message.guild.name}`).setColor("RED").setTimestamp().addFields(
{
name: "Reason:",
value: reason,
},
{
name: "Kicked By:",
value: message.member.user.toString(),
}
);
await target
.send({
embeds: [DMEmbed],
})
.catch((err) => {
console.log(err);
});
},
};
From what I can see, it is most likely the reason field being empty.
You can change it to this to ensure there is a fallback!
{
name: "Reason:",
value: reason.replace(/\s/g, '') == "" ? "Not Provided" : reason,
},

Export variable to other files discordjs

I changed my command handler and am no longer exporting anything from profileData (used to be command handler file). The file is checking for their profile and holding the data in profileData, or if they don't have on then create one for them. I want to export the profileData to be used in other files instead of querying in every single command. How can I achieve this. I have tried putting module.exports and exports.profileData = profileData all over the place and nothing works im just lost on how to do this. Any help would be appreciated.
profileData-
const profileModel = require("../../models/profileSchema");
module.exports = (client) => {
client.on("message", async (message) => {
const prefix = 's!'
if (!message.content.startsWith(prefix) || message.author.bot) return;
try {
const profileData = await profileModel.findOne({ userID: message.author.id });
if (!profileData) {
let profile = await profileModel.create({
userID: message.author.id,
serverID: message.guild.id,
coins: 10,
bank: 0,
});
profile.save();
}
} catch (err) {
console.log(err);
}
})
}
module.exports.config = {
displayName: 'Profile Data',
dbName: 'PROFILEDATA',
loadDBFirst: true
}
balance-
const { MessageEmbed } = require("discord.js");
const { profileData } = require("../../Features/client/profileData");
module.exports = {
name: "balance",
aliases: ["bal"],
category: "Economy",
cooldown: "20s",
permissions: ["ADMINISTRATOR"],
maxArgs: 0,
description: "Check your wallet and bank balance!",
execute: async ({ message, client }) => {
let balPlaceholder = "'s balance";
const BalEmbed = new MessageEmbed()
.setColor("#0bbffc")
.setAuthor("Saoul 2")
.setTitle(`${message.author.username}${balPlaceholder}`)
.addFields(
{ name: "💸 Wallet:", value: `${profileData.coins}`, inline: true },
{ name: "🏦 Bank:", value: `${profileData.bank}`, inline: true }
)
.setTimestamp()
.setFooter(
`Command Requested By ${message.author.tag}`,
client.user.displayAvatarURL()
);
message.channel.send(BalEmbed);
},
};
If I understand you correctly: you want to export the profileData, and if none can be found, create a new profile and use that. The following snippet might solve your problem.
const profileModel = require("../../models/profileSchema");
let data = getData(client);
exports.data = data;
async function getData(client) {
client.on("message", async(message) => {
const prefix = 's!'
if (!message.content.startsWith(prefix) || message.author.bot) return;
try {
const profileData = await profileModel.findOne({
userID: message.author.id
});
if (!profileData) {
let profile = await profileModel.create({
userID: message.author.id,
serverID: message.guild.id,
coins: 10,
bank: 0,
});
profile.save();
return profile;
} else {
return profileData;
}
} catch (err) {
console.log(err);
}
})
}
module.exports.config = {
displayName: 'Profile Data',
dbName: 'PROFILEDATA',
loadDBFirst: true
}
This is all I needed to get the function to run when a message is sent through the command handler.
module.exports = {
getData: async (message) => {
try {

Overwrite Permissions for all channels in a discord server

I'm trying to create a moderation discord bot with a mute command. The mute command works in the channel that you send the command in but it doesn't work in all of the other channels. I've tried to have it go over all channels using forEach() but that doesn't seem to work. I've looked through this and tried the other solutions but its still not working. Here is the code, I hope you can help.
const Discord = require("discord.js");
const ms = require('ms')
module.exports = {
name: "mute",
aliases: [],
category: "moderation",
run: async(bot, message, args) => {
let toMute = message.guild.member(message.mentions.users.first() || message.guild.members.cache.get(args[0]));
if(!toMute) return message.channel.send("Couldn't find the user.");
if(toMute.hasPermission("MANAGE_MESSAGES")) return message.reply("Can't mute them")
let muteRole = message.guild.roles.cache.find(muteRole => muteRole.name === "Muted");
//This is where the problem starts
if(!muteRole){
muteRole = await message.guild.roles.create({ data: { name: "Muted", color: 0x000000, permissions: [] } })
message.guild.channels.cache.each(async (channel) => {
await channel.overwritePermissions(muteRole, {
"SEND_MESSAGES": false,
"ADD_REACTIONS": false,
"TALK": false
});
});
}
let muteTime = args[1];
if(!muteTime) return message.reply("Please Specify a time.");
await(toMute.roles.add(muteRole));
const mEmbed = new Discord.MessageEmbed()
.setTitle("Muted")
.addFields({ name: "Member", value: toMute, inline: false },
{ name: "Time", value: muteTime })
.setTimestamp()
message.channel.send(mEmbed)
setTimeout(function() {
toMute.roles.remove(muteRole);
message.channel.send(`<#${toMute.id}> has been unmuted`);
}, ms(muteTime))
}
}
I changed the overwritePermissions() to updateOverwrite() and it seemed to work. Here is the code:
if(!muteRole){
muteRole = await message.guild.roles.create({
data: {
name: "Muted",
color: "#000000",
permissions: [],
},
});
message.guild.channels.cache.forEach(async (channel, id) => {
await channel.updateOverwrite(muteRole, {
SEND_MESSAGES: false,
SPEAK: false,
ADD_REACTIONS: false
})
});
}
I also organized the code to make it easier to see.

Categories