Advertisement
rjarmon

Discord Music Feature - Local Files

Dec 28th, 2022 (edited)
1,124
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const fs = require('fs');
  2. const path = require('path');
  3. const { createAudioResource, createAudioPlayer, joinVoiceChannel, NoSubscriberBehavior } = require('@discordjs/voice');
  4. const { EmbedBuilder, AttachmentBuilder } = require('discord.js');
  5. const { musicChannelId } = require('../config.json')
  6.  
  7. module.exports = async (client) => {
  8.     // Get the correct voice channel for the server
  9.     const musicChannel = client.channels.cache.get(musicChannelId)
  10.  
  11.         // Join the voice channel
  12.         const connection = joinVoiceChannel({
  13.             channelId: musicChannel.id,
  14.             guildId: musicChannel.guild.id,
  15.             adapterCreator: musicChannel.guild.voiceAdapterCreator,
  16.         });
  17.        
  18.         // Create the audio player
  19.         const player = createAudioPlayer({
  20.             behaviors: {
  21.                 noSubscriber: NoSubscriberBehavior.Pause
  22.             }
  23.         })
  24.  
  25.         // Get the folder containing the song files
  26.         const songsFolder = path.join(__dirname, '../music-feature/songs')
  27.         const imageFolder = path.join(__dirname, '../music-feature/images')
  28.  
  29.         // Read the contents of the folders
  30.         fs.readdir(songsFolder, (err, songFiles) => {
  31.             if (err) {
  32.             console.log(err);
  33.             return;
  34.             }
  35.  
  36.             fs.readdir(imageFolder, (err, imageFiles) => {
  37.             if (err) {
  38.                 console.log(err);
  39.                 return;
  40.             }
  41.  
  42.             // Iterate through the song files and play them
  43.             let trackPosition = 0;
  44.  
  45.             const playNextSong = async () => {
  46.                 const songFile = songFiles[trackPosition];
  47.                 const imageFile = imageFiles[trackPosition];
  48.                 const song = `${songsFolder}/${songFile}`;
  49.                 const image = `${imageFolder}/${imageFile}`;
  50.                 const songName = path.parse(song).name;
  51.                 const attachment = new AttachmentBuilder(image, { name: imageFile } )
  52.                 //TODO Update artistList with the name of the artists in the correct order
  53.                 const artistList = ['Artist 1', 'Artist 2', 'Artist 3', 'Artist 4']
  54.                 const resource = createAudioResource(song, { inlineVolume: true })
  55.                 player.play(resource);
  56.  
  57.                 // Create an embed with the track and artist names
  58.                 const nowPlaying = new EmbedBuilder()
  59.                 .setColor('#4fbaf6')
  60.                 .setTitle(`**Currently playing:**`)
  61.                 .addFields({ name: 'Title:', value: songName, inline: true })
  62.  
  63.                 if (artistList.length >= 1) {
  64.                     nowPlaying.addFields({ name: 'Artist:', value: artistList[trackPosition], inline: true })
  65.                 }
  66.  
  67.                 // Find and delete previous messages in the channel
  68.                 const previousMessages = await musicChannel.messages.fetch()
  69.                 if (previousMessages) await musicChannel.bulkDelete(previousMessages).catch(console.error)
  70.                 // Send track image and details messages
  71.                 await musicChannel.send({ files: [attachment] })
  72.                 await musicChannel.send({ embeds: [nowPlaying] })
  73.            
  74.                 // Increment to the next song
  75.                 await trackPosition++;
  76.                
  77.                 // Upon reaching the end of the playlist, loop back to the top
  78.                 if (trackPosition >= songFiles.length) trackPosition = 0;
  79.             };
  80.            
  81.             connection.subscribe(player)
  82.  
  83.             // Plays songs
  84.             playNextSong();
  85.             // Once current song ends, advance to the next song
  86.             player.on('idle', playNextSong);
  87.         });
  88.     });
  89. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement