Skip to content
Merged
55 changes: 0 additions & 55 deletions packages/bot/src/functions/music/commands/play/index.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -133,12 +133,6 @@ jest.mock('../../../../utils/general/errorSanitizer', () => ({
createUserFriendlyError: (error: unknown) => 'User friendly error',
}))

const registerNowPlayingMessageMock = jest.fn()
jest.mock('../../../../handlers/player/trackNowPlaying', () => ({
registerNowPlayingMessage: (...args: unknown[]) =>
registerNowPlayingMessageMock(...args),
}))

import playCommand from './index'

function createInteraction(guildId: string | null) {
Expand Down Expand Up @@ -729,53 +723,4 @@ describe('play command', () => {
}),
)
})

it('registers interaction reply as now-playing message to prevent duplicate (queuePosition=0)', async () => {
// When the track starts immediately (no pre-existing queue), the /play
// interaction reply shows "Now Playing". Without registration, the
// playerStart handler sends a second "Now Playing" message. This test
// verifies the registration happens so the handler edits instead.
const interaction = createInteraction('guild-1')
const track = {
id: 'track-1',
url: 'https://youtube.com/watch?v=abc',
title: 'Test Song',
author: 'Test Artist',
duration: '3:30',
thumbnail: null,
requestedBy: { id: 'user-1' },
metadata: {},
}

resolveGuildQueueMock.mockReturnValue({ queue: null }) // no pre-existing queue
const queue = {
tracks: { size: 0, toArray: jest.fn(() => []) },
repeatMode: 0,
}
resolveGuildQueueMock
.mockReturnValueOnce({ queue: null })
.mockReturnValue({ queue })

await playCommand.execute({
client: createClient(
async () => ({
track,
searchResult: { playlist: null, tracks: [track] },
}),
{ tracksSize: 0 },
),
interaction,
} as any)

await flushPromises()

// fetchReply must be called and registerNowPlayingMessage invoked with
// the reply's id and channelId — this prevents the duplicate embed.
expect(interaction.fetchReply).toHaveBeenCalled()
expect(registerNowPlayingMessageMock).toHaveBeenCalledWith(
'guild-1',
'msg-123',
'channel-1',
)
})
})
32 changes: 4 additions & 28 deletions packages/bot/src/functions/music/commands/play/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,7 @@
blendAutoplayTracks,
} from '../../../../utils/music/queueManipulation'
import { buildPlayResponseEmbed } from '../../../../utils/music/nowPlayingEmbed'
import { createMusicControlButtons } from '../../../../utils/music/buttonComponents'

Check warning on line 24 in packages/bot/src/functions/music/commands/play/index.ts

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Remove this unused import of 'createMusicControlButtons'.

See more on https://sonarcloud.io/project/issues?id=LucasSantana-Dev_Lucky&issues=AZ19T9EAO-njQfcvj3W0&open=AZ19T9EAO-njQfcvj3W0&pullRequest=557
import { registerNowPlayingMessage } from '../../../../handlers/player/trackNowPlaying'
import {
DISCORD_UNKNOWN_INTERACTION_CODE,
isUnknownInteractionError,
Expand Down Expand Up @@ -176,12 +175,12 @@
} catch (youtubeError) {
warnLog({
message:
'YouTube search failed, falling back to AUTO',
'YouTube search failed, falling back to SoundCloud',
data: { query },
})
result = await client.player.play(voiceChannel, query, {
...playOptions,
searchEngine: QueryType.AUTO,
searchEngine: QueryType.SOUNDCLOUD_SEARCH,
})
}
} else {
Expand Down Expand Up @@ -232,7 +231,7 @@
},
})
: buildPlayResponseEmbed({
kind: queuePosition === 0 ? 'nowPlaying' : 'addedToQueue',
kind: 'addedToQueue',
track,
requestedBy: interaction.user,
queuePosition,
Expand All @@ -251,34 +250,11 @@
})
}

// Attach the music control button row so the user can
// pause/skip/shuffle/loop/previous directly from the /play
// response. The row is queue-state-aware (disables Previous
// when there's no history, disables Shuffle on small queues).
const components = queue ? [createMusicControlButtons(queue)] : []

