繁体   English   中英

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

[英]How do I set a variable to a specific voice channel discord.js?

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

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

  const voiceChannel = channel_ID;

  const voiceChannel = channel.id(channel_ID);

(其中 channel_ID 是 discord 分配的实际 ID 号)

我查看了 discord.js.org,但找不到解决方案。

我可能正在做一些非常明显的错误,但我无法弄清楚它是什么。 有任何想法吗?

您可以将变量存储为任何内容,因为 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);

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

如何获得(您的) channel的( ID )?

好吧,您有两种选择:

  • Discord中激活developer mode > 右键单击target channel和 select 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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM