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 switch (play.yt_validate(input)) {
7 case 'video':
8 const info = await play.video_basic_info(input);
9 return [info.video_details];
10 case 'search':
11 const results = await play.search(input, { source: { youtube: 'video' }, limit: 1 });
12
13 if (results.length == 0)
14 return [];
15
16 const firstResult = results[0];
17 return [firstResult];
18 case 'playlist':
19 const playlist = await play.playlist_info(input, { incomplete: true });
20 return await playlist.all_videos();
21 default:
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
45 const yt_videos = await handleUserInput(input);
46 const added = await playUrls(yt_videos, channel);
47
48 switch (added.length) {
49 case 0:
50 return await interaction.editReply('No videos were added to the queue.');
51 case 1:
52 return await interaction.editReply(`Added ${formatTitle(added[0])} to queue.`);
53 default:
54 return await interaction.editReply(`Added ${added.length} videos to queue.`);
55 }
56 },
57};