Skip to content

fix(bot): enforce spotify→youtube→soundcloud source priority - #515

Merged
LucasSantana-Dev merged 1 commit into
mainfrom
fix/source-priority-spotify-youtube-soundcloud
Apr 10, 2026
Merged

LucasSantana-Dev merged 1 commit into
mainfrom
fix/source-priority-spotify-youtube-soundcloud

Conversation

@LucasSantana-Dev

@LucasSantana-Dev LucasSantana-Dev commented Apr 10, 2026 •

Copy link
Copy Markdown
Owner

Summary

  • Stream bridge (playerFactory.ts): YouTube direct stream is now attempted first (using playdl.stream(track.url)), since the track always carries its source URL. SoundCloud search is the fallback for tracks where YouTube direct fails (e.g. bot-detection). Old order was SoundCloud → YouTube. Removed the spam-channel shortcut since YouTube direct is now universally tried first.
  • Autoplay search engines (queueManipulation.ts): All search loops (searchSeedCandidates, searchLastFmQuery) now use [SPOTIFY_SEARCH, YOUTUBE_SEARCH, AUTO] order (was [SPOTIFY_SEARCH, AUTO, YOUTUBE_SEARCH] and [SPOTIFY_SEARCH, AUTO]).
  • /play fallback (play/index.ts): Spotify → YouTube → AUTO instead of Spotify → AUTO.

Test plan

  • All 1684 tests pass
  • Bridge tests updated to reflect new order (YouTube first, SoundCloud fallback)
  • queueManipulation tests updated to assert YOUTUBE_SEARCH at call 2, AUTO at call 3
  • Lint passes

Summary by CodeRabbit

Release Notes

  • Bug Fixes
    • Enhanced music search fallback sequence to attempt YouTube search before auto-discovery, improving track resolution reliability
    • Improved stream resolution by prioritizing direct URLs as the first fallback option
    • Better error reporting when all playback options are exhausted

stream bridge: try direct youtube url first, soundcloud as fallback
(was soundcloud→youtube). search engines: all autoplay search loops
now use [spotify_search, youtube_search, auto] order (was [spotify,
auto, youtube] or [spotify, auto]). /play fallback: spotify → youtube
→ auto instead of spotify → auto.
@coderabbitai

coderabbitai Bot commented Apr 10, 2026 •

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

The PR modifies music playback and search fallback behavior to introduce QueryType.YOUTUBE_SEARCH as an intermediate fallback engine between primary search methods and QueryType.AUTO fallback across the play command, player factory, and queue manipulation components. Direct stream attempts are now prioritized in the resilient stream factory with SoundCloud search as secondary fallback.

Changes

Cohort / File(s) Summary
Search Fallback Engine Order
packages/bot/src/functions/music/commands/play/index.ts, packages/bot/src/utils/music/queueManipulation.ts
Modified search engine fallback sequence to retry with YOUTUBE_SEARCH before AUTO. Play command now cascades: initial engine → YOUTUBE_SEARCH → AUTO. Queue manipulation functions expanded fallback from [SPOTIFY_SEARCH, AUTO] to [SPOTIFY_SEARCH, YOUTUBE_SEARCH, AUTO].
Search Fallback Tests
packages/bot/src/utils/music/queueManipulation.spec.ts
Updated test assertions to reflect new fallback order: YouTube search now occurs at call index 2 with AUTO at index 3. Last.fm Spotify-failure test updated to expect YOUTUBE_SEARCH as second fallback engine.
Player Factory Streaming Chain
packages/bot/src/handlers/player/playerFactory.ts
Reordered resilient stream fallback: direct playdl.stream() attempt now prioritized first (when URL exists), with SoundCloud search stages (full query then title-only) as secondary fallback. Removed isSpamChannel control-flow branch. Changed direct-stream failure logging from error-level to debug-level, with consolidated error emission only after all fallback stages exhausted.
Player Factory Stream Tests
packages/bot/src/handlers/player/playerFactory.bridge.spec.ts
Restructured createResilientStream test coverage: direct stream is now the first attempt (no SoundCloud calls on success); SoundCloud fallback tests updated to expect rejection of direct stream before running primary and title-only searches. Removed spam-channel skip scenario and updated terminal failure expectation from direct-stream error to "bridge exhausted" message.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 33.33% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely captures the main objective: enforcing a specific source priority order (Spotify→YouTube→SoundCloud) across multiple components in the music streaming bot.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/source-priority-spotify-youtube-soundcloud

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@vercel

