组合误差(2).我怎么修理它?bot期望未定义或null和字符串原语返回



我正在创建一个支持斜杠命令的音乐机器人。它做得很好,当我嵌入一个url到一个单一的歌曲。但是,当我试图把一个链接到播放列表,它返回两个错误。

CombinedError (2)
Received one or more errors
1 ValidationError > s.nullish
|   Expected undefined or null
|
|   Received:
|   | Thumbnail {
|   |   id: null,
|   |   width: 336,
|   |   height: 188,
|   |   url:
|   |    'https://i.ytimg.com/vi/U7L-3VXAkSA/hqdefault.jpg?sqp=-oaymwEXCNACELwBSFryq4qpAwkIARUAAIhCGAE=&rs=AOn4CLADvf4gOVhdVe-L0E8w-HsOCrvOfA' }
2 ValidationError > s.string
|   Expected a string primitive
|
|   Received:
|   | Thumbnail {
|   |   id: null,
|   |   width: 336,
|   |   height: 188,
|   |   url:
|   |    'https://i.ytimg.com/vi/U7L-3VXAkSA/hqdefault.jpg?sqp=-oaymwEXCNACELwBSFryq4qpAwkIARUAAIhCGAE=&rs=AOn4CLADvf4gOVhdVe-L0E8w-HsOCrvOfA' }
at UnionValidator.handle (C:UserssomeoneDesktopNewMusicnode_modules@sapphireshapeshiftdistindex.js:1088:23)
at UnionValidator.parse (C:UserssomeoneDesktopNewMusicnode_modules@sapphireshapeshiftdistindex.js:201:88)
at EmbedBuilder.setThumbnail (C:UserssomeoneDesktopNewMusicnode_modules@discordjsbuildersdistindex.js:257:23)
at Object.execute (C:UserssomeoneDesktopNewMusiccommandsplay.js:80:18)
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
at async Client.<anonymous> (C:UserssomeoneDesktopNewMusicindex.js:72:9)type here

这是我的播放音乐的play.js

const { SlashCommandBuilder } = require("@discordjs/builders")
const { EmbedBuilder } = require("discord.js")
const { QueryType } = require("discord-player")
module.exports = {
data: new SlashCommandBuilder()
.setName("play")
.setDescription("play a song from YouTube.")
.addSubcommand(subcommand =>
subcommand
.setName("search")
.setDescription("Searches for a song and plays it")
.addStringOption(option =>
option.setName("searchterms").setDescription("search keywords").setRequired(true)
)
)
.addSubcommand(subcommand =>
subcommand
.setName("playlist")
.setDescription("Plays a playlist from YT")
.addStringOption(option => option.setName("url").setDescription("the playlist's url").setRequired(true))
)
.addSubcommand(subcommand =>
subcommand
.setName("song")
.setDescription("Plays a single song from YT")
.addStringOption(option => option.setName("url").setDescription("the song's url").setRequired(true))
),
execute: async ({ client, interaction }) => {
// Make sure the user is inside a voice channel
if (!interaction.member.voice.channel) return interaction.reply("You need to be in a Voice Channel to play a song.");
// Create a play queue for the server
const queue = await client.player.createQueue(interaction.guild);
// Wait until you are connected to the channel
if (!queue.connection) await queue.connect(interaction.member.voice.channel)
let embed = new EmbedBuilder()
if (interaction.options.getSubcommand() === "song") {
let url = interaction.options.getString("url")

// Search for the song using the discord-player
const result = await client.player.search(url, {
requestedBy: interaction.user,
searchEngine: QueryType.YOUTUBE_VIDEO
})
// finish if no tracks were found
if (result.tracks.length === 0)
return interaction.reply("No results")
// Add the track to the queue
const song = result.tracks[0]
await queue.addTrack(song)
embed
.setDescription(`**[${song.title}](${song.url})** has been added to the Queue`)
.setThumbnail(song.thumbnail)
.setFooter({ text: `Duration: ${song.duration}`})
}
else if (interaction.options.getSubcommand() === "playlist") {
// Search for the playlist using the discord-player
let url = interaction.options.getString("url")
const result = await client.player.search(url, {
requestedBy: interaction.user,
searchEngine: QueryType.YOUTUBE_PLAYLIST
})
if (result.tracks.length === 0)
return interaction.reply(`No playlists found with ${url}`)

// Add the tracks to the queue
const playlist = result.playlist
await queue.addTracks(result.tracks)
embed
.setDescription(`**${result.tracks.length} songs from [${playlist.title}](${playlist.url})** have been added to the Queue`)
.setThumbnail(playlist.thumbnail)
} 
else if (interaction.options.getSubcommand() === "search") {
// Search for the song using the discord-player
let url = interaction.options.getString("searchterms")
const result = await client.player.search(url, {
requestedBy: interaction.user,
searchEngine: QueryType.AUTO
})
// finish if no tracks were found
if (result.tracks.length === 0)
return interaction.editReply("No results")

// Add the track to the queue
const song = result.tracks[0]
await queue.addTrack(song)
embed
.setDescription(`**[${song.title}](${song.url})** has been added to the Queue`)
.setThumbnail(song.thumbnail)
.setFooter({ text: `Duration: ${song.duration}`})
}
// Play the song
if (!queue.playing) await queue.play()

// Respond with the embed containing information about the player
await interaction.reply({
embeds: [embed]
})
},
}

