rcspotdl
v1.0.0
Published
Spotify downloader library - Download Spotify tracks easily by RiiCODE
Maintainers
Readme
🎵 RcSpotDL
Spotify downloader library - Download and send Spotify tracks directly as audio files
Installation • Quick Start • Documentation • Bot Integration
✨ Features
- 🎵 Download Spotify Tracks - Download any Spotify track easily
- 📤 Direct Audio Send - Send audio files directly to users (no links!)
- 📝 Track Information - Get detailed track metadata
- 🔄 Auto Conversion - Automatically convert Spotify links
- 🚀 Simple API - Clean and intuitive methods
- ⚡ Fast - Optimized performance
- 🛡️ Error Handling - Comprehensive error messages
- 🤖 Bot Ready - Perfect for Telegram & WhatsApp bots
📦 Installation
npm install rcspotdl axiosor with yarn:
yarn add rcspotdl axios🚀 Quick Start
const RcSpotDL = require('rcspotdl');
const axios = require('axios');
const fs = require('fs');
const spotdl = new RcSpotDL();
async function downloadTrack() {
const url = 'https://open.spotify.com/track/3n3Ppam7vgaVa1iaRUc9Lp';
const result = await spotdl.download(url);
if (result.success) {
console.log('Track Info:', result.info);
const response = await axios.get(result.download.downloadUrl, {
responseType: 'arraybuffer'
});
fs.writeFileSync('track.mp3', response.data);
console.log('✅ Audio file saved!');
} else {
console.log('Error:', result.message);
}
}
downloadTrack();📚 Documentation
Initialization
const RcSpotDL = require('rcspotdl');
const spotdl = new RcSpotDL();Methods
info(spotifyUrl)
Get track information from Spotify URL.
Parameters:
spotifyUrl(string) - Spotify track URL
Returns: Promise<Object>
Example:
const result = await spotdl.info('https://open.spotify.com/track/3n3Ppam7vgaVa1iaRUc9Lp');
if (result.success) {
console.log(result.data);
}Success Response:
{
"success": true,
"data": {
"title": "Track Title",
"artist": "Artist Name",
"album": "Album Name",
"duration": "3:45",
"image": "https://..."
},
"creator": "RiiCODE"
}convert(spotifyUrl)
Convert Spotify URL to downloadable link.
Parameters:
spotifyUrl(string) - Spotify track URL
Returns: Promise<Object>
download(spotifyUrl)
Get complete track information and download link.
Parameters:
spotifyUrl(string) - Spotify track URL
Returns: Promise<Object>
🤖 Bot Integration
Telegram Bot Integration
Using Telegraf
const { Telegraf } = require('telegraf');
const RcSpotDL = require('rcspotdl');
const axios = require('axios');
const bot = new Telegraf('YOUR_BOT_TOKEN');
const spotdl = new RcSpotDL();
bot.command('spotdl', async (ctx) => {
const url = ctx.message.text.replace('/spotdl', '').trim();
if (!url) {
return ctx.reply('Usage: /spotdl <spotify_url>\nExample: /spotdl https://open.spotify.com/track/...');
}
if (!url.includes('spotify.com/track/')) {
return ctx.reply('❌ Invalid Spotify track URL!');
}
try {
await ctx.reply('🔍 Fetching track information...');
const result = await spotdl.download(url);
if (!result.success) {
return ctx.reply(`❌ Error: ${result.message}`);
}
const info = result.info;
const download = result.download;
await ctx.reply('⬇️ Downloading audio file...');
const response = await axios.get(download.downloadUrl, {
responseType: 'arraybuffer'
});
const audioBuffer = Buffer.from(response.data);
const caption = `
🎵 *${info.title}*
🎤 Artist: ${info.artist}
📀 Album: ${info.album}
⏱️ Duration: ${info.duration}
_Powered by RcSpotDL by RiiCODE_
`.trim();
await ctx.replyWithAudio(
{ source: audioBuffer },
{
caption: caption,
parse_mode: 'Markdown',
title: info.title,
performer: info.artist,
thumb: info.image ? { url: info.image } : undefined
}
);
} catch (error) {
console.error('Error:', error);
ctx.reply('❌ An error occurred. Please try again later.');
}
});
bot.command('start', (ctx) => {
ctx.reply(`
👋 Welcome to Spotify Downloader Bot!
Commands:
/spotdl <url> - Download Spotify track as audio file
Example:
/spotdl https://open.spotify.com/track/3n3Ppam7vgaVa1iaRUc9Lp
🎵 Audio will be sent directly to you!
Powered by RcSpotDL
`);
});
bot.launch();
console.log('✅ Telegram bot is running...');
process.once('SIGINT', () => bot.stop('SIGINT'));
process.once('SIGTERM', () => bot.stop('SIGTERM'));Using node-telegram-bot-api
const TelegramBot = require('node-telegram-bot-api');
const RcSpotDL = require('rcspotdl');
const axios = require('axios');
const token = 'YOUR_BOT_TOKEN';
const bot = new TelegramBot(token, { polling: true });
const spotdl = new RcSpotDL();
bot.onText(/\/spotdl (.+)/, async (msg, match) => {
const chatId = msg.chat.id;
const url = match[1];
if (!url.includes('spotify.com/track/')) {
return bot.sendMessage(chatId, '❌ Invalid Spotify track URL!');
}
try {
await bot.sendMessage(chatId, '🔍 Fetching track information...');
const result = await spotdl.download(url);
if (!result.success) {
return bot.sendMessage(chatId, `❌ Error: ${result.message}`);
}
const info = result.info;
const download = result.download;
await bot.sendMessage(chatId, '⬇️ Downloading audio file...');
const response = await axios.get(download.downloadUrl, {
responseType: 'arraybuffer'
});
const audioBuffer = Buffer.from(response.data);
const caption = `
🎵 *${info.title}*
🎤 Artist: ${info.artist}
📀 Album: ${info.album}
⏱️ Duration: ${info.duration}
_Powered by RcSpotDL by RiiCODE_
`.trim();
await bot.sendAudio(chatId, audioBuffer, {
caption: caption,
parse_mode: 'Markdown',
title: info.title,
performer: info.artist
});
if (info.image) {
await bot.sendPhoto(chatId, info.image);
}
} catch (error) {
console.error('Error:', error);
bot.sendMessage(chatId, '❌ Error occurred. Please try again.');
}
});
bot.onText(/\/start/, (msg) => {
const chatId = msg.chat.id;
bot.sendMessage(chatId, `
👋 Welcome to Spotify Downloader Bot!
Commands:
/spotdl <url> - Download Spotify track as audio file
Example:
/spotdl https://open.spotify.com/track/3n3Ppam7vgaVa1iaRUc9Lp
🎵 Audio will be sent directly to you!
Powered by RcSpotDL
`);
});
console.log('✅ Telegram bot is running...');WhatsApp Bot Integration
Using @whiskeysockets/baileys
const { default: makeWASocket, DisconnectReason, useMultiFileAuthState } = require('@whiskeysockets/baileys');
const RcSpotDL = require('rcspotdl');
const axios = require('axios');
const spotdl = new RcSpotDL();
async function connectToWhatsApp() {
const { state, saveCreds } = await useMultiFileAuthState('auth_info_baileys');
const sock = makeWASocket({
auth: state,
printQRInTerminal: true
});
sock.ev.on('creds.update', saveCreds);
sock.ev.on('connection.update', (update) => {
const { connection, lastDisconnect } = update;
if (connection === 'close') {
const shouldReconnect = lastDisconnect?.error?.output?.statusCode !== DisconnectReason.loggedOut;
if (shouldReconnect) {
connectToWhatsApp();
}
} else if (connection === 'open') {
console.log('✅ WhatsApp bot connected!');
}
});
sock.ev.on('messages.upsert', async ({ messages }) => {
const msg = messages[0];
if (!msg.message || msg.key.fromMe) return;
const text = msg.message.conversation || msg.message.extendedTextMessage?.text || '';
const from = msg.key.remoteJid;
if (text.startsWith('.spotdl') || text.startsWith('.spotify')) {
const url = text.split(' ')[1];
if (!url) {
await sock.sendMessage(from, {
text: '📚 *Spotify Downloader*\n\nUsage: .spotdl <spotify_url>\n\nExample:\n.spotdl https://open.spotify.com/track/3n3Ppam7vgaVa1iaRUc9Lp\n\n🎵 Audio will be sent directly!\n\n_Powered by RcSpotDL_'
});
return;
}
if (!url.includes('spotify.com/track/')) {
await sock.sendMessage(from, { text: '❌ Invalid Spotify track URL!' });
return;
}
try {
await sock.sendMessage(from, { text: '🔍 Fetching track information...' });
const result = await spotdl.download(url);
if (!result.success) {
await sock.sendMessage(from, { text: `❌ Error: ${result.message}` });
return;
}
const info = result.info;
const download = result.download;
await sock.sendMessage(from, { text: '⬇️ Downloading audio file...' });
const response = await axios.get(download.downloadUrl, {
responseType: 'arraybuffer'
});
const audioBuffer = Buffer.from(response.data);
const caption = `
🎵 *${info.title}*
🎤 Artist: ${info.artist}
📀 Album: ${info.album}
⏱️ Duration: ${info.duration}
━━━━━━━━━━━━━━━━━
_Powered by RcSpotDL by RiiCODE_
`.trim();
if (info.image) {
await sock.sendMessage(from, {
image: { url: info.image },
caption: caption
});
}
await sock.sendMessage(from, {
audio: audioBuffer,
mimetype: 'audio/mp4',
ptt: false,
fileName: `${info.title} - ${info.artist}.mp3`
});
} catch (error) {
console.error('Error:', error);
await sock.sendMessage(from, {
text: '❌ An error occurred. Please try again later.'
});
}
}
if (text === '.menu' || text === '.help') {
const helpMessage = `
┏━━━━━━━━━━━━━━━━━━━━━┓
┃ 🎵 *SPOTIFY DOWNLOADER* ┃
┗━━━━━━━━━━━━━━━━━━━━━┛
*Commands:*
• .spotdl <spotify_url>
Download & send Spotify track as audio
• .menu
Show this menu
*Example:*
.spotdl https://open.spotify.com/track/3n3Ppam7vgaVa1iaRUc9Lp
*Features:*
✓ Direct audio download
✓ High quality MP3
✓ Track information
✓ Fast delivery
━━━━━━━━━━━━━━━━━━━━━
_Powered by RcSpotDL by RiiCODE 2025_
`.trim();
await sock.sendMessage(from, { text: helpMessage });
}
});
return sock;
}
connectToWhatsApp();Advanced WhatsApp Bot Example
const { default: makeWASocket, DisconnectReason, useMultiFileAuthState } = require('@whiskeysockets/baileys');
const RcSpotDL = require('rcspotdl');
const axios = require('axios');
const spotdl = new RcSpotDL();
async function startBot() {
const { state, saveCreds } = await useMultiFileAuthState('auth_info');
const sock = makeWASocket({
auth: state,
printQRInTerminal: true
});
sock.ev.on('creds.update', saveCreds);
sock.ev.on('connection.update', async (update) => {
const { connection, lastDisconnect } = update;
if (connection === 'close') {
const shouldReconnect = lastDisconnect?.error?.output?.statusCode !== DisconnectReason.loggedOut;
if (shouldReconnect) {
startBot();
}
} else if (connection === 'open') {
console.log('✅ Bot connected successfully!');
}
});
sock.ev.on('messages.upsert', async ({ messages, type }) => {
if (type !== 'notify') return;
const msg = messages[0];
if (!msg.message || msg.key.fromMe) return;
const messageType = Object.keys(msg.message)[0];
const messageContent = msg.message[messageType];
const text = messageContent?.text || messageContent?.caption || messageContent || '';
const from = msg.key.remoteJid;
const command = text.toLowerCase().split(' ')[0];
const args = text.slice(command.length).trim();
const reply = async (text) => {
await sock.sendMessage(from, { text }, { quoted: msg });
};
const sendAudio = async (buffer, info) => {
await sock.sendMessage(from, {
audio: buffer,
mimetype: 'audio/mp4',
ptt: false,
fileName: `${info.title} - ${info.artist}.mp3`,
contextInfo: {
externalAdReply: {
title: info.title,
body: `${info.artist} - ${info.album}`,
thumbnailUrl: info.image,
mediaType: 2,
mediaUrl: '',
sourceUrl: ''
}
}
});
};
switch (command) {
case '.spotdl':
case '.spotify':
case '.spot':
if (!args) {
await reply('📝 Usage: .spotdl <spotify_url>\n\nExample: .spotdl https://open.spotify.com/track/...\n\n🎵 Audio will be sent directly to you!');
return;
}
if (!args.includes('spotify.com/track/')) {
await reply('❌ Invalid Spotify track URL!');
return;
}
try {
await reply('🔍 Fetching track information...');
const result = await spotdl.download(args);
if (!result.success) {
await reply(`❌ Error: ${result.message}`);
return;
}
const info = result.info;
const download = result.download;
await reply('⬇️ Downloading audio file...');
const response = await axios.get(download.downloadUrl, {
responseType: 'arraybuffer'
});
const audioBuffer = Buffer.from(response.data);
await reply('📤 Sending audio file...');
await sendAudio(audioBuffer, info);
let infoMessage = `╭─「 🎵 SPOTIFY TRACK 」\n`;
infoMessage += `│ Title: ${info.title}\n`;
infoMessage += `│ Artist: ${info.artist}\n`;
infoMessage += `│ Album: ${info.album}\n`;
infoMessage += `│ Duration: ${info.duration}\n`;
infoMessage += `╰────────────────\n\n`;
infoMessage += `✅ Audio file sent successfully!\n\n`;
infoMessage += `_Powered by RcSpotDL by RiiCODE_`;
await reply(infoMessage);
} catch (error) {
console.error('Error:', error);
await reply('❌ Error: ' + error.message);
}
break;
case '.spotinfo':
if (!args) {
await reply('📝 Usage: .spotinfo <spotify_url>');
return;
}
if (!args.includes('spotify.com/track/')) {
await reply('❌ Invalid Spotify track URL!');
return;
}
try {
await reply('🔍 Fetching track information...');
const result = await spotdl.info(args);
if (!result.success) {
await reply(`❌ Error: ${result.message}`);
return;
}
const info = result.data;
let response = `╭─「 📀 TRACK INFO 」\n`;
response += `│ Title: ${info.title}\n`;
response += `│ Artist: ${info.artist}\n`;
response += `│ Album: ${info.album}\n`;
response += `│ Duration: ${info.duration}\n`;
response += `╰────────────────\n\n`;
response += `_Use .spotdl to download this track_\n\n`;
response += `_Powered by RcSpotDL by RiiCODE_`;
if (info.image) {
await sock.sendMessage(from, {
image: { url: info.image },
caption: response
}, { quoted: msg });
} else {
await reply(response);
}
} catch (error) {
await reply('❌ Error: ' + error.message);
}
break;
case '.menu':
case '.help':
const menu = `
╭─「 🎵 SPOTIFY DOWNLOADER 」
│
│ ⚡ *Commands:*
│ • .spotdl <spotify_url>
│ Download & send audio directly
│
│ • .spotinfo <spotify_url>
│ Get track information only
│
│ • .menu
│ Show this menu
│
│ 📝 *Examples:*
│ .spotdl https://open.spotify.com/track/...
│ .spotinfo https://open.spotify.com/track/...
│
│ 💡 *Features:*
│ ✓ Direct audio download
│ ✓ High quality MP3
│ ✓ Fast delivery
│ ✓ Track metadata
│
╰────────────────
_Powered by RcSpotDL by RiiCODE 2025_
`.trim();
await reply(menu);
break;
}
});
}
startBot();💡 More Examples
Download and Save Locally
const RcSpotDL = require('rcspotdl');
const axios = require('axios');
const fs = require('fs');
const path = require('path');
const spotdl = new RcSpotDL();
async function downloadAndSave(url) {
try {
const result = await spotdl.download(url);
if (result.success) {
console.log('═══════════════════════════════════');
console.log(`🎵 ${result.info.title}`);
console.log(`🎤 Artist: ${result.info.artist}`);
console.log(`📀 Album: ${result.info.album}`);
console.log(`⏱️ Duration: ${result.info.duration}`);
console.log('═══════════════════════════════════');
console.log('⬇️ Downloading audio file...');
const response = await axios.get(result.download.downloadUrl, {
responseType: 'arraybuffer'
});
const filename = `${result.info.title} - ${result.info.artist}.mp3`;
const filepath = path.join(__dirname, 'downloads', filename);
if (!fs.existsSync(path.join(__dirname, 'downloads'))) {
fs.mkdirSync(path.join(__dirname, 'downloads'));
}
fs.writeFileSync(filepath, response.data);
console.log(`✅ Audio saved to: ${filepath}`);
} else {
console.log('❌ Error:', result.message);
}
} catch (error) {
console.error('Error:', error.message);
}
}
downloadAndSave('https://open.spotify.com/track/3n3Ppam7vgaVa1iaRUc9Lp');Batch Download with Progress
const RcSpotDL = require('rcspotdl');
const axios = require('axios');
const fs = require('fs');
const path = require('path');
const spotdl = new RcSpotDL();
const playlist = [
'https://open.spotify.com/track/3n3Ppam7vgaVa1iaRUc9Lp',
'https://open.spotify.com/track/2takcwOaAZWiXQijPHIx7B',
'https://open.spotify.com/track/0VjIjW4GlUZAMYd2vXMi3b'
];
async function batchDownload() {
console.log('🎵 Starting batch download...\n');
const downloadDir = path.join(__dirname, 'downloads');
if (!fs.existsSync(downloadDir)) {
fs.mkdirSync(downloadDir);
}
for (let i = 0; i < playlist.length; i++) {
const url = playlist[i];
console.log(`[${i + 1}/${playlist.length}] Processing...`);
try {
const result = await spotdl.download(url);
if (result.success) {
const response = await axios.get(result.download.downloadUrl, {
responseType: 'arraybuffer'
});
const filename = `${result.info.title} - ${result.info.artist}.mp3`;
const filepath = path.join(downloadDir, filename);
fs.writeFileSync(filepath, response.data);
console.log(`✅ ${result.info.title} - ${result.info.artist}`);
console.log(` Saved to: ${filepath}\n`);
} else {
console.log(`❌ Failed: ${url}\n`);
}
} catch (error) {
console.log(`❌ Error: ${url}\n`);
}
}
console.log('🎉 Batch download completed!');
spotdl.clear();
}
batchDownload();🔧 Error Handling
const RcSpotDL = require('rcspotdl');
const axios = require('axios');
const spotdl = new RcSpotDL();
async function safeDownload(url) {
try {
const result = await spotdl.download(url);
if (!result.success) {
console.error('❌ Download failed:', result.message);
return null;
}
const response = await axios.get(result.download.downloadUrl, {
responseType: 'arraybuffer',
timeout: 30000
});
return {
buffer: Buffer.from(response.data),
info: result.info
};
} catch (error) {
if (error.code === 'ECONNABORTED') {
console.error('❌ Download timeout');
} else if (error.response) {
console.error('❌ Download failed:', error.response.status);
} else {
console.error('❌ Error:', error.message);
}
return null;
}
}
safeDownload('https://open.spotify.com/track/3n3Ppam7vgaVa1iaRUc9Lp');🛠️ Requirements
- Node.js >= 18.0.0
- npm or yarn
- axios (for downloading audio files)
📝 License
MIT License - see LICENSE file for details
⚠️ Disclaimer
This package is for educational purposes only. Please respect Spotify's Terms of Service and copyright laws. Download only tracks you have the rights to download.
🙏 Credits
This package uses SpotMate API for downloading Spotify tracks.
Made with ❤️ by RiiCODE
© 2025 RiiCODE. All rights reserved.
