Skip to content

Commit

Permalink
Rewrote Autoplay + added history + auto disconnect
Browse files Browse the repository at this point in the history
  • Loading branch information
Loukious committed Aug 20, 2023
1 parent 943ab1d commit 92868a1
Showing 1 changed file with 32 additions and 5 deletions.
37 changes: 32 additions & 5 deletions src/structures/Dispatcher.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ export default class Dispatcher {
public filters: Array<string>;
public autoplay: boolean;
public nowPlayingMessage: Message | null;
public history: Song[] = [];

constructor(options: DispatcherOptions) {
this.client = options.client;
Expand Down Expand Up @@ -95,6 +96,12 @@ export default class Dispatcher {
)) as any;
this.matchedTracks.push(...search.tracks);
this.player.playTrack({ track: this.current?.track });
if (this.current) {
this.history.push(this.current);
if (this.history.length > 100) {
this.history.shift();
}
}
}
public pause() {
if (!this.player) return;
Expand All @@ -119,6 +126,7 @@ export default class Dispatcher {
}
public destroy() {
this.queue.length = 0;
this.history = [];
this.player.connection.disconnect();
this.client.queue.delete(this.guildId);
if (this.stopped) return;
Expand Down Expand Up @@ -153,10 +161,13 @@ export default class Dispatcher {
public stop() {
if (!this.player) return;
this.queue.length = 0;
this.history = [];
this.loop = 'off';
this.autoplay = false;
this.repeat = 0;
this.stopped = true;
this.player.stopTrack();
this.player.connection.disconnect();
}
public setLoop(loop: any) {
this.loop = loop;
Expand All @@ -173,12 +184,28 @@ export default class Dispatcher {
public async Autoplay(song: Song) {
const resolve = await this.node.rest.resolve(`${this.client.config.searchEngine}:${song.info.author}`);
if (!resolve || !resolve.tracks.length) return this.destroy();
let choosed = new Song(resolve.tracks[Math.floor(Math.random() * resolve.tracks.length)], this.client.user);
if (this.queue.some((s) => s.track === choosed.track)) {
return this.Autoplay(song);

let choosed: Song | null = null;
const maxAttempts = 10; // Maximum number of attempts to find a unique song
let attempts = 0;

while (attempts < maxAttempts) {
const potentialChoice = new Song(resolve.tracks[Math.floor(Math.random() * resolve.tracks.length)], this.client.user);

// Check if the chosen song is not already in the queue or history
if (!this.queue.some((s) => s.track === potentialChoice.track) && !this.history.some((s) => s.track === potentialChoice.track)) {
choosed = potentialChoice;
break;
}

attempts++;
}

if (choosed) {
this.queue.push(choosed);
return this.isPlaying();
}
this.queue.push(choosed);
return this.isPlaying();
return this.destroy();
}
public async setAutoplay(autoplay: boolean) {
this.autoplay = autoplay;
Expand Down

0 comments on commit 92868a1

Please sign in to comment.