MessageCreate.js prefix issues with database - Discord.js v13/MongoDB - mongodb

I have this code in my messageCreate event:
// MODULES
const Discord = require('discord.js');
const mongoose = require('mongoose');
const Levels = require('discord.js-leveling');
// FILES
const Guild = require('../../models/guild');
const config = require('../../files/config.json');
const swearwords = require("../../files/data.json");
const colors = require('../../files/colors.json');
// ERROR MESSAGE
const errorMain = new Discord.MessageEmbed()
.setDescription("There was an error!")
.setColor(colors.COLOR)
const addedDatabase = new Discord.MessageEmbed()
.setDescription("This server is now added to our database.")
.setColor(colors.COLOR)
module.exports = async (Discord, client, message) => {
if (!message.guild) return;
if (message.author.bot) return;
const settings = await Guild.findOne({
guildID: message.guild.id
}, (err, guild) => {
if (err) message.channel.send(errorMain);
if (!guild) {
const newGuild = new Guild({
_id: mongoose.Types.ObjectId(),
guildID: message.guild.id,
prefix: config.PREFIX,
logChannelID: String,
enableLog: false,
enableSwearFilter: true,
enableMusic: true,
enableLevel: true,
});
newGuild.save()
.catch(err => message.channel.send(errorMain));
return message.channel.send({embeds: [addedDatabase]}).then(m => m.delete({ timeout: 10000 }))
}
});
// VARIABLES
const IDGuild = message.guild.id;
const user = message.author;
const prefix = settings.prefix;
const swearFilterOn = settings.enableSwearFilter;
// LEVEL SYSTEM
if (settings.enableLevel === "true") {
const requiredXp = Levels.xpFor(parseInt(user.level) + 1)
const randomAmountOfXp = Math.floor(Math.random() * 29) + 1;
const hasLeveledUp = await Levels.appendXp(message.author.id, message.guild.id, randomAmountOfXp);
if (hasLeveledUp) {
const user = await Levels.fetch(message.author.id, message.guild.id);
const levelEmbed = new Discord.MessageEmbed()
.setTitle('New Level!')
.setColor(colors.COLOR)
.setDescription(`**GG** ${message.author}, you just leveled up to level **${user.level}**!\nContiune to chat to level up again.`)
const sendEmbed = await message.channel.send({embeds: [levelEmbed]});
}
}
// EXECUTE COMMAND AND SWEARFILTER
if (swearFilterOn === "true") {
var msg = message.content.toLowerCase();
for (let i = 0; i < swearwords["swearwords"].length; i++) {
if (msg.includes(swearwords["swearwords"][i])) {
message.delete();
return message.channel.send("Please do not swear.").then(msg => msg.delete({ timeout: 3000 }));
}
}
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ +/);
const cmd = args.shift().toLowerCase();
const command = client.commands.get(cmd) ||
client.commands.find(a => a.aliases && a.aliases.includes(cmd));;
if (command) command.execute(client, message, args, Discord)
} else {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ +/);
const cmd = args.shift().toLowerCase();
const command = client.commands.get(cmd) ||
client.commands.find(a => a.aliases && a.aliases.includes(cmd));;
if (command) command.execute(client, message, args, Discord)
}
}
And when i send a message right after the bot joines the discord, it gives the error that it cannot read properties of null (reading 'prefix').
The bot crashes, and when it's restarted it works because it has been added to the Database. So how can i fix that when it sends the first message it can still read 'prefix'. its probably a database issue.
I was told that settings.prefix probaly wasn't assinged a value, is there a way to fix this?
I'm using mongodb for my database.

You really should assign the prefix right after the bot joins new server with guildCreate event. It may cause some issues if your database is down etc. When you wait till the message event

Related

Bot doesnt want to take id from db

