1

[FIXED] My sleep function used to work for all of my commands. I didn't do anything to the function but somehow it now only works for certain commands (in the code); like over here:

if (message.author.id != dev_ids) return message.channel.send("You don't have permission to use this command")

        let msg = await message.channel.send("Fetching link...")
        await sleep(2000)
        msg.edit(`Check your DMs <@${message.author.id}>`)
        message.author.send(`Bot Logs: https://dashboard.heroku.com/apps/***/logs\nAny problems? DM <@***>`)

But doesn't work for this command code (my ping cmd):

const Discord = require('discord.js')

module.exports = {
    name: "ping",
    description: "ping command",
    cooldown: 2000,

    async run(bot, message, args, sleep) {
        message.channel.send("Pinging... <a:870735815062462464:878533686499356683>").then(async m => {
            var ping = m.createdTimestamp - message.createdTimestamp;

            await sleep(1000)

            var embed = new Discord.MessageEmbed()
                .setColor("#ffffff")
                .setAuthor(`${ping}ms`)

            m.delete()
            m.channel.send("Pong! :ping_pong:", embed)
        })
    }
}
        })

I get an error message from the code above:

(node:4) UnhandledPromiseRejectionWarning: TypeError: sleep is not a function
     at /app/commands/General/ping.js:12:19
     at processTicksAndRejections (internal/process/task_queues.js:95:5)
 (Use `node --trace-warnings ...` to show where the warning was created)
 (node:4) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)
(node:4) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code

Before you say the function is not defined, I have defined the function globally in my index file

const Discord = require('discord.js');

const bot = new Discord.Client();

const mongoose = require('mongoose')
mongoose.connect('mongodb+srv://Blue_Crafter:***@***.ecxew.mongodb.net/Data', {
    useUnifiedTopology: true,
    useNewUrlParser: true,
    useFindAndModify: false
}).then(console.log('Connected to MongoDB'))

const { token } = require('./config.json');

const { readdirSync, read } = require('fs');
const ms = require('ms');

const Levels = require('discord-xp')
Levels.setURL("mongodb+srv://Blue_Crafter:***@***.ecxew.mongodb.net/Data")

const config = require('./config.json');
bot.config = config;


bot.commands = new Discord.Collection();
const commandFolders = readdirSync('./commands');
const Timeout = new Discord.Collection();

const PrefixSchema = require('./Schema/presch')

//------------------------------------------------------------------------------
for (const folder of commandFolders) {
    const commandFiles = readdirSync(`./commands/${folder}`).filter(file => file.endsWith('.js'));
    for (const file of commandFiles) {
        const command = require(`./commands/${folder}/${file}`);
        bot.commands.set(command.name, command);
    }
}

bot.on("error", console.error);


//------------------------------------------------------------------------------
bot.on('ready', () => {
    console.log('Powered on!');
    const statusArray = ['a>help, WATCHING', //More statuses];

    setInterval(() => {
        const random = statusArray[Math.floor(Math.random() * statusArray.length)].split(', ')
        const status = random[0];
        const mode = random[1];
        bot.user.setActivity(status, { type: mode })

    }, 20000);
})
//------------------------------------------------------------------------------
const lvlschema = require('./Schema/lvltog')
bot.on("message", async (message) => {
    const idarray = ['***']

    if (message.author.bot) return;
    if (message.channel.type === 'dm') return; //optional#
    if (message.author.id === idarray) return


    var prefix;
    let data = await PrefixSchema.findOne({ guildID: message.guild.id })
if (data === null) { 
    prefix = "a>"
}
else { 
prefix = data.newPrefix
}

    const sleep = (ms) => { 
        return new Promise(resolve => 
            setTimeout(resolve, ms)
            );
      }

    if (message.content.startsWith(prefix)) {
        const args = message.content.slice(prefix.length).trim().split(/ +/);

        const commandName = args.shift().toLowerCase();

        const command = bot.commands.get(commandName) || bot.commands.find(cmd => cmd.aliases && cmd.aliases.includes(commandName));
        if (!command) return;

        if (command) {
            if (command.cooldown) {
                if (Timeout.has(`${command.name}${message.author.id}`)) return message.channel.send(`Please wait **${ms(Timeout.get(`${command.name}${message.author.id}`) - Date.now(), { long: true })}** before using this command again!`)
                command.run(bot, message, args)
                Timeout.set(`${command.name}${message.author.id}`, Date.now() + command.cooldown)
                setTimeout(() => {
                    Timeout.delete(`${command.name}${message.author.id}`)
                }, command.cooldown)
//Here is where it exports the variables
            } else command.run(bot, message, args, sleep);
        }
    }
})


bot.login(token);        

Any fixes? I need something ASAP

blueCrafter6
  • 191
  • 2
  • 8

1 Answers1

1

In node.js, if you declare a variable inside your index.js file, it won't be available in your ping.js file. Although you say that you "have defined the function globally", it's not global. It's only available inside your index.js file.

If you want to use this function in other files, you can export it:

// index.js
// ...
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))
module.exports = { sleep }
// ...

and import it in other the file(s):

// ping.js
// ...
const { sleep } = require('../../index.js') // make sure the path is correct
// ...

Now, you can use sleep in your other files.

Zsolt Meszaros
  • 21,961
  • 19
  • 54
  • 57