Discord JS - 从另一个文件的方法导入变量



我有两个命令:连接和断开。Join函数使bot使用方法joinVoiceChannel加入语音通道,而disconnect命令通过使用getVoiceConnection方法从通道中删除bot:
Join .js

const Command = require('../handlers/Command.js');
const { joinVoiceChannel } = require('@discordjs/voice');
module.exports = new Command({
name: "join",
description: "Joins voice channel",
async run(message, args, client) {
const channel = message.member.voice.channel;
if (!channel) return message.channel.send('You need to be in a voice channel.');
const permissions = channel.permissionsFor(message.client.user);
if (!permissions.has('CONNECT') || !permissions.has('SPEAK')) return message.channel.send("You don't have the right permission.");
const connection = joinVoiceChannel({
channelId: channel.id,
guildId: channel.guild.id,
adapterCreator: channel.guild.voiceAdapterCreator,
});
}
});

disconnect.js

const Command = require('../handlers/Command.js');
const { getVoiceConnection } = require('@discordjs/voice');
module.exports = new Command({
name: "disconnect",
description: "Disconnects from the voice channel",
async run(message, args, client) {
try {
const channel = message.member.voice.channel;
const connection = getVoiceConnection(channel.guild.id);
connection.destroy();
} catch (error) { }
}
});

我能否从中导入连接常量join.jsdisconnect.js避免使用其他方法?

访问connection的2种简单方法,无需导出和要求:

  1. 提升到不和客户端对象。这样你就可以访问connection,只要你有访问你的不和谐客户端(通常由clientmessage.client)。当然,这只能在join.js命令至少执行一次后才可用,在此之前,client.connection将是undefined
const connection = joinVoiceChannel({
channelId: channel.id,
guildId: channel.guild.id,
adapterCreator: channel.guild.voiceAdapterCreator,
});
client.connection = connection;
// You can now use client.connection in any file that has client defined
  1. 提升到global对象。与#1类似,但是connection变量与环境的global对象一起被提升,该对象可被节点环境中的所有JavaScript文件访问。
const connection = joinVoiceChannel({
channelId: channel.id,
guildId: channel.guild.id,
adapterCreator: channel.guild.voiceAdapterCreator,
});
global.connection = connection;

相关内容

  • 没有找到相关文章

最新更新