javascript - 从nodejs中的其他js文件访问其他js函数

标签 javascript node.js discord

好吧,我的问题是如何访问 skip.js 文件中的 play.js 文件中的函数。我对 javascript 真的很陌生,所以你可能需要把它简单化才能让我理解。 但我的主要目标是在 skip.js 中使用我的 play.getQueue() 函数。我想我会理解其余的。

这是play.js文件。

const commando = require('discord.js-commando');
var YoutubeDL = require('youtube-dl');
const ytdl = require('ytdl-core');
var bot;
let queues = {};

let MAX_QUEUE_SIZE = 20;
let DEFAULT_VOLUME = 50;
let ALLOW_ALL_SKIP = true;
let CLEAR_INVOKER = false;
class playCommand extends commando.Command {
constructor(client) {
    bot = client;
    super(client, {
        name: 'play',
        group: 'music',
        memberName: 'play',
        description: 'Plays x Song'
    });
}



async run(msg, args) {
    msg.delete(5000);

    // Make sure the user is in a voice channel.
    if (msg.member.voiceChannel === undefined) return msg.channel.sendMessage(wrap('You\'re not in a voice channel.')).then(msg => {
        msg.delete(5000);
    });



    // Get the queue.
    const queue = getQueue(msg.guild.id);

    // Check if the queue has reached its maximum size.
    if (queue.length >= MAX_QUEUE_SIZE) {
        return msg.channel.sendMessage(wrap('Maximum queue size reached!')).then(msg => {
            msg.delete(5000);
        });
    }

    // Get the video information.
    msg.channel.sendMessage(wrap('Searching...')).then(response => {
        var searchstring = args

        if (!args.toLowerCase().startsWith('http')) {
            searchstring = 'gvsearch1:' + args;
        }

        YoutubeDL.getInfo(searchstring, ['-q', '--no-warnings', '--force-ipv4'], (err, info) => {
            // Verify the info.
            if (err || info.format_id === undefined || info.format_id.startsWith('0')) {
                return response.edit(wrap('Invalid video!'));
            }

            info.requester = msg.author.id;

            // Queue the video.
            response.edit(wrap('Queued: ' + info.title)).then(() => {
                queue.push(info);
                // Play if only one element in the queue.
                if (queue.length === 1) executeQueue(msg, queue);
            }).catch(console.log);
        });
    }).catch(console.log);

}


}


/**
 * Checks if a user is an admin.
 * 
 * @param {GuildMember} member - The guild member
 * @returns {boolean} - 
 */
function isAdmin(member) {
    return member.hasPermission("ADMINISTRATOR");
}

/**
 * Checks if the user can skip the song.
 * 
 * @param {GuildMember} member - The guild member
 * @param {array} queue - The current queue
 * @returns {boolean} - If the user can skip
 */
function canSkip(member, queue) {
    if (ALLOW_ALL_SKIP) return true;
    else if (queue[0].requester === member.id) return true;
    else if (isAdmin(member)) return true;
    else return false;
}


function getQueue (server) {

    // Return the queue.
    if (!queues[server]) queues[server] = [];
    return queues[server];
}



function queue(msg, args) {
    // Get the queue.
    const queue = getQueue(msg.guild.id);

    // Get the queue text.
    const text = queue.map((video, index) => (
        (index + 1) + ': ' + video.title
    )).join('\n');

    // Get the status of the queue.
    let queueStatus = 'Stopped';
    const voiceConnection = bot.voiceConnections.find(val => val.channel.guild.id == msg.guild.id);
    if (voiceConnection !== null) {
        const dispatcher = voiceConnection.player.dispatcher;
        queueStatus = dispatcher.paused ? 'Paused' : 'Playing';
    }

    // Send the queue and status.
    msg.channel.sendMessage(wrap('Queue (' + queueStatus + '):\n' + text));
}

function executeQueue(msg, queue) {
    // If the queue is empty, finish.
    if (queue.length === 0) {
        msg.channel.sendMessage(wrap('Playback finished.')).then(msg => {
            msg.delete(5000);
        });

        // Leave the voice channel.
        const voiceConnection = bot.voiceConnections.find(val => val.channel.guild.id == msg.guild.id);
        if (voiceConnection !== null) return voiceConnection.disconnect();
    }

    new Promise((resolve, reject) => {
        // Join the voice channel if not already in one.
        const voiceConnection = bot.voiceConnections.find(val => val.channel.guild.id == msg.guild.id);
        if (voiceConnection === null) {
            // Check if the user is in a voice channel.
            if (msg.member.voiceChannel) {
                msg.member.voiceChannel.join().then(connection => {
                    resolve(connection);
                }).catch((error) => {
                    console.log(error);
                });
            } else {
                // Otherwise, clear the queue and do nothing.
                queue.splice(0, queue.length);
                reject();
            }
        } else {
            resolve(voiceConnection);
        }
    }).then(connection => {
        // Get the first item in the queue.
        const video = queue[0];

        console.log(video.webpage_url);

        // Play the video.
        msg.channel.sendMessage(wrap('Now Playing: ' + video.title)).then(msg => {
            msg.delete(5000);
            let dispatcher = connection.playStream(ytdl(video.webpage_url, {
                filter: 'audioonly'
            }), {
                seek: 0,
                volume: (DEFAULT_VOLUME / 100)
            });

            connection.on('error', (error) => {
                // Skip to the next song.
                console.log(error);
                queue.shift();
                executeQueue(msg, queue);
            });

            dispatcher.on('error', (error) => {
                // Skip to the next song.
                console.log(error);
                queue.shift();
                executeQueue(msg, queue);
            });

            dispatcher.on('end', () => {
                // Wait a second.
                setTimeout(() => {
                    if (queue.length > 0) {
                        // Remove the song from the queue.
                        queue.shift();
                        // Play the next song in the queue.
                        executeQueue(msg, queue);
                    }
                }, 1000);
            });
        }).catch((error) => {
            console.log(error);
        });
    }).catch((error) => {
        console.log(error);
    });
}

function wrap(text) {
    return '```\n' + text.replace(/`/g, '`' + String.fromCharCode(8203)) + '\n```';
}


module.exports = playCommand;

这是skip.js文件

const commando = require('discord.js-commando');
var YoutubeDL = require('youtube-dl');
const ytdl = require('ytdl-core');
var bot;
var play = require('./play');
class skipCommand extends commando.Command {
constructor(client) {
    bot = client;
    super(client, {
        name: 'skip',
        group: 'music',
        memberName: 'skip',
        description: 'skips song'
    });
}

async run(msg, suffix) {
    // Get the voice connection.
    const voiceConnection = bot.voiceConnections.find(val => val.channel.guild.id == msg.guild.id);
    if (voiceConnection === null) return msg.channel.sendMessage(wrap('No music being played.'));

    // Get the queue.
    const queue = play.getQueue(msg.guild.id);

    if (!canSkip(msg.member, queue)) return msg.channel.sendMessage(wrap('You cannot skip this as you didn\'t queue it.')).then((response) => {
        response.delete(5000);
    });

    // Get the number to skip.
    let toSkip = 1; // Default 1.
    if (!isNaN(suffix) && parseInt(suffix) > 0) {
        toSkip = parseInt(suffix);
    }
    toSkip = Math.min(toSkip, queue.length);

    // Skip.
    queue.splice(0, toSkip - 1);

    // Resume and stop playing.
    const dispatcher = voiceConnection.player.dispatcher;
    if (voiceConnection.paused) dispatcher.resume();
    dispatcher.end();

    msg.channel.sendMessage(wrap('Skipped ' + toSkip + '!'));
}



}

function canSkip(member, queue) {
return true;
}

function getQueue(server) {

    // Return the queue.
    if (!queues[server]) queues[server] = [];
    return queues[server];
}


function queue(msg, args) {
// Get the queue.
const queue = play.getQueue(msg.guild.id);

// Get the queue text.
const text = queue.map((video, index) => (
    (index + 1) + ': ' + video.title
)).join('\n');

// Get the status of the queue.
let queueStatus = 'Stopped';
const voiceConnection = bot.voiceConnections.find(val => val.channel.guild.id == msg.guild.id);
if (voiceConnection !== null) {
    const dispatcher = voiceConnection.player.dispatcher;
    queueStatus = dispatcher.paused ? 'Paused' : 'Playing';
}

// Send the queue and status.
msg.channel.sendMessage(wrap('Queue (' + queueStatus + '):\n' + text));
}

function wrap(text) {
return '```\n' + text.replace(/`/g, '`' + String.fromCharCode(8203)) + '\n```';
}

module.exports = skipCommand;

最佳答案

您可以为此使用导出模块

假设您有greetings.js 文件

exports.hello = function(){
  console.log("HELLO");
}

您可以像这样在其他文件(main.js)中访问此 hello 函数

var greetings = require("./greetings.js");
greetings.hello();

输出: 你好

您可以查看此链接以供引用

https://www.sitepoint.com/understanding-module-exports-exports-node-js/

关于javascript - 从nodejs中的其他js文件访问其他js函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44217111/

相关文章:

javascript - 在 HTML 或 JavaScript 中调整图像大小

node.js - 为什么meteor.js是同步的?

java - 按钮交互失败

node.js - NodeJS 返回未处理的 promise 拒绝错误

python - 播放音频时,最后一部分被切断。如何解决这个问题? (不和谐.py)

javascript - ng-table 的 getData 函数中未定义的参数

javascript - (错误)日志记录的最佳实践

javascript - 使用 Phonegap 在 Android 上访问联系人

json - 无法识别 Express REST API 响应方法

javascript - Node server.js 没有响应