Repository navigation
fix(bot): update discord-player-youtubei v3 extractor registration - #510
Conversation
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)
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
|
Warning Rate limit exceeded
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 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 configurationConfiguration used: Organization UI Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (1)
📝 WalkthroughWalkthroughUpdated YouTube extractor registration in playerFactory.ts to support Changes
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Possibly related PRs
Suggested labels
🚥 Pre-merge checks | ✅ 3✅ Passed checks (3 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
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
📒 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 enforcedImplement 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. ThrowError(or typed subclasses) with descriptive messages
Include causal error ascausewhen 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)
MarkretryablevsnonRetryableerrors 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, andaria-*attributes as needed.
React Native accessibility: use accessibility props (accessible,accessibilityLabel), proper roles and labels.
Identify and extract repetitive UI components proactively tocomponents/with clear props and minimal coupling.
Web styles: prefer co-located styles or design system tokens; avoid global style leakage.
React Native styles: preferStyleSheet.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 usinganytype in TypeScript. If unavoidable, useunknownwith type guards and justify with a code comment
Preferinterfacefor defining public object shapes in TypeScript, usetypefor unions and utility types
Use TypeScript utility types such asPartial,Pick,Omit,Readonly, andRecordwhen appropriate
UseI{Name}naming convention for interfaces in TypeScript
UseT{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 useanytypes - ESLint enforces this at error level
**/*.{ts,tsx}: Prefer types over interfaces for most cases
Don't ever useany- type safety always
Avoid enums; use const objects instead
For complex types, create a separate file to declare them and import them
Avoid usinganytype; if unavoidable, useunknownwith type guards and justify with code comment
Preferinterfacefor public API shapes; usetypefor 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 commentsNever hardcode secrets, IPs, or ports; use
.envanddocs/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}: UseuseMainPlayer()fromdiscord-playerto access the player instance; do not instantiate player directly
Do not duplicate queue or player state outside Discord Player; use shared services from@lucky/sharedfor persistent data like track history and session information
UseerrorLoganddebugLogfrom@lucky/shared/utilsfor logging throughout the bot package
Use embed and reply utilities from@lucky/sharedfor 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
botpackage depends onsharedand 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/sharedfor 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
Trackis appropriate for thePick<Track, ...>usage increateResilientStream.
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 v3createStreamcontract.The
Pick<Track, 'title' | 'author' | 'duration' | 'url'>signature uses the correctTracktype fromdiscord-playerand aligns with the v3 callback contract. All properties in the Pick are used in the function body, the_extparameter is intentionally unused (correctly marked with underscore), and thePromise<Readable>return type is appropriate. Type safety and guidelines are properly maintained.
| // 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, | ||
| }) |
There was a problem hiding this comment.
🧩 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
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)
|
) * 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)
) * 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)



Root Cause
discord-player-youtubei@3.0.0-beta.4renamed the extractor fromYoutubeiExtractortoYoutubeExtractorand removedstreamOptions.useClient/generateWithPoTokenfrom the registration options.The old code resolved
mod.YoutubeiExtractor→undefined, which causedplayer.extractors.register(undefined, ...)to throwTypeError: 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 withNoResultError: Could not extract stream for this track(Sentry LUCKY-2J, 4 events).Changes
mod.YoutubeExtractor ?? mod.YoutubeiExtractorstreamOptions.useClient,generateWithPoToken)createResilientStreamsignature to v3:(track: Pick<Track, ...>, _ext?: unknown)Test plan
Registered YoutubeExtractor (SoundCloud bridge + YouTube fallback)instead ofYouTube extractor unavailable/play Ousama ranking Opening 2 Demonow streams successfully🤖 Generated with Claude Code
Summary by CodeRabbit