Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ```js
- // index.js
- // ...
- import { Player } from 'discord-player';
- import pkg from '@discord-player/extractor'; // I
- const { YouTubeExtractor, SpotifyExtractor, SoundcloudExtractor, AppleMusicExtractor } = pkg; // Extract relevant extractors
- // ...
- const player = new Player(client)
- player.extractors.register(YouTubeExtractor);
- player.extractors.register(SpotifyExtractor);
- player.extractors.register(SoundcloudExtractor);
- player.extractors.register(AppleMusicExtractor);
- global.player = player
- // ...
- ```
- ```js
- // play.js
- import { SlashCommandBuilder } from 'discord.js';
- export default {
- data: new SlashCommandBuilder()
- .setName('play')
- .setDescription('Play music from a YouTube URL or search term')
- .addStringOption(option =>
- option.setName('query')
- .setDescription('The YouTube URL or search term to play')
- .setRequired(true)
- ),
- async execute(interaction) {
- const query = interaction.options.getString('query');
- const channel = interaction.member.voice.channel;
- if (!channel) {
- return interaction.reply('You need to join a voice channel first!');
- }
- // Ensure the query is a valid string
- if (typeof query !== 'string' || !query.trim()) {
- return interaction.reply('Please provide a valid search query or URL.');
- }
- try {
- // Search for the track using the provided query
- const result = await player.search(query, {
- requestedBy: interaction.user,
- searchEngine: 'ytsearch'
- });
- // If no results are found, inform the user
- if (result.tracks.length === 0) {
- return interaction.reply('No results found for the given query!');
- }
- // Create a queue for the voice channel
- const queue = player.nodes.create(interaction.guild, {
- metadata: {
- channel: interaction.channel,
- },
- });
- // Connect to the voice channel if not already connected
- if (!queue.connection) {
- await queue.connect(channel);
- }
- // Add the first track to the queue
- queue.addTrack(result.tracks[0]);
- // Start playing the track if the bot isn't already playing
- if (!queue.isPlaying()) {
- await queue.play();
- }
- // Inform the user about the track being played
- return interaction.reply(`Now playing **${result.tracks[0].title}**`);
- } catch (error) {
- console.error('Error during play command execution:', error);
- return interaction.reply('An error occurred while trying to play the track.');
- }
- }
- };
- ```
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement