title: Discord.js YouTube Search and Play
body: <p>I am trying to make discord bot that will play some music but I can't manage to make search command correctly ( Now I need to type command .f press enter and then put that what I want to search and I want it to just .f [what i want to search]) but doesn't know how to. I tried many guides but still nothing, also I would like to have that after searching and choosin what to I meant to play bot automatically join and play it (I made it buut in weird way and I know there is easier way but I am dumb for it.</p>
  
  <p>TL;DR: Search command that will search and play with ".f [what to search]".</p>
  
  <p>Whole code if it wil help:</p>
  
  <pre><code>const { Client } = require("discord.js");
  const config = require('./config.json')
  const Discord = require("discord.js");
  const ytdl = require('ytdl-core');
  const search = require("youtube-search")
  const opts = {
    maxResults: 25,
    key: config.YOUTUBE_API,
    type: 'video'
  }
  const queue = new Map();
  
  const client = new Client({
      disableEveryone: true
  
  });
  
  
  
  client.on("ready", () =&gt; {
      console.log(`ŻYJE I JAM JEST ${client.user.username} `);
  
  
  });
  client.on("message", async message =&gt; {
      console.log(`${message.author.username} mówi: ${message.content}`)
  });
  
  client.on("message", async message =&gt; {
      if (!message.content.startsWith('.')) return;
  
      const serverQueue = queue.get(message.guild.id);
  
      if (message.content.startsWith(`.p`, '.play', '.pla', '.pl')) {
        execute(message, serverQueue);
        return;
      } else if (message.content.startsWith(`.s`, '.skip', '.sk', '.ski')) {
        skip(message, serverQueue);
        return;
      } else if (message.content.startsWith(`.l`, '.leave', '.le', '.lea', '.leav')) {
        stop(message, serverQueue);
        return;
  
  
      };
  
  
  
  
  
      if (message.content.toLowerCase() === '.f') {
        let embed = new Discord.MessageEmbed()
            .setColor("#00FE0C")
            .setDescription("Czego szukasz? Opowiedz mi dokładniej.")
            .setTitle("Wyszukiwarka")
            .setThumbnail('https://i.imgur.com/vs6ulWc.gif')
        let embedMsg = await message.channel.send(embed);
        let filter = m =&gt; m.author.id === message.author.id;
        let query = await message.channel.awaitMessages(filter, { max: 1});
        let results = await search(query.first().content, opts).catch(err =&gt; console.log(err))
        if(results) {
          let youtubeResults = results.results;
          let i =0;
          let titles = youtubeResults.map(result =&gt; {
            i++;
            return i + ") " + result.title;
  
          });
          console.log(titles);
          message.channel.send({
            embed : {
              title: "Wybieraj mordo",
              description: titles.join("\n")
            }
          }).catch(err =&gt; console.log(err));
  
          filter = m =&gt; (m.author.id === message.author.id) &amp;&amp; m.content &gt;= 1 &amp;&amp; m.content &lt;= youtubeResults.length;
          let collected = await message.channel.awaitMessages(filter, { max: 1 });
          let selected = youtubeResults[collected.first().content - 1];
  
          embed = new Discord.MessageEmbed()
            .setColor("#00FE0C")
            .setTitle(`${selected.title}`)
            .setURL(`${selected.link}`)
            .setDescription(`${selected.description}`)
            .setThumbnail(`${selected.thumbnails.default.url}`);
  
          message.channel.send(embed)
          if (message.member.voice.channel) {
            const connection = await message.member.voice.channel.join();
            await message.channel.send(`.p ${selected.link}`).then(d_msg =&gt; { d_msg.delete({ timeout: 1500 })})
          }
  
        };
      };
  
  });
  
  
  
  
  
  
  
  async function execute(message, serverQueue) {
      const args = message.content.split(" ");
  
      const voiceChannel = message.member.voice.channel;
      if (!voiceChannel)
        return message.channel.send(
          "No wbij Mordunio na kanał najpierw!"
        );
      const permissions = voiceChannel.permissionsFor(message.client.user);
      if (!permissions.has("CONNECT") || !permissions.has("SPEAK")) {
        return message.channel.send(
          "Dawaj klucze do kantorka to wbije!"
        );
      }
  
      const songInfo = await ytdl.getInfo(args[1]);
      const song = {
        title: songInfo.title,
        url: songInfo.video_url
      };
  
      if (!serverQueue) {
        const queueContruct = {
          textChannel: message.channel,
          voiceChannel: voiceChannel,
          connection: null,
          songs: [],
          volume: 5,
          playing: true
        };
  
        queue.set(message.guild.id, queueContruct);
  
        queueContruct.songs.push(song);
  
        try {
          var connection = await voiceChannel.join();
          queueContruct.connection = connection;
          play(message.guild, queueContruct.songs[0]);
        } catch (err) {
          console.log(err);
          queue.delete(message.guild.id);
          return message.channel.send(err);
        }
      } else {
        serverQueue.songs.push(song);
        return message.channel.send(`**${song.title}** został do kolejeczki dodany Byku!`);
      }
  }
  
  function skip(message, serverQueue) {
      if (!message.member.voice.channel)
        return message.channel.send(
          "Nie zatrzymasz mnie! Ciebie tu nie ma!"
        );
      if (!serverQueue)
        return message.channel.send("A co miałabym pominąć");
      serverQueue.connection.dispatcher.end();
  }
  
  function stop(message, serverQueue) {
      if (!message.member.voice.channel)
        return message.channel.send(
          "Musisz tu byyyyć byyyyyku!!"
        );
      serverQueue.songs = [];
      serverQueue.connection.dispatcher.end();
  }
  
  function play(guild, song, message) {
      const serverQueue = queue.get(guild.id);
      if (!song) {
        serverQueue.voiceChannel.leave();
        queue.delete(guild.id)
        return;
      }
  
      const dispatcher = serverQueue.connection
        .play(ytdl(song.url))
        .on("finish", () =&gt; {
          serverQueue.songs.shift();
          play(guild, serverQueue.songs[0]);
        })
        .on("error", error =&gt; console.error(error));
      dispatcher.setVolumeLogarithmic(serverQueue.volume / 5);
      serverQueue.textChannel.send(`Gram: **${song.title}**`);
  
  
  };
  
  
  
  client.login(config.TOKEN);
  </code></pre>