await interactionReply({
interaction,
content: { embeds: [embed], components },
content: { embeds: [embed] },
})

// When the track starts playing immediately (queuePosition === 0),
// register the interaction reply as the "now playing" message so
// the playerStart handler edits it (adding buttons) rather than
// sending a second "Now Playing" message in the channel.
if (queuePosition === 0 && interaction.guildId) {
try {
const reply = await interaction.fetchReply()
registerNowPlayingMessage(
interaction.guildId,
reply.id,
reply.channelId,
)
} catch {
// non-critical — worst case playerStart sends a fresh message
}
}

// Start background ops (apply autoplay pref then blend) without awaiting.
// This lets the response reach the user immediately.
// The Promise is not awaited, allowing the command handler to return while
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,9 @@ export function resolveSearchEngine(
case 'spotify':
return QueryType.SPOTIFY_SEARCH
default:
return QueryType.AUTO_SEARCH
// Spotify first: best metadata (titles, artwork, artist).
// Fallback chain in play/index.ts tries YouTube then AUTO if Spotify throws.
return QueryType.SPOTIFY_SEARCH
Comment on lines +60 to +62

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Comment references incorrect fallback engine.

Line 61 states the fallback chain "tries YouTube then AUTO," but the actual implementation in play/index.ts (lines 175-184) falls back to SOUNDCLOUD_SEARCH, not AUTO. This inconsistency could mislead future maintainers.

📝 Proposed fix
-            // Spotify first: best metadata (titles, artwork, artist).
-            // Fallback chain in play/index.ts tries YouTube then AUTO if Spotify throws.
+            // Spotify first: best metadata (titles, artwork, artist).
+            // Fallback chain in play/index.ts tries YouTube then SoundCloud if Spotify throws.
             return QueryType.SPOTIFY_SEARCH
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
// Spotify first: best metadata (titles, artwork, artist).
// Fallback chain in play/index.ts tries YouTube then AUTO if Spotify throws.
return QueryType.SPOTIFY_SEARCH
// Spotify first: best metadata (titles, artwork, artist).
// Fallback chain in play/index.ts tries YouTube then SoundCloud if Spotify throws.
return QueryType.SPOTIFY_SEARCH
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/bot/src/functions/music/commands/play/queryUtils.ts` around lines 60
- 62, Comment incorrectly says the fallback after QueryType.SPOTIFY_SEARCH is
"YouTube then AUTO"; update the comment to reflect the actual fallback used in
play/index.ts (YouTube then SOUNDCLOUD_SEARCH). Locate the comment adjacent to
QueryType.SPOTIFY_SEARCH in queryUtils.ts and change the text to explicitly
state "tries YouTube then SOUNDCLOUD_SEARCH" so it matches the implementation in
play/index.ts.

}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ async function addUpcomingTracks(
const trackList = await createTrackListDisplay(allTracks, options, page)
embed.addFields({
name: `\u{1F4CB} Upcoming Tracks (${allTracks.length})`,
value: trackList,
value: trackList || 'No displayable tracks',
inline: false,
})
} else {
Expand Down
25 changes: 21 additions & 4 deletions packages/bot/src/handlers/player/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@ import type { Player } from 'discord-player'
import type { CustomClient } from '../../types'
import { createPlayer } from './playerFactory'
import { setupErrorHandlers } from './errorHandlers'
import { setupLifecycleHandlers } from './lifecycleHandlers'
import {
setupLifecycleHandlers,
setupVoiceKickDetection,
} from './lifecycleHandlers'
import { setupTrackHandlers } from './trackHandlers'

type CreatePlayerParams = {
Expand All @@ -16,9 +19,23 @@ export const createPlayerWithHandlers = ({

player.events.removeAllListeners()

setupErrorHandlers(player as unknown as { events: { on: (event: string, handler: Function) => void } })
setupLifecycleHandlers(player as unknown as { events: { on: (event: string, handler: Function) => void } })
setupTrackHandlers({ player: player as unknown as { events: { on: (event: string, handler: Function) => void } }, client })
setupErrorHandlers(
player as unknown as {
events: { on: (event: string, handler: Function) => void }
},
)
setupLifecycleHandlers(
player as unknown as {
events: { on: (event: string, handler: Function) => void }
},
)
setupTrackHandlers({
player: player as unknown as {
events: { on: (event: string, handler: Function) => void }
},
client,
})
setupVoiceKickDetection(client)

return player
}
Expand Down
75 changes: 74 additions & 1 deletion packages/bot/src/handlers/player/lifecycleHandlers.spec.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { beforeEach, describe, expect, it, jest } from '@jest/globals'
import type { GuildQueue } from 'discord-player'
import { setupLifecycleHandlers } from './lifecycleHandlers'

const debugLogMock = jest.fn()
const infoLogMock = jest.fn()
Expand All @@ -9,6 +8,8 @@ const saveSnapshotMock = jest.fn()
const watchdogArmMock = jest.fn()
const watchdogCheckRecoverMock = jest.fn()
const watchdogClearMock = jest.fn()
const watchdogMarkIntentionalStopMock = jest.fn()
const watchdogIsIntentionalStopMock = jest.fn(() => false)

jest.mock('@lucky/shared/utils', () => ({
debugLog: (...args: unknown[]) => debugLogMock(...args),
Expand All @@ -28,9 +29,13 @@ jest.mock('../../utils/music/watchdog', () => ({
checkAndRecover: (...args: unknown[]) =>
watchdogCheckRecoverMock(...args),
clear: (...args: unknown[]) => watchdogClearMock(...args),
isIntentionalStop: watchdogIsIntentionalStopMock,
markIntentionalStop: watchdogMarkIntentionalStopMock,
},
}))

import { setupLifecycleHandlers } from './lifecycleHandlers'

type PlayerEventHandler = (queue: GuildQueue, message?: string) => Promise<void>

describe('setupLifecycleHandlers', () => {
Expand All @@ -39,6 +44,7 @@ describe('setupLifecycleHandlers', () => {
restoreSnapshotMock.mockResolvedValue({ restoredCount: 0 })
saveSnapshotMock.mockResolvedValue(null)
watchdogCheckRecoverMock.mockResolvedValue('none')
watchdogIsIntentionalStopMock.mockReturnValue(false)
})

it('restores snapshot and arms watchdog on connection', async () => {
Expand Down Expand Up @@ -92,4 +98,71 @@ describe('setupLifecycleHandlers', () => {
expect(saveSnapshotMock).toHaveBeenCalledWith(queue)
expect(watchdogCheckRecoverMock).toHaveBeenCalledWith(queue)
})

it('does NOT call checkAndRecover when connectionDestroyed', async () => {
const handlers: Record<string, PlayerEventHandler> = {}
const player = {
events: {
on: jest.fn((event: string, handler: PlayerEventHandler) => {
handlers[event] = handler
}),
},
}

setupLifecycleHandlers(player)

const queue = {
guild: { id: 'guild-3', name: 'Guild 3' },
} as unknown as GuildQueue

await handlers.connectionDestroyed(queue)

expect(saveSnapshotMock).toHaveBeenCalled()
expect(watchdogCheckRecoverMock).not.toHaveBeenCalled()
})

it('does NOT call checkAndRecover when disconnect is intentional stop', async () => {
watchdogIsIntentionalStopMock.mockReturnValue(true)

const handlers: Record<string, PlayerEventHandler> = {}
const player = {
events: {
on: jest.fn((event: string, handler: PlayerEventHandler) => {
handlers[event] = handler
}),
},
}

setupLifecycleHandlers(player)

const queue = {
guild: { id: 'guild-4', name: 'Guild 4' },
} as unknown as GuildQueue

await handlers.disconnect(queue)

expect(saveSnapshotMock).toHaveBeenCalledWith(queue)
expect(watchdogCheckRecoverMock).not.toHaveBeenCalled()
})

it('marks intentional stop on emptyQueue', async () => {
const handlers: Record<string, PlayerEventHandler> = {}
const player = {
events: {
on: jest.fn((event: string, handler: PlayerEventHandler) => {
handlers[event] = handler
}),
},
}

setupLifecycleHandlers(player)

const queue = {
guild: { id: 'guild-5', name: 'Guild 5' },
} as unknown as GuildQueue

await handlers.emptyQueue(queue)

expect(watchdogMarkIntentionalStopMock).toHaveBeenCalledWith('guild-5')
})
})
25 changes: 23 additions & 2 deletions packages/bot/src/handlers/player/lifecycleHandlers.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type { GuildQueue } from 'discord-player'
import type { Client } from 'discord.js'
import { infoLog, debugLog } from '@lucky/shared/utils'
import * as voiceStatus from '../../services/VoiceChannelStatusService'
import * as musicPresence from '../../services/MusicPresenceService'
Expand All @@ -7,6 +8,20 @@ import { musicWatchdogService } from '../../utils/music/watchdog'
import { musicSessionSnapshotService } from '../../utils/music/sessionSnapshots'
import type { QueueMetadata } from '../../types/QueueMetadata'

export const setupVoiceKickDetection = (client: Client): void => {
client.on('voiceStateUpdate', (oldState, newState) => {
if (newState.member?.id !== client.user?.id) return
const wasInChannel = Boolean(oldState.channelId)
const nowDisconnected = !newState.channelId
if (wasInChannel && nowDisconnected && oldState.guild) {
musicWatchdogService.markIntentionalStop(oldState.guild.id)
infoLog({
message: `Bot was disconnected from voice in ${oldState.guild.name} — marked intentional`,
})
}
})
}

export const setupLifecycleHandlers = (player: {
events: { on: (event: string, handler: Function) => void }
}): void => {
Expand Down Expand Up @@ -52,7 +67,7 @@ export const setupLifecycleHandlers = (player: {
await voiceStatus.clearStatus(queue)
musicPresence.clearMusicPresence(queue.guild.id)
await musicSessionSnapshotService.saveSnapshot(queue)
await musicWatchdogService.checkAndRecover(queue)
// Queue was explicitly deleted — never attempt recovery here.
})

player.events.on('emptyChannel', async (queue: GuildQueue) => {
Expand All @@ -63,6 +78,10 @@ export const setupLifecycleHandlers = (player: {
musicWatchdogService.clear(queue.guild.id)
})

player.events.on('emptyQueue', async (queue: GuildQueue) => {
musicWatchdogService.markIntentionalStop(queue.guild.id)
})

player.events.on('disconnect', async (queue: GuildQueue) => {
infoLog({
message: `Disconnected from voice channel in ${queue.guild.name}`,
Expand All @@ -71,6 +90,8 @@ export const setupLifecycleHandlers = (player: {
await voiceStatus.clearStatus(queue)
musicPresence.clearMusicPresence(queue.guild.id)
await musicSessionSnapshotService.saveSnapshot(queue)
await musicWatchdogService.checkAndRecover(queue)
if (!musicWatchdogService.isIntentionalStop(queue.guild.id)) {
await musicWatchdogService.checkAndRecover(queue)
}
})
}
1 change: 1 addition & 0 deletions packages/bot/src/handlers/player/trackHandlers.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ jest.mock('../../utils/music/watchdog', () => ({
musicWatchdogService: {
arm: (...args: unknown[]) => watchdogArmMock(...args),
clear: (...args: unknown[]) => watchdogClearMock(...args),
isIntentionalStop: () => false,
},
}))

Expand Down
2 changes: 2 additions & 0 deletions packages/bot/src/handlers/player/trackHandlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,7 @@ const handlePlayerFinish = async (
): Promise<void> => {
try {
await scrobbleAndRecord(queue, track)
if (musicWatchdogService.isIntentionalStop(queue.guild.id)) return
await replenishIfAutoplay(queue)
await musicSessionSnapshotService.saveSnapshot(queue)

Expand All @@ -235,6 +236,7 @@ const handlePlayerSkip = async (
try {
debugLog({ message: 'Track skipped, checking queue...' })
await scrobbleAndRecord(queue, track)
if (musicWatchdogService.isIntentionalStop(queue.guild.id)) return
await replenishIfAutoplay(queue)
await musicSessionSnapshotService.saveSnapshot(queue)

Expand Down
Loading
Loading