这是index.js

require('dotenv').config();
const {REST} = require('@discordjs/rest');
const { Routes } = require('discord-api-types/v9');
const { Client, GatewayIntentBits, Collection } = require("discord.js");
const { Player } = require("discord-player")
const fs = require('fs');
const path = require('path');

const  client = new Client({
intents: [
GatewayIntentBits.GuildMessages,
GatewayIntentBits.Guilds,
GatewayIntentBits.MessageContent,
GatewayIntentBits.GuildVoiceStates,
GatewayIntentBits.GuildPresences,
GatewayIntentBits.GuildMembers,
GatewayIntentBits.GuildScheduledEvents,
GatewayIntentBits.GuildMessageReactions,
GatewayIntentBits.GuildVoiceStates,
],
});
// List of all commands
const commands = [];
client.commands = new Collection();
const commandsPath = path.join(__dirname, "commands"); // E:ytdiscord botjsintrocommands
const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.js'));
for(const file of commandFiles)
{
const filePath = path.join(commandsPath, file);
const command = require(filePath);
client.commands.set(command.data.name, command);
commands.push(command.data.toJSON());
}
// Add the player on the client
client.player = new Player(client, {
ytdlOptions: {
quality: "highestaudio",
highWaterMark: 1 << 25
}
})
client.on("ready", () => {
// Get all ids of the servers
const guild_ids = client.guilds.cache.map(guild => guild.id);

const rest = new REST({version: '9'}).setToken(process.env.TOKEN);
for (const guildId of guild_ids)
{
rest.put(Routes.applicationGuildCommands(process.env.CLIENT_ID, guildId), 
{body: commands})
.then(() => console.log('Successfully updated commands for guild ' + guildId))
.catch(console.error);
}
});
client.on("interactionCreate", async interaction => {
if(!interaction.isCommand()) return;
const command = client.commands.get(interaction.commandName);
if(!command) return;
try
{
await command.execute({client, interaction});
}
catch(error)
{
console.error(error);
await interaction.reply({content: "There was an error executing this command"});
}
});
client.login(process.env.TOKEN);

我不知道如何解决这个问题。有人能帮忙吗?我使用node.js v19和discord.js v14

.setThumbnail(playlist.thumbnail)应该是.setThumbnail(playlist.thumbnail.url),因为playlist.thumbnail是对象,setThumbnail接受字符串作为URL。

相关内容

最新更新