src/commands/play.ts (view raw)
1import { ChatInputCommandInteraction, SlashCommandBuilder } from 'discord.js';
2import play, { YouTubeVideo } from 'play-dl';
3import { playUrls, getChannel, formatTitle } from '../functions/music';
4
5async function handleUserInput(input: string): Promise<YouTubeVideo[]> {
6 try {
7 switch (play.yt_validate(input)) {
8 case 'video':
9 const info = await play.video_basic_info(input);
10 return [info.video_details];
11 case 'playlist':
12 const playlist = await play.playlist_info(input, { incomplete: true });
13 return await playlist.all_videos();
14 case 'search':
15 const results = await play.search(input, { source: { youtube: 'video' }, limit: 1 });
16 if (results.length > 0) return [results[0]];
17 default:
18 return [];
19 }
20 } catch (error) {
21 console.error(error);
22 return [];
23 }
24}
25
26module.exports = {
27 data: new SlashCommandBuilder()
28 .setName('play')
29 .setDescription('Play something off YouTube.')
30 .addStringOption((option) => option
31 .setName('query')
32 .setDescription('YouTube URL or search query')
33 .setRequired(true),
34 ),
35
36 async execute(interaction: ChatInputCommandInteraction) {
37 const channel = await getChannel(interaction);
38 if (typeof channel == 'string')
39 return await interaction.reply({ content: channel, ephemeral: true });
40
41 await interaction.deferReply();
42 const opt = interaction.options;
43 const input = opt.getString('query');
44 const yt_videos = await handleUserInput(input);
45 const added = await playUrls(yt_videos, channel);
46
47 switch (added.length) {
48 case 0:
49 return await interaction.editReply('No videos were added to the queue.');
50 case 1:
51 return await interaction.editReply(`Added ${formatTitle(added[0])} to queue.`);
52 default:
53 return await interaction.editReply(`Added ${added.length} videos to queue.`);
54 }
55 },
56};