I'm making a command where u can setup a bot status channel. Everything so far worked fine, db even writes down id of guild and channel but when I want to use it in ready.js is says its not defined.
Little help would be handy and grateful
Code:
https://pastebin.com/GnxtxFwG - main command
https://pastebin.com/hhy90czw - schema
https://pastebin.com/jVDGu43T - error
Error file:
const { EmbedBuilder } = require('discord.js');
const { channelId } = require('../../schemas/status');
module.exports = {
name: "ready",
once: "true",
async execute(client) {
console.log(channelId)
console.log('Bot is up and ready to work!')
const uptime = new EmbedBuilder()
.setColor('ffd9c0')
.addFields(
{ name: 'Capy is back and online!', value: 'Bot was probably offline due to a bug or maintenance.'},
{ name: '\u200b', value: 'If Capy isnt working how is he supposed to be contact on of our Developers or contact <#574849327650963469> directly.'},
)
const channel = await client.channels.cache.get(channelId);
channel.send({ embeds: [uptime] });
setInterval(client.pickPresence, 10 * 1000);
},
};
Client on function
const { EmbedBuilder } = require('discord.js');
const { Statuses } = require('../../schemas/status');
const uptime = require('../../commands/tools/status')
module.exports = {
name: "ready",
once: "true",
async execute(client) {
console.log(Statuses.channelId)
console.log('Bot is up and ready to work!')
const uptimeEmbed = new EmbedBuilder()
.setColor('ffd9c0')
.addFields(
{ name: 'Capy is back and online!', value: 'Bot was probably offline due to a bug or maintenance.'},
{ name: '\u200b', value: 'If Capy isnt working how is he supposed to be contact on of our Developers or contact <#574849327650963469> directly.'},
)
const channel = await client.channels.cache.get(Statuses.channelId);
Statuses.findById({ channelId: message.guild.id }, async (err, data) => {
if (data) {
channel.send({ embeds: [uptimeEmbed] });
} else {
new Statuses ({
guildId: interaction.guild.id,
chnanelId: uptime ? uptime : "None"
}).save()
console.log("Status channel wasnt set on this server yet!")
}
});
setInterval(client.pickPresence, 10 * 1000);
},
};
Schema
const { Schema, model } = require('mongoose');
const statusSchema = new Schema({
guildId: String,
channelId: String,
});
module.exports = model("Status", statusSchema, "Statuses");
Main command
const {
SlashCommandBuilder,
ChatInputCommandInteraction,
EmbedBuilder,
} = require("discord.js");
const Statuses = require('../../schemas/status');
module.exports = {
data: new SlashCommandBuilder()
.setName("status")
.setDescription("Select the language of the bot")
.addChannelOption(uptime => {
return uptime
.setName("channel")
.setDescription("Channel you want to send the FAQ embed in")
.setRequired(true)
}),
/**
*
* #param {ChatInputCommandInteraction} interaction
* #param {Client} client
*/
async execute(interaction, client) {
const { options } = interaction;
const uptime = options.getChannel("channel");
const user = interaction.user;
const status = new EmbedBuilder()
.setColor("#bb6464")
.setDescription(`Status message was set to ${uptime}!`)
.setFooter({ text: `Request from ${interaction.user.username}`, iconURL: user.displayAvatarURL()})
.setTimestamp();
const status2 = new EmbedBuilder()
.setColor("#bb6464")
.setDescription(`Status message was changed to ${uptime}!`)
.setFooter({ text: `Request from ${interaction.user.username}`, iconURL: user.displayAvatarURL()})
.setTimestamp();
let statusProfile = await Statuses.findOne({ channelId: interaction.guild.id });
if (!statusProfile) {
statusProfile = await new Statuses({
guildId: interaction.guild.id,
channelId: uptime,
});
await statusProfile.save().catch(console.error);
interaction.reply({ embeds: [status] })
console.log(statusProfile);
} else {
await interaction.reply({ embeds: [status2] });
console.log(statusProfile);
}
}
}

MongoDB doesn't add a new user after previous request with UNIQUE referral code. MongoDB webpage "REFRESH" helps only. What I did wrong?

Auth.js (CONTROLLER):
const bcrypt = require('bcryptjs')
const jwt = require('jsonwebtoken')
const User = require('../models/User')
const keys = require('../config/keys')
const errorHandler = require('../utils/errorHandler')
// REGISTRATION
module.exports.register = async function(req, res) {
const candidate = await User.findOne({email: req.body.email})
const phone = await User.findOne({phone: req.body.phone})
if (candidate) {
// user exist
res.status(409).json({
message: 'Email is taken. Try another one!'
})
} else {
// new user
const salt = bcrypt.genSaltSync(10)
const password = req.body.password
const user = new User({
username: req.body.username,
password: bcrypt.hashSync(password, salt),
})
try {
await user.save()
res.status(201).json(user)
} catch(e) {
errorHandler(res, e)
}
}
}
Auth.js (ROUTES):
const express = require('express')
const controller = require('../controllers/auth')
const router = express.Router()
//localhost:5000/api/auth/register
router.post('/register', controller.register)
module.exports = router
User.js(MODEL):
const mongoose = require('mongoose')
const Schema = mongoose.Schema
const userSchema = new Schema({
username: {
type: String,
unique: false
},
password: {
type: String,
required: true
},
codeRef: {
type: String,
default: makeid(6).toString(),
unique: true
}
})
// GENERATE RANDOM REFFERAL LINK
function makeid(length) {
var result = ''
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
var charactersLength = characters.length
for ( var i = 0; i < length; i++ ) {
result += characters.charAt(Math.floor(Math.random() * charactersLength))
}
return result
}
module.exports = mongoose.model('users', userSchema)
Everything works fine, the new user added successfully.
The problem comes with another added user after the first one. Generated referral code gives error until we refresh the MongoDB database or restart the server (NPM).
(Results from POSTMAN)
{
"success": false,
"message": "E11000 duplicate key error collection: Cluster.users index: codeRef_1 dup key: { codeRef: \"DDP1SF\" }"
}
Logs from console:
POST /api/auth/register 201 457.563 ms - 350
POST /api/auth/register 500 304.148 ms - 142
POST /api/auth/register 500 190.155 ms - 142
Tried to change the const to var... Should I clear the Schema data of previous request somehow? Because my generated random code for 6 symbols is the same until refresh.
MODELS should NOT contain functions because they are static.
Placing the function inside CONTROLLER file did the work.
// GENERATE RANDOM REFFERAL LINK
function makeid(length) {
var result = ''
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
var charactersLength = characters.length
for ( var i = 0; i < length; i++ ) {
result += characters.charAt(Math.floor(Math.random() * charactersLength))
}
return result
}
To show the response after the server was updated, use new: true :
const user = new User({
username: req.body.username,
password: bcrypt.hashSync(password, salt),
codeRef: makeid(6).toString(),
new: true
})

When I enter my command for my discord bot it says that it confirmed the command twice does anyone know how to fix this?

So when I use my discord bots kick command it says everything twice. I've tried restarting Visual Studio Code but it still doesn't work. I haven't duplicated my code or anything so I'm pretty confused on what the problem could be
const Discord = require('discord.js');
const client = new Discord.Client();
const prefix = '!';
const fs = require('fs');
client.commands = new Discord.Collection();
const commandFiles = fs.readdirSync('./commands/').filter(file => file.endsWith('.js'));
for(const file of commandFiles){
const command = require(`./commands/${file}`);
client.commands.set(command.name, command);
}
client.once('ready', () => {
console.log('KeyBot is online!');
});
client.on('message', message => {
if (!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ +/);
const command = args.shift().toLowerCase();
if (command === 'ping') {
message.channel.send('pong!');
}
});
client.on('message', (message) => {
if (!message.guild) return;
if (message.content.startsWith('!kick')) {
const user = message.mentions.users.first();
if (user) {
const member = message.guild.member(user);
if (member) {
member
.kick('Optional reason that will display in the audit logs')
.then(() => {
message.reply(`Successfully kicked ${user.tag}`);
})
.catch((err) => {
message.reply('I was unable to kick the member');
console.error(err);
});
} else {
message.reply("That user isn't in this guild!");
}
} else {
message.reply("You didn't mention the user to kick!");
}
}
});

Socket.io, Mongodb returning undefined to frontend

