Youtube.js – elephantine-featured wrapper around YouTube’s deepest API
I be loopy about constituents, on tale of they are expedient.
A elephantine-featured wrapper around the Innertube API, which is what YouTube itself uses.
Table of Contents
About
Innertube is an API former across all YouTube purchasers, it became made to simplify the interior construction of the platform and invent it easy to push updates. This library takes earnings of that API, as a result of this truth offering a easy & atmosphere marvelous plan to work alongside with YouTube programmatically.
And colossal as a result of @gatecrasher777 for his research on the workings of the Innertube API!
Aspects
As of now, this is basically one of essentially the most developed & stable YouTube libraries accessible, this is a brief summary of its facets:
- Search movies, playlists, tune, albums etc
- Get detailed data about any video or playlist
- Receive are dwelling chat & are dwelling stats in trusty time
- Commerce notification preferences for a channel
- Subscribe/Unsubscribe/Esteem/Dislike/Comment etc
- With out misfortune register to any Google Account
- Commerce an tale’s settings.
- Get subscriptions/dwelling feed
- Get notifications
- Get gaze history
- Procure movies
Enact stammer that you could be signed-in to invent actions that involve an tale, equivalent to commenting, subscribing, sending messages to a are dwelling chat, etc.
Enact I need an API key to make exercise of this?
No, YouTube.js would not exercise any kindly API so no API keys are required.
Getting Started
Need to haves
-
NodeJS v14 or better
To non-public a study things are teach up
effectively, which you could flee this:
Installation
- NPM:
npm set up youtubei.js@latest
- Yarn:
tale add youtubei.js@latest
Utilization
To begin with we’re gonna originate up by initializing the Innertube event.
And to invent things sooner, which you could composed discontinue this handiest as soon as and reuse the Innertube object when indispensable.
const Innertube = require('youtubei.js'); const youtube = live up for fresh Innertube();
Doing a easy search
YouTube:
const search = live up for youtube.search('Procuring for lifestyles on Mars - Documentary');
YTMusic:
const search = live up for youtube.search('Interstellar Major Theme', { client: 'YTMUSIC' });
YouTube Output
{ ask: string, corrected_query: string, estimated_results: quantity, movies: [ { id: string, url: string, title: string, description: string, metadata:{ view_count: string, short_view_count_text: { simple_text: string, accessibility_label: string }, thumbnails: [Array], length: { seconds: quantity, simple_text: string, accessibility_label: string }, printed: string, badges: [Array], owner_badges: [Array] } } //... ] }
YTMusic Output
{ ask: string, corrected_query: string, results: { top_result: [Array], // Would per chance perchance also be the relaxation; video, playlist, artist etc.. songs: [ { id:string, title:string, artist:string, album:string, duration:string, thumbnails:[ Array ] }, //... ], movies: [ { id: string, title: string, author: string, views: string, duration: string, thumbnails: [Array] }, //... ], albums: [ { id: string, title: string, author: string, year: string, thumbnails: [Array] }, //... ], featured_playlists: [ { id:string, title:string, author:string, channel_id:string, total_items:number }, //... ], community_playlists: [ { id:string, title:string, author:string, channel_id:string, total_items:number }, //... ], artists: [ { id: string, name: string, subscribers: string, thumbnails: [Array] }, //... ] } }
Get search concepts:
const concepts = live up for youtube.getSearchSuggestions('QUERY', { client: 'YOUTUBE' // Exhaust YTMUSIC whenever you occur to desire tune search concepts })
Output
[ { text: string, bold_text: string }, //... ]
Get video data:
const video = live up for youtube.getDetails('VIDEO_ID');
Output
{ title: string, description: string, thumbnail: { url: string, width: quantity, height: quantity }, metadata: { embed: { iframeUrl: string, flashUrl: string, width: quantity, height: quantity, flashSecureUrl: string }, likes: quantity, dislikes: quantity, view_count: quantity, average_rating: quantity, length_seconds: quantity, channel_id: string, channel_url: string, external_channel_id: string, allow_ratings: boolean, is_live_content: boolean, is_family_safe: boolean, is_unlisted: boolean, is_private: boolean, is_liked: boolean, is_disliked: boolean, is_subscribed: boolean, subscriber_count: string, current_notification_preference: string, likes: { count: quantity, short_count_text: string }, publish_date_text: string, has_ypc_metadata: boolean, class: string, channel_name: string, publish_date: string, upload_date: string, key phrases: [Array] } }
Get comments:
const response = live up for youtube.getComments('VIDEO_ID');
Alternatively which you could exercise:
const video = live up for youtube.getDetails('VIDEO_ID'); const response = live up for video.getComments();
Output
{ comments: [ { text: string, author: { name: string, thumbnail: [ { url: string, width: number, height: number } ], channel_id: string }, metadata: { printed: string, is_liked: boolean, is_disliked: boolean, is_pinned: boolean, is_channel_owner: boolean, like_count: quantity, reply_count: quantity, identification: string } }, //... ], comment_count: string // not on hand in continuations }
Reply to, indulge in and disfavor comments:
live up for response.comments[0].indulge in(); live up for response.comments[0].disfavor(); live up for response.comments[0].answer('Tremendous comment!');
Get comment replies:
const replies = live up for response.comments[0].getReplies();
Get comments/replies continuation:
const continuation = live up for response.getContinuation(); const replies_continuation = live up for replies.getContinuation();
Get dwelling feed:
const homefeed = live up for youtube.getHomeFeed();
Output
{ movies: [ { id: string, title: string, description: string, channel: { id: string, name: string, url: string }, metadata: { view_count: string, short_view_count_text: { simple_text: string, accessibility_label: string }, thumbnail: { url: string, width: number, height: number }, moving_thumbnail: { url: string, width: number, height: number }, published: string, duration: { seconds: number, simple_text: string, accessibility_label: string }, badges: string, owner_badges: [Array] } }, // ... ] }
Get continuation:
const continuation = live up for homefeed.getContinuation();
Get gaze history:
const history = live up for youtube.getHistory();
Output
{ items: [ { date: string, videos: [ { id: string, title: string, channel: { id: string, name: string, url: string }, metadata: { view_count: string, short_view_count_text: { simple_text: string, accessibility_label: string }, thumbnail: { url: string, width: number, height: number }, moving_thumbnail: { url: string, width: number, height: number }, published: string, badges: [Array], owner_badges: [Array] } }, //... ] }, //... ] }
Get continuation:
const continuation = live up for history.getContinuation();
Get subscriptions feed:
const mysubsfeed = live up for youtube.getSubscriptionsFeed();
Output
{ items: [ { date: string, videos: [ { id: string, title: string, description: string, channel: { id: string, name: string, url: string }, metadata: { view_count: string, short_view_count_text: { simple_text: string, accessibility_label: string }, thumbnail: { url: string, width: number, height: number }, moving_thumbnail: { url: string, width: number, height: number }, published: string, badges: [Array], owner_badges: [Array] } }, //... ] }, //... ] }
Get continuation:
const continuation = live up for mysubsfeed.getContinuation();
Get notifications:
const notifications = live up for youtube.getNotifications();
Output
{ items: [ { title: string, sent_time: string, channel_name: string, channel_thumbnail: { url: string, width: number, height: number }, video_thumbnail: { url: string, width: number, height: number }, video_url: string, read: boolean, notification_id: string }, //... ] }
Get continuation:
const continuation = live up for notifications.getContinuation();
Get unseen notifications count:
const notifications = live up for youtube.getUnseenNotificationsCount();
Get track lyrics:
const search = live up for youtube.search('Never give you up', { client: 'YTMUSIC' }); const lyrics = live up for youtube.getLyrics(search.results.songs[0].identification);
Get playlist:
YouTube (default):
const playlist = live up for youtube.getPlaylist('PLAYLIST_ID');
YouTube Music:
const playlist = live up for youtube.getPlaylist('PLAYLIST_ID', { client: 'YTMUSIC' });
YouTube Output
{ title: string, description: string, total_items: string, last_updated: string, views: string, items: [ { id: string, title: string, author: string, duration: { seconds: number, simple_text: string, accessibility_label: string }, thumbnails: [Array] }, //... ] }
YouTube Music Output
{ title: string, description: string, total_items: quantity, length: string, yr: string, items: [ { identification: string, title: string, creator: string, length: { seconds: quantity, simple_text: string }, thumbnails: [Array] }, //... }
Interactions:
The library makes it easy to work alongside with YouTube programmatically. Nonetheless, produce not neglect that you could be signed in to make exercise of the next facets!
-
Subscribe/Unsubscribe:
live up for youtube.work together.subscribe('CHANNEL_ID'); live up for youtube.work together.unsubscribe('CHANNEL_ID');
-
Esteem/Dislike:
live up for youtube.work together.indulge in('VIDEO_ID'); live up for youtube.work together.disfavor('VIDEO_ID'); live up for youtube.work together.removeLike('VIDEO_ID');
-
Comment:
live up for youtube.work together.comment('VIDEO_ID', 'Haha, effective video!');
-
Commerce notification preferences:
// Alternate choices: ALL | NONE | PERSONALIZED live up for youtube.work together.changeNotificationPreferences('CHANNEL_ID', 'ALL');
These programs will frequently return { success: fair correct, status_code: 200 }
if a hit.
Account Settings
It’s far additionally that which you could recall to mind to govern an tale’s settings:
-
Get tale data:
live up for youtube.tale.data();
Output
{ title: string, photo: [ { url: string, width: number, height: number } ], nation: string, language: string; }
Notification settings:
-
Subscription notifications:
live up for youtube.tale.settings.notifications.setSubscriptions(fair correct);
-
In actual fact helpful state notifications:
live up for youtube.tale.settings.notifications.setRecommendedVideos(fair correct);
-
Channel job notifications:
live up for youtube.tale.settings.notifications.setChannelActivity(fair correct);
-
Comment replies notifications:
live up for youtube.tale.settings.notifications.setCommentReplies(fair correct);
-
Channel mention notifications:
live up for youtube.tale.settings.notifications.setSharedContent(fair correct);
Privateness settings:
-
Subscriptions privateness:
live up for youtube.tale.settings.privateness.setSubscriptionsPrivate(fair correct);
-
Saved playlists privateness:
live up for youtube.tale.settings.privateness.setSavedPlaylistsPrivate(fair correct);
Are dwelling chats:
YouTube.js will not be ready to download are dwelling state yet, nonetheless it does imply which you could get are dwelling chats plus which you could additionally ship messages!
const Innertube = require('youtubei.js'); async function originate up() { const youtube = live up for fresh Innertube(); const search = live up for youtube.search('Lofi girl are dwelling'); const video = live up for youtube.getDetails(search.movies[0].identification); const livechat = video.getLivechat(); // Up so far stats relating to the livestream livechat.on('update-metadata', (data) => { console.data('Records:', data); }); // Fired at any time when there's a brand fresh message or a form of chat events livechat.on('chat-update', (message) => { console.data(`- ${message.creator.title}n${message.textual state}nn`); if(message.textual state == '!data') { livechat.sendMessage('Hey! This message became sent from YouTube.js'); } }); } originate up();
Discontinuance fetching the are dwelling chat:
Delete a message:
const msg = live up for livechat.sendMessage('Tremendous livestream!'); live up for msg.deleteMessage();
Downloading movies:
YouTube.js presents a easy-to-exercise and simple downloader:
const fs = require('fs'); const Innertube = require('youtubei.js'); async function originate up() { const youtube = live up for fresh Innertube(); const search = live up for youtube.search('Procuring for lifestyles on Mars - documentary'); const scamper = youtube.download(search.movies[0].identification, { format: 'mp4', // Elective, defaults to mp4 and I imply to switch away it as it is except you realize what which you could be doing effective: '360p', // if a video would not non-public a particular effective it could per chance per chance perchance tumble support to 360p, additionally not famed when kind is decided to audio kind: 'videoandaudio' // would be “video”, “audio” and “videoandaudio” }); scamper.pipe(fs.createWriteStream(`./${search.movies[0].title}.mp4`)); scamper.on('originate up', () => { console.data('[DOWNLOADER]', 'Starting up download now!'); }); scamper.on('data', (data) => { // { video_details: {..}, selected_format: {..}, formats: {..} } console.data('[DOWNLOADER]', `Downloading ${data.video_details.title} by ${data.video_details.metadata.channel_name}`); }); scamper.on('development', (data) => { job.stdout.clearLine(); job.stdout.cursorTo(0); job.stdout.write(`[DOWNLOADER] Downloaded ${data.percentage}% (${data.downloaded_size}MB) of ${data.dimension}MB`); }); scamper.on('discontinue', () => { job.stdout.clearLine(); job.stdout.cursorTo(0); console.data('[DOWNLOADER]', 'Done!'); }); scamper.on('error', (err) => console.error('[ERROR]', err)); } originate up();
You should additionally specify a ramification:
const scamper = youtube.download(VIDEO_ID, { //... kind: 'videoandaudio', vary: { originate up: 0, discontinue: 1048576 * 5 } });
Homicide a download:
Alternatively, which you could salvage the deciphered streaming data and contend with the download your self:
const streaming_data = live up for youtube.getStreamingData(search.movies[0].identification, { format: 'mp4', effective: '360p', kind: 'videoandaudio' });
Output
{ selected_format: { itag: quantity, mimeType: string, bitrate: quantity, initRange: { originate up: string, discontinue: string }, indexRange: { originate up: string, discontinue: string }, lastModified: string, contentLength: string, effective: string, projectionType: string, averageBitrate: quantity, highReplication: boolean, audioQuality: string, approxDurationMs: string, audioSampleRate: string, audioChannels: quantity, loudnessDb: quantity, url: string, has_audio: boolean, has_video: boolean }, formats: [ { itag: number, mimeType: string, bitrate: number, initRange: { start: string, end: string }, indexRange: { start: string, end: string }, lastModified: string, contentLength: string, quality: string, projectionType: string, averageBitrate: number, highReplication: boolean, audioQuality: string, approxDurationMs: string, audioSampleRate: string, audioChannels: number, loudnessDb: number, url: string, has_audio: boolean, has_video: boolean } //... ] }
Signing-in:
When signing in to your tale, you non-public gotten two alternatives:
- Exhaust OAuth 2.0; easy, easy & kindly.
- Cookies; on the entire extra subtle to salvage and unreliable.
OAuth:
const fs = require('fs'); const Innertube = require('youtubei.js'); const creds_path = './yt_oauth_creds.json'; async function originate up() { const creds = fs.existsSync(creds_path) && JSON.parse(fs.readFileSync(creds_path).toString()) || {}; const y
Read More
Share this on knowasiak.com to seek the recommendation of with people on this topicSignal up on Knowasiak.com now whenever you occur to could perchance be not registered yet.