all repos — simple-discord-music-bot @ 212dbc349e9c614822b8877c19ca95faa85d7349

A Discord bot making use of discord.js and play-yt.

src/commands/play.ts (view raw)

 1import { ChatInputCommandInteraction, SlashCommandBuilder } from 'discord.js';
 2import play, { YouTubeVideo } from 'play-dl';
 3import { getChannel, formatTitle, getQueue } 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 queue = getQueue(interaction.guildId);
46        const added = await queue.addArray(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};