all repos — simple-discord-music-bot @ f47db6558591aa10292c163eeb24ceed1becab50

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

commands/play.js (view raw)

 1const path = require("node:path");
 2const { SlashCommandBuilder } = require("discord.js");
 3const {
 4  createAudioResource,
 5  createAudioPlayer,
 6  joinVoiceChannel,
 7  NoSubscriberBehavior,
 8  AudioPlayerStatus,
 9} = require("@discordjs/voice");
10
11const play = require('play-dl')
12
13//const reg = /^((?:https?:)?\/\/)?((?:www|m)\.)?((?:youtube(-nocookie)?\.com|youtu.be))(\/(?:[\w\-]+\?v=|embed\/|v\/)?)([\w\-]+)(\S+)?$/;
14
15module.exports = {
16  data: new SlashCommandBuilder()
17    .setName("play")
18    .setDescription("Play something off YouTube.")
19    .addStringOption((option) => option
20        .setName("query")
21        .setDescription("YouTube URL or search query")
22        .setRequired(true)
23    ),
24
25  async execute(interaction) {
26    const member = interaction.member;
27    if (!member)
28      return await interaction.reply({ content: "Please use this in your current server.", ephemeral: true });
29
30    const user_connection = member.voice;
31    const channel = user_connection.channel;
32
33    if (!channel)
34      return await interaction.reply({ content: "You're not in a voice channel.", ephemeral: true });
35
36    await interaction.deferReply();
37    const guild = channel.guild;
38
39    // Get the YouTube URL or search query
40    let url = interaction.options.getString("query");
41
42    let video;
43    switch (play.yt_validate(url)) {
44      case "video":
45        video = {url: url};
46        break;
47      
48      case "search":
49        yt_info = await play.search(url, { source : { youtube : "video" }, limit: 1 });
50
51        if(yt_info.length === 0)
52          return await interaction.editReply(`No results found.`);
53
54        video = yt_info[0];
55        break;
56    
57      default:
58        return await interaction.editReply(`Not supported.`);
59    }
60    let stream = await play.stream(video.url);
61
62    // Connect to the user's voice channel
63    const connection = joinVoiceChannel({
64      channelId: channel.id,
65      guildId: guild.id,
66      adapterCreator: guild.voiceAdapterCreator,
67    });
68
69    let resource = createAudioResource(stream.stream, {
70      inputType: stream.type
71    })
72
73    player = createAudioPlayer({
74      behaviors: { noSubscriber: NoSubscriberBehavior.Play }
75    });
76
77    player.on(AudioPlayerStatus.Idle, () => {
78      player.stop();
79      player.subscribers.forEach((element) => element.connection.disconnect());
80    });
81
82    player.play(resource);
83    connection.subscribe(player);
84    return await interaction.editReply(`Playing ${video.url}`);
85  },
86};