trixxy-spotify
v1.0.0
Published
A package for Spotify integration with Discord bots.
Maintainers
Readme
trixxy-spotify
A package for integrating Spotify functionalities into your Discord bot, allowing you to search for tracks and display them using Discord embeds.
Installation
npm install trixxy-spotifySetup
- Create a Spotify Developer Application: Go to the Spotify Developer Dashboard and create a new application.
- Get Client ID and Client Secret: Once your application is created, you will find your
Client IDandClient Secret. - Set Redirect URI: In your application settings, add a
Redirect URI. For local development,http://localhost:8888/callbackis a common choice. This URI is where Spotify will redirect the user after they authorize your application.
Usage
const { Client, GatewayIntentBits } = require('discord.js');
const TrixxySpotify = require('trixxy-spotify');
// Replace with your actual Spotify API credentials and redirect URI
const SPOTIFY_CLIENT_ID = 'YOUR_SPOTIFY_CLIENT_ID';
const SPOTIFY_CLIENT_SECRET = 'YOUR_SPOTIFY_CLIENT_SECRET';
const SPOTIFY_REDIRECT_URI = 'http://localhost:8888/callback'; // Must match your Spotify app settings
const spotify = new TrixxySpotify(SPOTIFY_CLIENT_ID, SPOTIFY_CLIENT_SECRET, SPOTIFY_REDIRECT_URI);
const client = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.MessageContent] }); // Add MessageContent intent for commands
client.on('ready', () => {
console.log(`Logged in as ${client.user.tag}!`);
});
client.on('messageCreate', async message => {
if (message.author.bot) return;
if (!message.content.startsWith('!')) return; // Simple command prefix
const args = message.content.slice(1).trim().split(/ +/);
const command = args.shift().toLowerCase();
if (command === 'searchspotify') {
const query = args.join(' ');
if (!query) {
return message.reply('Please provide a search query.');
}
try {
// You'll need to handle Spotify authorization first to get an access token.
// For demonstration, we'll assume you have a valid access token set.
// In a real application, you'd implement an OAuth flow.
// For testing, you can manually set an access token obtained from Spotify's API console.
// spotify.spotifyApi.setAccessToken('YOUR_MANUALLY_OBTAINED_ACCESS_TOKEN');
// A simpler way for server-side applications is to use Client Credentials Flow
// to get an app access token for searching public data.
const data = await spotify.spotifyApi.clientCredentialsGrant();
spotify.spotifyApi.setAccessToken(data.body['access_token']);
const tracks = await spotify.searchTracks(query, { limit: 1 });
if (tracks.length > 0) {
const track = tracks[0];
const embed = spotify.createTrackEmbed(track);
if (embed) {
message.channel.send({ embeds: [embed] });
} else {
message.reply('Could not create embed for the track.');
}
} else {
message.reply('No tracks found for your query.');
}
} catch (error) {
console.error('Error during Spotify search:', error);
message.reply('There was an error performing the Spotify search.');
}
} else if (command === 'searchplaylist') {
const query = args.join(' ');
if (!query) {
return message.reply('Please provide a search query for playlists.');
}
try {
const data = await spotify.spotifyApi.clientCredentialsGrant();
spotify.spotifyApi.setAccessToken(data.body['access_token']);
const playlists = await spotify.searchPlaylists(query, { limit: 1 });
if (playlists.length > 0) {
const playlist = playlists[0];
const embed = spotify.createPlaylistEmbed(playlist);
if (embed) {
message.channel.send({ embeds: [embed] });
} else {
message.reply('Could not create embed for the playlist.');
}
} else {
message.reply('No playlists found for your query.');
}
} catch (error) {
console.error('Error during Spotify playlist search:', error);
message.reply('There was an error performing the Spotify playlist search.');
}
}
});
client.login('YOUR_BOT_TOKEN');Methods
constructor(clientId, clientSecret, redirectUri)
Initializes the Spotify API wrapper.
authorize(code)
Exchanges an authorization code for an access token and refresh token. Use this for user-specific authorization.
refreshAccessToken()
Refreshes the Spotify access token using the refresh token.
searchTracks(query, options)
Searches for tracks on Spotify. Returns an array of track objects.
searchPlaylists(query, options)
Searches for playlists on Spotify. Returns an array of playlist objects.
getTrack(trackId)
Retrieves detailed information for a single track by its Spotify ID.
createTrackEmbed(track)
Creates a Discord EmbedBuilder object from a Spotify track object, ready to be sent in a Discord message.
createPlaylistEmbed(playlist)
Creates a Discord EmbedBuilder object from a Spotify playlist object, ready to be sent in a Discord message.
Contributing
Feel free to open issues or submit pull requests.
License
ISC
