如何让机器人更改语音通道的名称? (Discord.js)

时间:2021-06-02 15:32:26

标签: javascript node.js discord.js bots

我的想法是让机器人根据命令后的文本更改语音通道名称。例如,命令 =changename p 会将人声通道名称更改为 "? Pepper"。但是,我无法让机器人做到这一点。

这是唯一对我有用的代码:

client.on('message', message =>
{
    if (message.channel.id === '748181582241857657') 
    {
        if(!message.content.startsWith(prefix) || message.author.bot) return;

        const args = message.content.slice(prefix.length).split(/ +/);
        const command = args.shift().toLowerCase();
        const channel = '843111736898617384' 
        //The ID of the vocal channel I want to change name
        const name = message.content.replace('=changename ','')

        if (command === 'changename')
        {
            if (name === 'p')
            message.channel.setName('? Pepper')
        }
    }
});

但是,这会更改写入消息的频道的名称,而不是我想要的频道。除此之外的一切都会使机器人崩溃,所以我真的不知道。有什么想法吗?

1 个答案:

答案 0 :(得分:2)

问题在于您更改的是 message.channel 的名称,而不是 ID 为 channel 的名称。

您需要先获取语音通道。您可以使用 guild.channels.resolve(ID) 将 ID 解析为语音通道对象,解析完成后,使用 setName 方法更改其名称。

client.on('message', (message) => {
  if (!message.content.startsWith(prefix) || message.author.bot) return;
  const args = message.content.slice(prefix.length).split(/ +/);
  const command = args.shift().toLowerCase();

  if (command === 'changename') {
    if (!args[0])
      return message.channel.send('You must provide a new channel name');

    const voiceChannelID = '843111736898617384';
    const abbr = {
      a: '? Avocado',
      b: '? Banana',
      c: '? Coconut',
      d: '? Date',
      k: '? Kiwi',
      p: '? Pepper',
    };
    const name = abbr[args[0]];

    if (!name)
      return message.channel.send(`${args[0]} is not a valid channel name`);

    const voiceChannel = message.guild.channels.resolve(voiceChannelID);
    if (!voiceChannel)
      return message.channel.send(
        `Can't find a voice channel with the ID \`${voiceChannelID}\``,
      );

    voiceChannel
      .setName(name)
      .then((newChannel) =>
        message.channel.send(`The channel's new name is ${newChannel.name}`),
      )
      .catch(console.error);
  }
});
相关问题