I want to use socekt.io for a new project I am building. I am using socket.io for a login component and will be using socket.io in the future to update pages like a chat app. I am also using mongoose to handle my mongodb connection. I am taking in a username, and returning a password to my front end to be bcryptjs compareSync hashed. The problem I am having is that whatever is returned to the front end is undefined. When I print out what is returned to the front end, it prints out the value I am looking for though. Something is going on between the backend emitting something, and the frontend receiving something but I don't know what is it exactly. Here is my code for the back end:
const express = require('express')
const socket = require('socket.io');
const http = require('http');
const router = require('./router');
const mongoose = require('mongoose');
let Player = require('../models/player.model');
require('dotenv').config();
const PORT = process.env.PORT || 5000;
const app = express();
const server = http.createServer(app);
const uri = process.env.ATLAS_URI;
mongoose.connect(uri, {useNewUrlParser: true, useCreateIndex: true,
useUnifiedTopology: true });
const connection = mongoose.connection;
connection.once('open',() => {
console.log('MongoDB database connection established successfully')
});
const io = socket(server);
io.on('connection', (socket) => {
console.log('We have a new connection');
socket.on('login', ({ username }, callback) => {
console.log(username);
Player.find({"username": username}, function (err, player) {
if(err) {
console.log("there has been an error"), {player: null}
}
socket.emit('id', { password: player[0]['password'].toString(), id : player[0]['_id']})
}) })})
app.use(router);
server.listen(PORT, () => console.log('Server is working'))
Here is my code for the front end:
const ENDPOINT = 'localhost:5000';
async function submitAccount (e) {
e.preventDefault();
socket.emit('login', { username });
socket.on("id", (response) => {
setPassword2(String(response['password']));
id = response['id']; console.log(id);
console.log(password2)
});
try {
if (bcrypt.compareSync(password, password2) == true) {
props.setCookie("id", id);
setAccess(true);
access2 = true;
console.log(access2)
console.log('works')
}
else {
setErrorType('Invalid Password')
setErrorMsg('There is an issue with your password. Please try again')
setOpenModal(true)
console.log(password);
console.log(password2);
}
}
catch {
setErrorType('Invalid Username')
setErrorMsg('This username does not exist. Please try another')
setOpenModal(true)
}
Thanks for the help!
When you do the socket.on, it should include the whole statement you are looking to change with the socket.io output. See below:
async function submitAccount (e) {
e.preventDefault();
socket.emit('login', { username });
socket.on("id", (response) => {
setPassword2(String(response['password']));
id = response['id']; console.log(id);
console.log(password2)
if (password2 != undefined) {
try {
if (bcrypt.compareSync(password, password2) == true) {
props.setCookie("id", id);
setAccess(true);
access2 = true;
console.log(access2)
console.log('works')
}
}

How can I wrap sails-mongo db methods for profiling?

I'm trying to setup a sails hook with miniprofiler to help profile mongo usage. I'm struggling for how to wrap the db methods in a function that will execute the profile. I'm trying to do this via a user hook:
setupMiniprofilerMongo(req, res, next) {
const adapter = sails.hooks.orm.datastores.default.adapter;
const adapterPrototype = Object.getPrototypeOf(adapter);
const originalMethod = adapter.adapter.find;
methodPrototype.find = function profiledMongoCommand(connectionName, collectionName, options, cb) {
sails.log.info(`${collectionName}.find`);
return originalMethod.call(adapter, connectionName, collectionName, options, cb);
};
}
That causes the following error to be thrown:
TypeError: Cannot read property 'collections' of undefined
at Object.module.exports.adapter.find (/Users/jgeurts/dev/platform/node_modules/sails-mongo/lib/adapter.js:349:40)
at Object.profiledMongoCommand [as find] (/Users/jgeurts/dev/platform/config/http.js:234:37)
Any help would be appreciated. I tried to wrap the methods on mongodb package, but that doesn't seem to work either. :/
I got this working by wrapping waterline query methods. There is room for improvement, though.
setupMiniprofilerWaterline(req, res, next) {
const dbOperations = [
'count',
'create',
'createEach',
'define',
'describe',
'destroy',
'drop',
'find',
'join',
// 'native',
// 'registerConnection',
'update',
];
const waterlineMethodByModels = {};
const miniprofilerWaterline = () => {
return {
name: 'mongodb',
handler(req, res, next) {
if (!req.miniprofiler || !req.miniprofiler.enabled) {
return next();
}
const profiler = req.miniprofiler;
for (const modelName of _.keys(sails.models)) {
for (const dbOperation of dbOperations) {
const model = sails.models[modelName];
if (!model[dbOperation]) {
continue;
}
if (!waterlineMethodByModels[modelName]) {
waterlineMethodByModels[modelName] = {};
}
// Prevent wrapping a method more than once
if (waterlineMethodByModels[modelName][dbOperation]) {
continue;
}
waterlineMethodByModels[modelName][dbOperation] = true;
const originalMethod = model[dbOperation];
model[dbOperation] = function profiledMongoCommand(...args) {
const query = args && args.length ? args[0] : '';
const lastArg = args && args.length ? args[args.length - 1] : null;
const modelAndMethod = `${modelName}.${dbOperation}`;
if (lastArg && typeof lastArg === 'function') {
sails.log.debug(`mongo::${modelAndMethod} - ${JSON.stringify(query)}`);
const callback = args.pop();
const timing = profiler.startTimeQuery('mongodb', query ? JSON.stringify(query || '') : '');
// In general, the callstack is kind of useless to us for these profiles
// The model/db method is more useful in the miniprofiler UI
timing.callStack = `\n\nMethod: ${modelAndMethod}`;
return originalMethod.call(this, ...args, function profiledResult(...results) {
profiler.stopTimeQuery(timing);
callback(...results);
});
}
const methodResult = originalMethod.call(this, ...args);
const methodResultPrototype = Object.getPrototypeOf(methodResult);
const isDeferred = !!methodResultPrototype.exec;
// If methodResult is a Deferred object type, then the query method will be profiled above when the deferred is executed (with a callback)
// So we only care to log this if the methodResult is not a deferred object
if (!isDeferred) {
sails.log.warn(`Was not able to profile mongo::${modelAndMethod}. Maybe its a promise? query: ${JSON.stringify(query)}`);
}
return methodResult;
};
}
}
next();
},
};
};
miniprofiler.express.for(miniprofilerWaterline())(req, res, next);
},
The code is available as miniprofiler-waterline if you want to contribute/use it in your own projects