Search code examples
node.jstypescriptimportdiscord.jsnode-modules

Update an imported module in Typescript


I'm sorry, but I'm kinda new in this language. I was creating a custom discord bot these days and I got stucked on this problem... I gave this bot the possibility to load the commands dynamically from a folder with one module for each command, but now I was trying to make a command to reload them all, but each time after the commands are reloaded the output is always the same.

Here is the code:

refreshCommands = () => {
    this.commands = {};
    console.log("Refreshing commands");
    Promise.all(fs.readdirSync("./dist/commands").map(file => {
        return new Promise(async resolve => {
            const tmp = (await import(`./commands/${file}`)).default;
            this.commands[tmp.name] = tmp;
            resolve(tmp);
        });
    })).then(() => {
        console.log("Listing commands: ");
        console.log(Object.keys(this.commands));
    });
}

Of course I update the commands from the js file, and not from the ts 'cause I would have to compile it again. I tried to make a simple "ping! Pong!" like command, and then to edit it to "ping! ping!" on runtime before using the //reload command, but it keeps writing "ping! Pong!"

Edit 1: The modules I have to import are made like this one:

import command from "../utils/command";
import { Guild, GuildEmoji, GuildEmojiManager, Message, MessageEmbed, Role } from "discord.js";
import { games } from "../utils/games";
import app from "../app";
import ReactionListener from "../utils/reactionListener";

const roleMessage: command = {
    name: "rolesMessage",
    description: "",
    execute: async (message, bot) => {
        message.delete();
        createRoles(message.guild as Guild);
        const embed = new MessageEmbed()
            .setColor('#F00')
            .setTitle("React to set your ROLE!");
    
        games.forEach(game => {
            let emoji = message.guild?.emojis.cache.find(emoji => emoji.name === game.emoji);
            console.log(emoji);
            embed.fields.push({
                name: game.name,
                value: (emoji as GuildEmoji).toString(),
                inline: false
            });
        });

        const msg = await message.channel.send(embed);
        app.reactionListeners.push(new ReactionListener(msg, 
            (reaction, user) => {
                let tmp = games.find(game=> reaction.emoji.name === game.emoji);
                if(tmp){
                    //msg.channel.send(tmp);
                    const role = (message.guild as Guild).roles.cache.find(role => role.name === tmp?.roleName) as Role;
                    message.guild?.members.cache.find(member => member.id === user.id)?.roles.add(role);
                }else{
                    reaction.remove();
                }
            }, (reaction, user)=>{
                let tmp = games.find(game=> reaction.emoji.name === game.emoji);
                if(tmp){
                    //msg.channel.send(tmp);
                    const role = (message.guild as Guild).roles.cache.find(role => role.name === tmp?.roleName) as Role;
                    message.guild?.members.cache.find(member => member.id === user.id)?.roles.remove(role);
                }
            })
        );

        games.forEach(game => {
            msg.react((message.guild?.emojis.cache.find(emoji => emoji.name === game.emoji) as GuildEmoji));
        });
    }
}

const createRoles = (guild: Guild) => {
    games.forEach(game => {
        if(!guild.roles.cache.find(role => role.name === game.roleName)){
            guild.roles.create({
                data: {
                name: game.roleName,
                color: "#9B59B6",
            },
                reason: 'we needed a role for Super Cool People',
            })
            .then(console.log)
            .catch(console.error);
        }
    });
}

export default roleMessage;

This is a different one from the one I was talking about earlier, but the problem is the same... Once I update and reload it (from the js compiled version), the old version keeps being runned


Solution

  • I managed to find a solution to the problem. As node js caches every module once imported, I deleted it from the cache like this

    refreshCommands = () => {
        Promise.all(fs.readdirSync("./dist/commands").map(file => {
            return new Promise(async resolve => {
                delete require.cache[require.resolve('./commands/' + file)];
                resolve(file);
            });
        })).then(() => {
            this.commands = {};
            console.log("Refreshing commands");
            Promise.all(fs.readdirSync("./dist/commands").map(file => {
                return new Promise(async resolve => {
                    const tmp = (await import(`./commands/${file}`)).default;
                    this.commands[tmp.name] = tmp;
                    resolve(tmp);
                });
            })).then(() => {
                console.log("Listing commands: ");
                console.log(Object.keys(this.commands));
    
            });
        });
    }
    

    The code might look like garbage, but it actually works... I'm on my way to make it better, but meanwhile I can rely on it. Any suggestion is well accepted