开发Discord机器人播放命令时遭遇TypeError: adapterCreator is not a function错误求助
Hey there, let's break down why you're hitting that TypeError: adapterCreator is not a function error and fix your play command step by step.
1. You're accessing the voice channel incorrectly
Right now you're setting GuildMember to message.author.id—that's just a string, not a guild member object. You can't get a voice channel from a user ID. Instead, use message.member (which represents the user's presence in the server) to access their voice state.
2. Typo in the adapterCreator reference
You wrote voiceAdatperCreator (missing an 'd' in "Adapter") instead of the correct voiceAdapterCreator. Also, you don't need to go through message.channel.guild—message.guild directly gives you the server object, which has the voiceAdapterCreator property.
3. Missing a check for voice channel presence
If the user isn't in a voice channel at all, your code will throw another error when trying to fetch the channel ID. Let's add a quick check to handle that case first.
Here's the corrected version of your code with all these fixes applied:
const ytdl = require('ytdl-core'); const { joinVoiceChannel, createAudioPlayer, createAudioResource, generateDependencyReport } = require('@discordjs/voice'); module.exports = { name: 'play', description: 'Plays audio from YouTube', async execute(message, args) { // Check if user is in a voice channel first if (!message.member.voice.channel) { return message.reply('You need to join a voice channel to use this command!'); } const url = 'https://www.youtube.com/watch?v=NevKVKbCNy4&ab_channel=NTDM'; // Add highWaterMark to prevent stream buffering issues const stream = ytdl(url, { filter: 'audioonly', highWaterMark: 1 << 25 }); const player = createAudioPlayer(); const resource = createAudioResource(stream); // Correct voice connection setup const connection = joinVoiceChannel({ channelId: message.member.voice.channel.id, guildId: message.guild.id, adapterCreator: message.guild.voiceAdapterCreator, }); connection.subscribe(player); player.play(resource); console.log(generateDependencyReport()); message.reply(`Now playing your requested track!`); }, };
Extra Tips to Avoid Future Issues
- Make sure you have all required dependencies installed:
@discordjs/voice,discord.js,ytdl-core, and@discordjs/opus(for audio encoding). - If you want users to pass custom URLs via command arguments, add logic to use
args[0]as the URL and validate it withytdl.validateURL(). - Add error handling for the audio player to catch stream failures:
player.on('error', error => { console.error(`Player error: ${error.message}`); message.reply('Oops, there was an issue playing that audio!'); });
内容的提问来源于stack exchange,提问作者Gio23

