Skip to content

fix(bot): update discord-player-youtubei v3 extractor registration - #510

Merged
LucasSantana-Dev merged 3 commits into
mainfrom
fix/youtube-extractor-v3-api
Apr 10, 2026
Merged

LucasSantana-Dev merged 3 commits into
mainfrom
fix/youtube-extractor-v3-api

Conversation

@LucasSantana-Dev

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

Copy link
Copy Markdown
Owner

Root Cause

discord-player-youtubei@3.0.0-beta.4 renamed the extractor from YoutubeiExtractor to YoutubeExtractor and removed streamOptions.useClient / generateWithPoToken from the registration options.

The old code resolved mod.YoutubeiExtractor → undefined, which caused player.extractors.register(undefined, ...) to throw TypeError: Cannot read properties of undefined (reading 'identifier'). This was silently caught, logging "YouTube extractor unavailable. Using SoundCloud/Spotify." on every bot startup.

Effect: No YouTube extractor was registered. All YouTube-backed tracks fell through to the SoundCloud extractor from DefaultExtractors. Tracks not available on SoundCloud (e.g. anime openings, niche tracks) failed with NoResultError: Could not extract stream for this track (Sentry LUCKY-2J, 4 events).

Changes

  • Resolve the extractor export with a v2 fallback: mod.YoutubeExtractor ?? mod.YoutubeiExtractor
  • Explicit guard when neither export is found (logs warn, returns cleanly)
  • Drop removed registration options (streamOptions.useClient, generateWithPoToken)
  • Update createResilientStream signature to v3: (track: Pick<Track, ...>, _ext?: unknown)

Test plan

  • CI passes (66 player handler tests green)
  • After deploy: bot logs should show Registered YoutubeExtractor (SoundCloud bridge + YouTube fallback) instead of YouTube extractor unavailable
  • Verify /play Ousama ranking Opening 2 Demo now streams successfully

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Chores
    • Updated YouTube extractor compatibility with the latest v3 release, including improved registration and error handling for enhanced reliability.

v3.0.0-beta.4 renamed YoutubeiExtractor → YoutubeExtractor and removed
the streamOptions/generateWithPoToken registration options. The old name
resolved to undefined, silently skipping YouTube extractor registration
on every startup. All YouTube tracks then fell through to the SoundCloud
extractor which failed for tracks not on SoundCloud, causing NoResultError.

- Resolve export by name with v2 fallback (YoutubeExtractor ?? YoutubeiExtractor)
- Drop removed options (streamOptions.useClient, generateWithPoToken)
- Update createResilientStream signature to v3 (Track, _ext?) instead of BridgeTrack
- Explicit guard when no extractor export found (logs warn instead of throwing)
@vercel

vercel Bot commented Apr 9, 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 9, 2026 11:58pm

Request Review

@coderabbitai

coderabbitai Bot commented Apr 9, 2026 •

Copy link
Copy Markdown

Warning

Rate limit exceeded

@LucasSantana-Dev has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 1 minutes and 58 seconds before requesting another review.

Your organization is not enrolled in usage-based pricing. Contact your admin to enable usage-based pricing to continue reviews beyond the rate limit, or try again in 1 minutes and 58 seconds.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 82eca066-83a3-4ab4-9da4-27779f037f43

📥 Commits

Reviewing files that changed from the base of the PR and between 304887c and 270645e.

📒 Files selected for processing (1)
  • packages/bot/tests/handlers/player/playerFactory.test.ts
📝 Walkthrough

Walkthrough

Updated YouTube extractor registration in playerFactory.ts to support discord-player-youtubei v3's export changes by detecting YoutubeExtractor or falling back to YoutubeiExtractor, and adjusted the createResilientStream function signature to align with the new v3 createStream interface requirements.

Changes

Cohort / File(s) Summary
YouTube Extractor Compatibility
packages/bot/src/handlers/player/playerFactory.ts
Updated extractor registration to handle v3 export rename with fallback logic; changed registration options to use only createStream: createResilientStream; modified createResilientStream signature from BridgeTrack to Pick<Track, 'title' | 'author' | 'duration' | 'url'> with additional ignored _ext parameter; updated related log messages and JSDoc.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Suggested labels

bot, dependencies, size/m

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main change: updating YouTube extractor registration to handle discord-player-youtubei v3's API changes and export renames.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/youtube-extractor-v3-api

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.

@coderabbitai coderabbitai Bot added dependencies Pull requests that update a dependency file size/m labels Apr 9, 2026

@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.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@packages/bot/src/handlers/player/playerFactory.ts`:
- Around line 68-83: The code currently checks both mod.YoutubeExtractor and
mod.YoutubeiExtractor but the package only exports YoutubeiExtractor; replace
the fallback logic by directly reading mod.YoutubeiExtractor (e.g., const
YoutubeExtractor = mod.YoutubeiExtractor), keep the same warnLog if it's
missing, and then call player.extractors.register(YoutubeExtractor, {
createStream: createResilientStream }) as before; update references to the
YoutubeExtractor variable accordingly so the code is unambiguous and only relies
on mod.YoutubeiExtractor.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: dc2d489b-340d-42b4-8ca8-0653bc71e825

📥 Commits

Reviewing files that changed from the base of the PR and between b6d4470 and 304887c.

📒 Files selected for processing (1)
  • packages/bot/src/handlers/player/playerFactory.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: SonarCloud Scan
  • GitHub Check: Quality Gates
🧰 Additional context used
📓 Path-based instructions (10)
**/*.{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/handlers/player/playerFactory.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/handlers/player/playerFactory.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/handlers/player/playerFactory.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/handlers/player/playerFactory.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/handlers/player/playerFactory.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/handlers/player/playerFactory.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/**

📄 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/handlers/player/playerFactory.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/handlers/player/playerFactory.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/handlers/player/playerFactory.ts
🔇 Additional comments (4)
packages/bot/src/handlers/player/playerFactory.ts (4)

1-2: LGTM!

Type-only import for Track is appropriate for the Pick<Track, ...> usage in createResilientStream.


85-96: LGTM!

Log messages are updated consistently to reflect the new extractor name. The success message clearly indicates the fallback strategy for operational clarity.


105-115: LGTM!

JSDoc clearly documents the v3 signature context and the three-stage fallback chain. This provides good context for future maintainers.


116-118: Signature is correct for v3 createStream contract.

The Pick<Track, 'title' | 'author' | 'duration' | 'url'> signature uses the correct Track type from discord-player and aligns with the v3 callback contract. All properties in the Pick are used in the function body, the _ext parameter is intentionally unused (correctly marked with underscore), and the Promise<Readable> return type is appropriate. Type safety and guidelines are properly maintained.

Comment on lines 68 to +83
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const mod = (await import('discord-player-youtubei')) as any

const registered = await player.extractors.register(
mod.YoutubeiExtractor,
{
streamOptions: {
useClient: 'IOS' as const,
highWaterMark: 1 << 25,
},
generateWithPoToken: true,
createStream: createResilientStream,
},
)
// v3 renamed YoutubeiExtractor → YoutubeExtractor
const YoutubeExtractor = mod.YoutubeExtractor ?? mod.YoutubeiExtractor
if (!YoutubeExtractor) {
warnLog({
message:
'discord-player-youtubei: no extractor export found — skipping YouTube extractor',
})
return
}

const registered = await player.extractors.register(YoutubeExtractor, {
createStream: createResilientStream,
})

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

🧩 Analysis chain

🌐 Web query:

discord-player-youtubei v3 YoutubeExtractor export createStream registration

💡 Result:

discord-player-youtubei does not export YouTubeExtractor (that’s from @discord-player/extractor, and Discord Player v7 removed YoutubeExtractor entirely). Use YoutubeiExtractor and register it once during startup. [1], [2]

Register (YoutubeiExtractor)

import { Player } from "discord-player";
import { YoutubeiExtractor } from "discord-player-youtubei";

const player = new Player(client);

// register ONCE (not inside commands)
player.extractors.register(YoutubeiExtractor, {
  // options...
});

[1]

Override createStream (custom stream factory)

discord-player-youtubei supports a createStream option with this shape:

createStream?: (q: Track, extractor: YoutubeiExtractor) => Promise<string | Readable>

Example:

import { Readable } from "node:stream";

player.extractors.register(YoutubeiExtractor, {
  async createStream(track, extractor) {
    // return a Readable OR a direct audio URL (string)
    // (implement your own streaming logic here)
    return "https://example.com/audio-stream-url";
    // or: return Readable.from(...)
  }
});

[1]

If you meant YouTube Data API v3 (Google API key-based) rather than YouTubei/InnerTube, say so—those are different systems and the setup is different. [1]

Sources:
[1] discord-player-youtubei README (usage, register, createStream option)
[2] Discord Player v7 migration guide (YoutubeExtractor removed)


Simplify extractor fallback: only YoutubeiExtractor is exported by discord-player-youtubei.

The fallback check mod.YoutubeExtractor ?? mod.YoutubeiExtractor is misleading—discord-player-youtubei v3 exports only YoutubeiExtractor. The first check will always be undefined and can be removed. The createStream registration is correct per the package API docs (discord-player-youtubei README). Replace the fallback with a direct check on mod.YoutubeiExtractor for clarity.

🤖 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 68 - 83, The
code currently checks both mod.YoutubeExtractor and mod.YoutubeiExtractor but
the package only exports YoutubeiExtractor; replace the fallback logic by
directly reading mod.YoutubeiExtractor (e.g., const YoutubeExtractor =
mod.YoutubeiExtractor), keep the same warnLog if it's missing, and then call
player.extractors.register(YoutubeExtractor, { createStream:
createResilientStream }) as before; update references to the YoutubeExtractor
variable accordingly so the code is unambiguous and only relies on
mod.YoutubeiExtractor.

remove assertions for removed options (streamOptions, generateWithPoToken)
and update mock to export the renamed YoutubeExtractor class
@github-actions github-actions Bot removed dependencies Pull requests that update a dependency file size/s labels Apr 9, 2026
add tests for: missing extractor export (no-op + warnLog), v2 fallback
(YoutubeiExtractor used when YoutubeExtractor absent), and explicit absence
of removed v3 options (streamOptions, generateWithPoToken)
@sonarqubecloud

Copy link
Copy Markdown

@LucasSantana-Dev
LucasSantana-Dev merged commit 13ad0d6 into main Apr 10, 2026
12 checks passed
@LucasSantana-Dev
LucasSantana-Dev deleted the fix/youtube-extractor-v3-api branch April 10, 2026 00:02
LucasSantana-Dev added a commit that referenced this pull request Apr 10, 2026
)

* fix(bot): update discord-player-youtubei v3 extractor registration

v3.0.0-beta.4 renamed YoutubeiExtractor → YoutubeExtractor and removed
the streamOptions/generateWithPoToken registration options. The old name
resolved to undefined, silently skipping YouTube extractor registration
on every startup. All YouTube tracks then fell through to the SoundCloud
extractor which failed for tracks not on SoundCloud, causing NoResultError.

- Resolve export by name with v2 fallback (YoutubeExtractor ?? YoutubeiExtractor)
- Drop removed options (streamOptions.useClient, generateWithPoToken)
- Update createResilientStream signature to v3 (Track, _ext?) instead of BridgeTrack
- Explicit guard when no extractor export found (logs warn instead of throwing)

* test(bot): update player factory spec for youtubei v3 api

remove assertions for removed options (streamOptions, generateWithPoToken)
and update mock to export the renamed YoutubeExtractor class

* test(bot): add coverage for youtubei v3 guard and fallback paths

add tests for: missing extractor export (no-op + warnLog), v2 fallback
(YoutubeiExtractor used when YoutubeExtractor absent), and explicit absence
of removed v3 options (streamOptions, generateWithPoToken)
LucasSantana-Dev added a commit that referenced this pull request May 13, 2026
)

* fix(bot): update discord-player-youtubei v3 extractor registration

v3.0.0-beta.4 renamed YoutubeiExtractor → YoutubeExtractor and removed
the streamOptions/generateWithPoToken registration options. The old name
resolved to undefined, silently skipping YouTube extractor registration
on every startup. All YouTube tracks then fell through to the SoundCloud
extractor which failed for tracks not on SoundCloud, causing NoResultError.

- Resolve export by name with v2 fallback (YoutubeExtractor ?? YoutubeiExtractor)
- Drop removed options (streamOptions.useClient, generateWithPoToken)
- Update createResilientStream signature to v3 (Track, _ext?) instead of BridgeTrack
- Explicit guard when no extractor export found (logs warn instead of throwing)

* test(bot): update player factory spec for youtubei v3 api

remove assertions for removed options (streamOptions, generateWithPoToken)
and update mock to export the renamed YoutubeExtractor class

* test(bot): add coverage for youtubei v3 guard and fallback paths

add tests for: missing extractor export (no-op + warnLog), v2 fallback
(YoutubeiExtractor used when YoutubeExtractor absent), and explicit absence
of removed v3 options (streamOptions, generateWithPoToken)

This branch was successfully deployed

1 active deployment
Preview — 270645e4 Deployed Apr 9, 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