如何将变量设置为特定的语音通道discord.js



我正在尝试将variable设置为特定的voice channel,这样我就可以让机器人始终在同一通道中工作,而不是在用户所在的任何通道中工作。我是js和编写discord-bots的新手。我的大部分代码都来自这里。

到目前为止,我已经尝试了的所有我能想到的东西

const voiceChannel = channel_ID;

const voiceChannel = channel.id(channel_ID);

(其中channel_ID是不一致分配的实际ID号(

我在discord.js.org上找过,但找不到解决方案。

我可能做错了一件非常明显的事,但我不知道是什么。有什么想法吗?

因此,为了在特定的channeljoin您的机器人,您首先必须实际获得channel

如何获得channel的(ID(

好吧,你有两个选择:

  • 激活Discord中的developer mode>右键单击target channel并选择Copy ID>将其粘贴到代码中
const channelId = '1234567890';
const targetChannel = client.channels.cache.get(channelId);
  • 按名称获取channel
const targetChannel = guild.channels.cache.find(channel => channel.name === "Name of the channel");

如果这样做了,你现在应该有你的channel,但这还不是全部

现在你想检查一下,如果你的机器人真的有channel,如果你想使用.join(),你必须确保它是VoiceChannel:

// Check if the channel is undefined or not
if(!targetChannel) return message.channel.send('Channel not found!');
// Check if the channel is a voice channel
if(targetChannel.type !== 'voice') return message.channel.send('This is not a voice channel!');
// If it passed the code above you can now let your bot join the channel
targetChannel.join().then(connection => {
console.log("Successfully connected.");
}).catch(e => {

console.error(e);

您可以将变量存储为任何值,因为ID是一组整数,所以可以在没有quotes("(template literals(``(管在使用parseInt()等方法时可能会发生冲突,但我们将其存储为字符串。假设我们现在有一个ID,并将其存储为:

const Channel = ('ChannelID');
var Channel = ('ChannelID');
let Channel = ('ChannelID'); // of course only one of these 

其中ChannelID是实际ID,现在我们可以稍后访问它来获取/获取通道,如下所示:

<client>.channels.cache.get(Channel) || <client>.channels.fetch(Channel);

最新更新