【问题标题】:My sleep function not working for certain commands, how do I fix it? (discord.js) [duplicate]我的睡眠功能不适用于某些命令,我​​该如何解决? (discord.js)[重复]
【发布时间】:2022-01-11 13:30:59
【问题描述】:

[已修复] 我的睡眠功能曾经适用于我的所有命令。我没有对该函数做任何事情,但不知何故它现在只适用于 certain 命令(在代码中);喜欢这里:

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 <@***>`)

但不适用于此命令代码(我的 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)
        })
    }
}
        })

我从上面的代码中收到一条错误消息:

(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

在你说函数没有定义之前,我已经在我的索引文件中全局定义了函数

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);        

任何修复?我需要尽快的东西

【问题讨论】:

  • 您是从index.js 导出sleep 函数并将其导入到您的ping.js 文件中,还是只是期待它以某种方式神奇地出现在那里?
  • @ZsoltMeszaros 问题已编辑

标签: javascript node.js discord.js


【解决方案1】:

在 node.js 中,如果您在 index.js 文件中声明了一个变量,那么它在您的 ping.js 文件中将不可用。虽然你说你“已经全局定义了函数”,但它不是全局的。它仅在您的 index.js 文件中可用。

如果你想在其他文件中使用这个功能,你可以导出它:

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

并将其导入其他文件:

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

现在,您可以在其他文件中使用sleep

【讨论】:

  • 我有一个命令处理程序,所以我用它来导出参数,如 args、客户端、消息。我使用我的 cmd 处理程序导出了我的睡眠函数,它工作正常。但现在,它只适用于某些命令
  • 好的,编辑完后给我ping :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-21
  • 1970-01-01
  • 2020-09-11
  • 2021-02-11
相关资源
最近更新 更多