I want to add the "Auto-Role System" to my discord bot. I was doing well but it went into an error, You can check the end of the article for errors.
What I want to do is:
- The owner uses the command by mentioning a role or a bunch of roles
- Bot stores them in an array and then saves it on the database
- When a user joined the guild, the bot gives that roles array to a member
So at first, we need to make a model for the database so I did create one:
// Guild.js
const mongoose = require('mongoose');
const guildConfigSchema = mongoose.Schema({
guildId: { type: String, match: /\d{18}/igm, required: true },
autoRoleDisabled: {
type: Boolean,
},
autoRoleRoles: {type: Array},
});
module.exports = mongoose.model('guild', guildConfigSchema);
Then I coded the setup command:
const role = message.mentions.roles.first();
if (!role) return message.channel.send('Please Mention the Role you want to add to other Auto Roles.');
Schema.findOne({ guildId: message.guild.id }, async (err, data) => {
if (data) {
data.autoRoleDisabled = false;
data.autoRoleRoles.push(role.id);
data.save();
} else {
new Schema({
guildId: message.guild.id,
autoRoleDisabled: false,
$push: { autoRoleRoles: role.id }
}).save();
}
message.channel.send('Role Added: ' + `<@&${role.id}>`);
})
In the end we need to make it work:
// Main.js
client.on("guildMemberAdd", async (member) => {
// ****Auto-Role****
const Welcome = require('./models/Guild');
try {
Welcome.findOne({ guildId: member.guild.id }, async (err, data) => {
if (!data) {
return;
} else {
if (data.autoRoleDisabled == false) {
let roles = data.autoRoleRoles;
roles.forEach(r => {
guildRrole = member.guild.roles.cache.find(role => role.id)
member.roles.add(guildRrole);
})
} else {
return;
}
}
});
} catch (e) {
console.log(e);
}
});
But it doesn't work and gives an error:
Error: cyclic dependency detected
at serializeObject (C:\Users\Pooyan\Desktop\PDMBot\node_modules\bson\lib\bson\parser\serializer.js:333:34)
And I think the problem is from pushing role IDs in the array.
Notes: I am using discord.js@13.8.0 and Node.js v16