这是我的代码:

const { SlashCommandBuilder } = require('@discordjs/builders');
const { createAudioPlayer, createAudioResource, joinVoiceChannel } = require('@discordjs/voice');
const ytdl = require('ytdl-core');
const { EmbedBuilder } = require('discord.js');

module.exports = {
  data: new SlashCommandBuilder()
    .setName('play')
    .setDescription('Play a song in your current voice channel')
    .addStringOption(option =>
      option.setName('song')
        .setDescription('Enter the YouTube URL or keywords to search for')
        .setRequired(true)),
  async execute(interaction) {
    const song = interaction.options.getString('song');

    // Check if the user is in a voice channel
    if (!interaction.member.voice.channel) {
      return interaction.reply({ content: 'You are not in a voice channel!', ephemeral: true });
    }

    // Join the user's voice channel
    const connection = joinVoiceChannel({
      channelId: interaction.member.voice.channel.id,
      guildId: interaction.guildId,
      adapterCreator: interaction.guild.voiceAdapterCreator
    });

    // Get video info and create an audio resource
    const videoInfo = await ytdl.getInfo(song);
    const stream = ytdl(song, { filter: 'audioonly' });
    const resource = createAudioResource(stream);

    // Create an audio player and play the resource
    const player = createAudioPlayer();
    player.play(resource);

    // Subscribe the connection to the player
    connection.subscribe(player);

    // Send a confirmation message
    const embed = new EmbedBuilder()
      .setColor("Green")
      .setTitle('Now Playing')
      .setDescription(`[${videoInfo.videoDetails.title}](${song})`)
      .setThumbnail(videoInfo.videoDetails.thumbnails[0].url);
    interaction.reply({ embeds: [embed] });
  },
};

这是一个允许用户在他们所在的语音频道中播放音乐的命令.用户必须在语音通道上,运行命令,然后机器人将连接到与用户相同的通道.问题是,当我在语音通道上时,它也会发送'You are not in a voice channel!',而不会进入下一步!我认为问题出在这里:

if (!interaction.member.voice.channel) {
      return interaction.reply({ content: 'You are not in a voice channel!', ephemeral: true });
    }

有没有人可以帮我解决这个问题(如果你发现任何其他问题,也请让我知道.)提前谢谢!

我有以下意图:[Guilds, GuildMembers, GuildMessages, MessageContent, DirectMessages].

注:

This articlethis不能解决我的案子,它也不是复制品.

推荐答案

您还需要添加GuildVoiceStates个意图才能查看语音状态更改.否则,当你启动你的机器人时,interaction.member.voice将总是返回语音状态的"快照".

如果没有GuildVoiceStates个意向变化,检测不到;如果当你启动你的机器人时,成员已经连接,interaction.member.voice将正确地返回语音状态,但如果他们被断开连接,你再次判断它,值是相同的,所以他们似乎仍然在那个语音通道中.

Javascript相关问答推荐

在分区内迭代分区

使用AJX发送表单后,$_Post看起来为空

被CSS优先级所迷惑

按下同意按钮与 puppeteer 师

网页自检测外部元素无法加载

TypeScript索引签名模板限制

如何从一个列表中创建一个2列的表?

用JavaScript复制C#CRC 32生成器

Mongoose post hook在使用await保存时不返回Postman响应

如何从html元素创建树 struct ?

检索相加到点的子项

使用Nuxt Apollo在Piniastore 中获取产品细节

使用带有HostBinding的Angular 信号来更新样式?

元素字符串长度html

如何用javascript更改元素的宽度和高度?

如何根据输入数量正确显示alert ?

是否设置以JavaScript为背景的画布元素?

如何压缩图像并将其编码为文本?

对不同目录中的Angular material 表列进行排序

在范围数组中查找公共(包含)范围