I have set up a code that adds guilds to the database with default settings when they join. If the guild decides to change the prefix, it updates successfully and they can immediately start using it. However, there is an issue where I have to restart the bot or use nodemon to auto-restart it upon changes for the new guild before they can use any commands. Is there a difference in how I am adding this information to the database compared to adding the prefix?
Below is the code I use to add the server to the database and below that is the code I use to allow them to change the prefix. I am attempting to make the commands work for the server that just invited the bot without having to restart the bot to prevent bugs down the line when it is interrupted and then restarted due to a new guild invitation.
/// code for adding a guild to the database upon invite
bot.on('guildCreate', async (guild) => {
// Guild the user needs to have the role in
let myGuild = await bot.guilds.fetch(process.env.BOT_GUILD);
console.log(myGuild);
// Required role for the user
let requiredRole = process.env.PAID_ROLE;
console.log(requiredRole);
// Finding the default channel
let defaultChannel = "";
guild.channels.cache.forEach((channel) => {
if(channel.type == "text" && defaultChannel == "") {
if(channel.permissionsFor(guild.me).has("SEND_MESSAGES")) {
defaultChannel = channel;
console.log(defaultChannel);
}
}
});
// Member object of the user in guildA
try{
let guildOwner = await myGuild.members.fetch(guild.ownerID);
console.log(guildOwner);
if (!guildOwner)
return console.log(`Oops, ${guild.owner} is not a member of your server.`);
}catch(error) {
return console.log(`Oops, ${guild.owner} is not a member of your server.`),
defaultChannel.send('Please kick the bot, have the guild owner join this discord https://discord.gg/tDTjBAaCAn, Then you can reinvite the bot and you will be properly added to the database and can use the bot! dont forget to check out the premium features while your there if you decide you want more features from Gate Bot!');
}
// Checking if they have the role
let guildOwner = await myGuild.members.fetch(guild.ownerID);
let ownerHasPaidRole = guildOwner.roles.cache.has(process.env.PAID_ROLE);
if (ownerHasPaidRole){
console.log(`Woohoo, ${guildOwner} has the required role`);}
try {
/// Insert serverid and serverownerid into servers db
await connection.query(
`INSERT INTO Servers (serverId, serverOwnerId, paidRole) VALUES ('${guild.id}', '${guild.ownerID}', 1)`
);
/// Insert server id into serverconfig db
await connection.query(
`INSERT INTO ServerConfig (serverId) VALUES ('${guild.id}')`
);
}catch(err){
console.log(err);
}});
Message handler for using the change prefix command
/// Allowing the script to access files from the commands folder
bot.commands = new Discord.Collection();
const commandFiles = fs.readdirSync('./commands/').filter(file => file.endsWith('.js'));
for(const file of commandFiles){
const command = require(`./commands/${file}`);
bot.commands.set(command.name, command);
}
/// Message Handler
bot.on('message', async (message) => {
const prefix = guildCommandPrefixes.get(message.guild.id);
console.log('Caught message');
if(!message.content.startsWith(prefix) || message.author.bot) return;
const args = message.content.slice(prefix.length).split(/ +/);
const command = args.shift().toLowerCase();
/// Basic ping pong test command
if(command === 'help'){
bot.commands.get('help').execute(message);
}
/// Basic ping pong test command
else if(command === 'ping'){
bot.commands.get('ping').execute(message);
}
/// Command to change the server's prefix
else if(command === 'changeprefix'){
bot.commands.get('changeprefix').execute(message, connection, prefix, guildCommandPrefixes);
}
/// Arguments test
else if (command === 'argsinfo'){
bot.commands.get('argsinfo').execute(message, command, args)
}
/// Message command list
else if (command === 'autoungate'){
bot.commands.get('autoungate').execute(message, args, Discord);
}});
Code used to change the prefix
module.exports= {
name: 'changeprefix',
description: "This will change the prefix in the database for the set guild id",
execute: async (message, connection, prefix, guildCommandPrefixes) =>{
setTimeout(() => {message.delete();}, 3000);
if (message.content.toLowerCase().startsWith(prefix + 'changeprefix')){
if (message.member.id === message.guild.ownerID) {
var guild = message.guild
paidRole = await connection.query(`SELECT paidRole FROM Servers Where '${guild}' === serverId`);
const [cmdName, newPrefix ] = message.content.split(" ");
if (paidRole === '1'){
if (newPrefix) {
try {
await connection.query(
`UPDATE ServerConfig SET cmdPrefix = '${newPrefix}' WHERE serverId= '${message.guild.id}'`
);
guildCommandPrefixes.set(message.guild.id, newPrefix);
message.channel.send(`Updated guild prefix to ${newPrefix}`).then(sentMessage => {sentMessage.delete({ timeout: 3000}); });
}catch(err) {
console.log(err);
message.channel.send(`Failed to update guild prefix to ${newPrefix}`).then(sentMessage => {sentMessage.delete({ timeout: 3000}); });
}}
else {
message.channel.send('You need to input a prefix to change to!').then(sentMessage => {sentMessage.delete({ timeout: 3000}); });
}}
else {
message.channel.send('You need to purchase the premium version for prefix customization.').then(sentMessage => {sentMessage.delete({ timeout: 3000}); });
}}
else {
message.channel.send('You do not have permissions to do this command!').then(sentMessage => {sentMessage.delete({ timeout: 3000}); });
}
}
}}