vercel Bot commented Apr 10, 2026 •

Copy link
Copy Markdown
Contributor

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
lucky Ready Ready Preview, Comment Apr 10, 2026 2:23am

Request Review

@sonarqubecloud

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🧹 Nitpick comments (2)
packages/bot/src/functions/music/commands/play/index.ts (1)

158-173: Consider extracting fallback cascade to reduce nesting.

The nested try-catch is functional but adds cognitive overhead. A helper function could make the intent clearer.

♻️ Optional refactor to extract fallback logic
// Helper function (could be placed above the command or in a utils file)
async function playWithFallback(
    player: Player,
    voiceChannel: VoiceChannel,
    query: string,
    baseOptions: PlayOptions,
    engines: QueryType[],
): Promise<PlayResult> {
    let lastError: unknown
    for (const searchEngine of engines) {
        try {
            return await player.play(voiceChannel, query, {
                ...baseOptions,
                searchEngine,
            })
        } catch (error) {
            debugLog({
                message: `Search failed with ${searchEngine}, trying next`,
                data: { query },
            })
            lastError = error
        }
    }
    throw lastError
}

// Usage in execute:
const engines = searchEngine === QueryType.AUTO
    ? [QueryType.AUTO]
    : [QueryType.SPOTIFY_SEARCH, QueryType.YOUTUBE_SEARCH, QueryType.AUTO]

