我有两个命令:连接和断开。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.js到disconnect.js避免使用其他方法?
访问connection
的2种简单方法,无需导出和要求:
- 提升到不和客户端对象。这样你就可以访问
connection
,只要你有访问你的不和谐客户端(通常由client
或message.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
- 提升到
global
对象。与#1类似,但是connection
变量与环境的global
对象一起被提升,该对象可被节点环境中的所有JavaScript文件访问。
const connection = joinVoiceChannel({
channelId: channel.id,
guildId: channel.guild.id,
adapterCreator: channel.guild.voiceAdapterCreator,
});
global.connection = connection;