result = await playWithFallback(client.player, voiceChannel, query, playOptions, engines)
🤖 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/index.ts` around lines 158 -
173, The nested try/catch around client.player.play with
QueryType.YOUTUBE_SEARCH then QueryType.AUTO increases nesting and cognitive
load; extract the fallback cascade into a helper (e.g., playWithFallback) that
accepts player, voiceChannel, query, baseOptions, and an ordered engines:
QueryType[] list, iterates engines calling client.player.play with {
...baseOptions, searchEngine } and returns on first success, logging each
failure via debugLog, and rethrows the last error if all engines fail; replace
the nested tries in execute with a single call to playWithFallback using the
appropriate engines order based on the initial searchEngine value.
packages/bot/src/handlers/player/playerFactory.ts (1)

151-177: Clarify the SoundCloud fallback query composition for spam channel scenarios.

The SoundCloud fallback uses cleanSearchQuery(cleanedTitle, cleanedAuthor) which includes the uploader in the search query. While the direct-stream-first approach mitigates spam channel issues for most tracks (as confirmed by the test "streams directly from source URL even for spam uploader channels"), when direct streaming fails, SoundCloud may return mismatched results for compilation channel uploads.

Consider whether this trade-off is acceptable given the fallback priority design, or if isSpamChannel should gate the title+author fallback (falling through to title-only for spam channels).

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/bot/src/handlers/player/playerFactory.ts` around lines 151 - 177,
The current fallback composes a title+author query via
cleanSearchQuery(cleanedTitle, cleanedAuthor) before falling back to title-only;
change this so that when isSpamChannel is true you skip the title+author attempt
and go straight to streamViaSoundCloud(cleanedTitle, track.duration).
Concretely, wrap the first try block (the
streamViaSoundCloud(cleanSearchQuery(...)) call and its debugLog) in an if
(!isSpamChannel) guard (or invert and early-try title-only), ensuring
streamViaSoundCloud, cleanSearchQuery, cleanedTitle, cleanedAuthor,
isSpamChannel and track.duration are used accordingly and update the debug/error
logs to reflect which branch was attempted.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@packages/bot/src/functions/music/commands/play/index.ts`:
- Around line 158-173: The nested try/catch around client.player.play with
QueryType.YOUTUBE_SEARCH then QueryType.AUTO increases nesting and cognitive
load; extract the fallback cascade into a helper (e.g., playWithFallback) that
accepts player, voiceChannel, query, baseOptions, and an ordered engines:
QueryType[] list, iterates engines calling client.player.play with {
...baseOptions, searchEngine } and returns on first success, logging each
failure via debugLog, and rethrows the last error if all engines fail; replace
the nested tries in execute with a single call to playWithFallback using the
appropriate engines order based on the initial searchEngine value.

In `@packages/bot/src/handlers/player/playerFactory.ts`:
- Around line 151-177: The current fallback composes a title+author query via
cleanSearchQuery(cleanedTitle, cleanedAuthor) before falling back to title-only;
change this so that when isSpamChannel is true you skip the title+author attempt
and go straight to streamViaSoundCloud(cleanedTitle, track.duration).
Concretely, wrap the first try block (the
streamViaSoundCloud(cleanSearchQuery(...)) call and its debugLog) in an if
(!isSpamChannel) guard (or invert and early-try title-only), ensuring
streamViaSoundCloud, cleanSearchQuery, cleanedTitle, cleanedAuthor,
isSpamChannel and track.duration are used accordingly and update the debug/error
logs to reflect which branch was attempted.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 1aab0990-b8b6-4cec-bafb-72caad996919

📥 Commits

Reviewing files that changed from the base of the PR and between 36cc8b6 and 7c87373.

📒 Files selected for processing (5)
  • packages/bot/src/functions/music/commands/play/index.ts
  • packages/bot/src/handlers/player/playerFactory.bridge.spec.ts
  • packages/bot/src/handlers/player/playerFactory.ts
  • packages/bot/src/utils/music/queueManipulation.spec.ts
  • packages/bot/src/utils/music/queueManipulation.ts
📜 Review details
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: Quality Gates
  • GitHub Check: SonarCloud Scan
🧰 Additional context used
📓 Path-based instructions (20)
**/*.{js,jsx,ts,tsx,vue,html}

📄 CodeRabbit inference engine (.cursor/rules/accessibility-openness.mdc)

Provide accessible UI components using semantic HTML and ARIA attributes where necessary

Files:

  • packages/bot/src/functions/music/commands/play/index.ts
  • packages/bot/src/utils/music/queueManipulation.ts
  • packages/bot/src/utils/music/queueManipulation.spec.ts
  • packages/bot/src/handlers/player/playerFactory.ts
  • packages/bot/src/handlers/player/playerFactory.bridge.spec.ts
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.cursor/rules/dependency-injection.mdc)

**/*.{ts,tsx,js,jsx}: Prefer constructor injection for classes that require dependencies
Avoid global mutable singletons unless necessary
Use explicit interfaces for external dependencies to make testing easier

**/*.{ts,tsx,js,jsx}: Include required references in PRs/code for non-trivial logic: TypeScript (official docs), MDN (JavaScript reference), and official docs for any runtime/framework/libraries used (e.g., Node.js, React) as applicable.
Before assuming behavior of an API, include the doc link and a ≤25-word quote when the change relies on it.

**/*.{ts,tsx,js,jsx}: Prefer named exports for clear usage and easier refactors in TypeScript/JavaScript
Keep import order consistent: external first, then internal modules
Remove dead code and unused imports

**/*.{ts,tsx,js,jsx}: Use PascalCase naming convention for React/UI components
Use camelCase naming convention for variables and functions
Use UPPER_SNAKE_CASE naming convention for constants
Maintain consistent import grouping and ordering within the project, keeping third-party imports separate from local imports
For external data sources (HTTP, database), always validate and sanitize input using type guards or schema validators

**/*.{ts,tsx,js,jsx}: Use Prettier with no semicolons, single quotes, 4-space indent, 80 character width
Files must not exceed 250 lines and this is enforced

Implement TypeScript typecheck and linter in CI quality checks

**/*.{ts,tsx,js,jsx}: Use TypeScript for enhanced type safety
Implement error handling and error logging
Avoid commenting code unless extremely necessary - code should explain itself with descriptive names
Leave NO todos, placeholders or missing pieces in the code
Variables and functions must use camelCase
Constants must use UPPER_SNAKE_CASE
Use arrow functions for methods and computed properties
Avoid unnecessary curly braces in conditionals; use concise syntax for simple statements
Maintain consistent import grouping/order: external imports first, then...

Files:

  • packages/bot/src/functions/music/commands/play/index.ts
  • packages/bot/src/utils/music/queueManipulation.ts
  • packages/bot/src/utils/music/queueManipulation.spec.ts
  • packages/bot/src/handlers/player/playerFactory.ts
  • packages/bot/src/handlers/player/playerFactory.bridge.spec.ts
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/error-handling.mdc)

**/*.{js,jsx,ts,tsx}: Never throw strings. Throw Error (or typed subclasses) with descriptive messages
Include causal error as cause when available for better debugging
Define clear, stable error codes (e.g., ERR_AUTH_EXPIRED, ERR_NETWORK_TIMEOUT)
Provide optional metadata (e.g., details, retryable, status, correlationId) in error objects
Use domain error classes per area (e.g., AuthenticationError, ValidationError, NetworkError)
Log errors with structure (message, code, stack, cause, correlationId, user context where appropriate)
Mark retryable vs nonRetryable errors where helpful for operations
Set timeouts and handle aborts/cancellations; avoid dangling requests in API/network code
Implement backoff for transient failures; avoid infinite retries
Map HTTP status → domain errors; 4xx vs 5xx behave differently (e.g., retry for 5xx/network)

**/*.{js,jsx,ts,tsx}: Use functional components with hooks in React/React Native. Avoid class components.
Keep components focused on a single responsibility; extract complex logic into custom hooks.
Keep state local when possible. Use Context/Zustand/Redux only when necessary for state management.
If props or state traverse more than 3 levels, consider using context or a feature-scoped store instead of prop drilling.
Use performance optimization techniques: React.memo, useMemo, useCallback, Suspense (web), and virtualization for long lists; avoid unnecessary re-renders.
Web accessibility: use semantic HTML, labels, focus management, keyboard navigation, and aria-* attributes as needed.
React Native accessibility: use accessibility props (accessible, accessibilityLabel), proper roles and labels.
Identify and extract repetitive UI components proactively to components/ with clear props and minimal coupling.
Web styles: prefer co-located styles or design system tokens; avoid global style leakage.
React Native styles: prefer StyleSheet.create, design tokens, and theme providers; avoid in...

Files:

  • packages/bot/src/functions/music/commands/play/index.ts
  • packages/bot/src/utils/music/queueManipulation.ts
  • packages/bot/src/utils/music/queueManipulation.spec.ts
  • packages/bot/src/handlers/player/playerFactory.ts
  • packages/bot/src/handlers/player/playerFactory.bridge.spec.ts
**/index.ts

📄 CodeRabbit inference engine (.cursor/rules/pattern.mdc)

Use index.ts only to re-export a small, intentional surface per module

Files:

  • packages/bot/src/functions/music/commands/play/index.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/pattern.mdc)

Introduce interfaces at module boundaries to enable testing and substitutions

**/*.{ts,tsx}: Avoid using any type in TypeScript. If unavoidable, use unknown with type guards and justify with a code comment
Prefer interface for defining public object shapes in TypeScript, use type for unions and utility types
Use TypeScript utility types such as Partial, Pick, Omit, Readonly, and Record when appropriate
Use I{Name} naming convention for interfaces in TypeScript
Use T{Name} naming convention for type aliases and utility types in TypeScript

**/*.{ts,tsx}: Functions must be less than 50 lines with cyclomatic complexity less than 10
Do not use any types - ESLint enforces this at error level

**/*.{ts,tsx}: Prefer types over interfaces for most cases
Don't ever use any - type safety always
Avoid enums; use const objects instead
For complex types, create a separate file to declare them and import them
Avoid using any type; if unavoidable, use unknown with type guards and justify with code comment
Prefer interface for public API shapes; use type for unions and utility types
Use TypeScript utility types (Partial, Pick, Omit, Readonly, Record)

Files:

  • packages/bot/src/functions/music/commands/play/index.ts
  • packages/bot/src/utils/music/queueManipulation.ts
  • packages/bot/src/utils/music/queueManipulation.spec.ts
  • packages/bot/src/handlers/player/playerFactory.ts
  • packages/bot/src/handlers/player/playerFactory.bridge.spec.ts
**/*.{js,ts,tsx,jsx}

📄 CodeRabbit inference engine (.cursor/rules/documentation.mdc)

**/*.{js,ts,tsx,jsx}: Minimize comments in code; explain the 'why' when non-obvious, let code express the 'what' through clear naming
Document trade-offs briefly when deviating from ideal patterns

**/*.{js,ts,tsx,jsx}: Store secrets, ports, and hosts in environment variables (.env, .env.example) and never hardcode them
Avoid redundant or decorative AI comments; code should be self-explanatory and only commented when logic is non-obvious; prefer refactoring over lengthy comments

Never hardcode secrets, IPs, or ports; use .env and docs/ for required configuration variables

Files:

  • packages/bot/src/functions/music/commands/play/index.ts
  • packages/bot/src/utils/music/queueManipulation.ts
  • packages/bot/src/utils/music/queueManipulation.spec.ts
  • packages/bot/src/handlers/player/playerFactory.ts
  • packages/bot/src/handlers/player/playerFactory.bridge.spec.ts
packages/bot/src/functions/*/commands/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/lucky-discord-bot.mdc)

packages/bot/src/functions/*/commands/**/*.{ts,tsx}: Command model must include data (slash builder), execute, and category properties exported from packages/bot/src/models/Command.ts
Use @discordjs/builders for building the data (SlashCommandBuilder) in command definitions
Command execute function must receive { interaction, client } parameters from CommandExecuteParams type
Use interactionReply and createUserFriendlyError utilities from @lucky/shared/general utils for command replies and error handling
Use existing validators from packages/bot/src/utils/command/ for voice channel, queue, and guild validations in commands

Files:

  • packages/bot/src/functions/music/commands/play/index.ts
packages/bot/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/lucky-discord-bot.mdc)

packages/bot/**/*.{ts,tsx}: Use useMainPlayer() from discord-player to access the player instance; do not instantiate player directly
Do not duplicate queue or player state outside Discord Player; use shared services from @lucky/shared for persistent data like track history and session information
Use errorLog and debugLog from @lucky/shared/utils for logging throughout the bot package
Use embed and reply utilities from @lucky/shared for consistent message formatting and error sanitization across the bot
Use services from @lucky/shared (DatabaseService, Redis client) for database and cache access; do not instantiate Prisma or Redis directly in the bot package

Files:

  • packages/bot/src/functions/music/commands/play/index.ts
  • packages/bot/src/utils/music/queueManipulation.ts
  • packages/bot/src/utils/music/queueManipulation.spec.ts
  • packages/bot/src/handlers/player/playerFactory.ts
  • packages/bot/src/handlers/player/playerFactory.bridge.spec.ts
packages/bot/**

📄 CodeRabbit inference engine (.cursor/rules/lucky-project.mdc)

The bot package depends on shared and contains Discord bot commands and player handlers using Discord.js and Discord Player

Files:

  • packages/bot/src/functions/music/commands/play/index.ts
  • packages/bot/src/utils/music/queueManipulation.ts
  • packages/bot/src/utils/music/queueManipulation.spec.ts
  • packages/bot/src/handlers/player/playerFactory.ts
  • packages/bot/src/handlers/player/playerFactory.bridge.spec.ts
**/*.{js,mjs,ts,mts}

📄 CodeRabbit inference engine (.cursor/rules/lucky-project.mdc)

Use Node.js version ≥22 with ESM (ECMAScript modules) only; no CommonJS

Files:

  • packages/bot/src/functions/music/commands/play/index.ts
  • packages/bot/src/utils/music/queueManipulation.ts
  • packages/bot/src/utils/music/queueManipulation.spec.ts
  • packages/bot/src/handlers/player/playerFactory.ts
  • packages/bot/src/handlers/player/playerFactory.bridge.spec.ts
packages/bot/src/functions/{general,music,download}/commands/**/*.ts

📄 CodeRabbit inference engine (.cursor/rules/subagent-discord.mdc)

packages/bot/src/functions/{general,music,download}/commands/**/*.ts: Apply .cursor/rules/lucky-discord-bot.mdc rules for Discord bot commands and player implementation
Use .cursor/skills/discord-commands/SKILL.md for implementing slash commands

Files:

  • packages/bot/src/functions/music/commands/play/index.ts
packages/bot/src/functions/music/commands/**/*.ts

📄 CodeRabbit inference engine (.cursor/rules/subagent-discord.mdc)

Use .cursor/skills/music-queue-player/SKILL.md for play, queue, skip, volume commands and player lifecycle management

Files:

  • packages/bot/src/functions/music/commands/play/index.ts
packages/bot/src/**/*.ts

📄 CodeRabbit inference engine (.cursor/rules/subagent-discord.mdc)

Use @lucky/shared for database, Redis, logging, and embed utilities instead of implementing them locally

Files:

  • packages/bot/src/functions/music/commands/play/index.ts
  • packages/bot/src/utils/music/queueManipulation.ts
  • packages/bot/src/utils/music/queueManipulation.spec.ts
  • packages/bot/src/handlers/player/playerFactory.ts
  • packages/bot/src/handlers/player/playerFactory.bridge.spec.ts
packages/bot/src/functions/music/**/*.ts

📄 CodeRabbit inference engine (.cursor/rules/subagent-discord.mdc)

Use existing voice/queue/guild validators before manipulating player or queue state

Files:

  • packages/bot/src/functions/music/commands/play/index.ts
**/*.{test,spec}.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/frontend.mdc)

**/*.{test,spec}.{js,jsx,ts,tsx}: Test behavior, not implementation. Prefer Testing Library utilities for testing React/React Native components.
For React Native tests: mock native modules and test component interactions and accessibility labels.

Files:

  • packages/bot/src/utils/music/queueManipulation.spec.ts
  • packages/bot/src/handlers/player/playerFactory.bridge.spec.ts
**/*.{test,spec}.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.cursor/rules/pattern.mdc)

**/*.{test,spec}.{ts,tsx,js,jsx}: Test behavior, not implementation details
Prefer unit tests for core logic; add integration tests at meaningful boundaries

Files:

  • packages/bot/src/utils/music/queueManipulation.spec.ts
  • packages/bot/src/handlers/player/playerFactory.bridge.spec.ts
**/*.{test,spec}.{js,ts,jsx,tsx}

📄 CodeRabbit inference engine (.cursor/rules/testing-quality.mdc)

**/*.{test,spec}.{js,ts,jsx,tsx}: Use Jest + a React testing library for unit and component tests as applicable
Test behavior, not implementation details

Files:

  • packages/bot/src/utils/music/queueManipulation.spec.ts
  • packages/bot/src/handlers/player/playerFactory.bridge.spec.ts
**/*.{spec,test}.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.cursor/rules/quality.mdc)

**/*.{spec,test}.{ts,tsx,js,jsx}: Use Jest for unit and integration tests
Test behavior, not implementation details
Run unit, integration tests, and coverage report in CI quality checks

Files:

  • packages/bot/src/utils/music/queueManipulation.spec.ts
  • packages/bot/src/handlers/player/playerFactory.bridge.spec.ts
**/*.spec.ts

📄 CodeRabbit inference engine (.cursor/rules/quality.mdc)

Unit tests must use naming convention *.spec.ts

Files:

  • packages/bot/src/utils/music/queueManipulation.spec.ts
  • packages/bot/src/handlers/player/playerFactory.bridge.spec.ts
packages/bot/src/handlers/player/**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/lucky-discord-bot.mdc)

Track handling, errors, and lifecycle must be managed through dedicated handlers in packages/bot/src/handlers/player/ (trackHandlers, errorHandlers, lifecycleHandlers)

Files:

  • packages/bot/src/handlers/player/playerFactory.ts
  • packages/bot/src/handlers/player/playerFactory.bridge.spec.ts
🔇 Additional comments (13)
packages/bot/src/handlers/player/playerFactory.ts (3)

107-112: Documentation accurately reflects the new priority order.

The docstring clearly explains the new fallback chain: YouTube direct → SoundCloud (full query) → SoundCloud (title only). This aligns with the PR objectives.


140-148: Appropriate log level change for expected fallback scenario.

Downgrading from warnLog to debugLog is correct since direct stream failures are expected (e.g., YouTube bot-detection) and handled gracefully by the SoundCloud fallback.


170-177: Error handling follows project conventions.

The terminal error correctly throws an Error with a descriptive message. The errorLog call before throwing provides observability for debugging. This aligns with the coding guidelines for error handling.

packages/bot/src/handlers/player/playerFactory.bridge.spec.ts (5)

175-184: Test correctly validates direct-stream-first behavior.

The test verifies that when playdl.stream(track.url) succeeds, no SoundCloud search is attempted. This aligns with the new priority order.


186-201: Test accurately covers SoundCloud fallback after direct stream failure.

Validates that when direct streaming fails (403), the bridge falls back to SoundCloud primary search with the title+author query.


203-222: Test covers the secondary SoundCloud fallback (title-only).

Properly simulates the scenario where direct stream fails, primary SoundCloud returns no validated match, and title-only fallback succeeds.


224-235: Test confirms spam channels now follow standard direct-stream path.

This test documents the behavioral change: spam uploaders (e.g., "Best Songs") no longer trigger special SoundCloud-skip logic. Direct streaming is attempted regardless of uploader.


237-252: Error case tests align with new terminal error message.

Both "no URL" and "all stages fail" cases correctly expect the bridge exhausted error pattern.

packages/bot/src/utils/music/queueManipulation.ts (2)

401-405: Engine order correctly prioritizes YouTube before AUTO fallback.

The new order [SPOTIFY_SEARCH, YOUTUBE_SEARCH, AUTO] aligns with the PR objective of enforcing Spotify → YouTube → SoundCloud/AUTO priority. This provides a more reliable fallback chain since YouTube is more likely to have matching results than the generic AUTO resolver.


566-570: Consistent engine order applied to Last.fm query fallback.

The searchLastFmQuery function now uses the same engine priority as searchSeedCandidates, ensuring consistent fallback behavior across all autoplay search paths.

packages/bot/src/functions/music/commands/play/index.ts (1)

151-177: Cascading fallback logic correctly implements Spotify → YouTube → AUTO priority.

The nested try-catch pattern ensures all fallback engines are attempted before propagating errors. This aligns with the PR objective.

One observation: the nested structure increases cyclomatic complexity. Consider extracting the fallback logic to a helper function for readability if this pattern grows further.

packages/bot/src/utils/music/queueManipulation.spec.ts (2)

317-330: Test assertions correctly updated for new engine fallback order.

The test now expects:

  1. Call 1: SPOTIFY_SEARCH
  2. Call 2: YOUTUBE_SEARCH
  3. Call 3: AUTO

This matches the implementation in searchSeedCandidates.


950-1012: Last.fm fallback test correctly updated for YouTube intermediate step.

The test verifies that when Spotify fails for a Last.fm seed query, the next attempt uses YOUTUBE_SEARCH before falling back to AUTO. This aligns with the updated searchLastFmQuery implementation.

@LucasSantana-Dev
LucasSantana-Dev merged commit f065887 into main Apr 10, 2026
12 checks passed
@LucasSantana-Dev
LucasSantana-Dev deleted the fix/source-priority-spotify-youtube-soundcloud branch April 10, 2026 02:27
LucasSantana-Dev added a commit that referenced this pull request Apr 10, 2026
stream bridge: try direct youtube url first, soundcloud as fallback
(was soundcloud→youtube). search engines: all autoplay search loops
now use [spotify_search, youtube_search, auto] order (was [spotify,
auto, youtube] or [spotify, auto]). /play fallback: spotify → youtube
→ auto instead of spotify → auto.
LucasSantana-Dev added a commit that referenced this pull request May 13, 2026
stream bridge: try direct youtube url first, soundcloud as fallback
(was soundcloud→youtube). search engines: all autoplay search loops
now use [spotify_search, youtube_search, auto] order (was [spotify,
auto, youtube] or [spotify, auto]). /play fallback: spotify → youtube
→ auto instead of spotify → auto.

This branch was successfully deployed

1 active deployment
Preview — 7c87373f Deployed Apr 10, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant