Youtube.js – elephantine-featured wrapper around YouTube’s deepest API

A full-featured wrapper around the Innertube API, which is what YouTube itself uses. Table of Contents About The Project Features Getting Started Prerequisites Installation Usage Interactions Livechats Downloading videos Signing in Contributing License Contact Disclaimer About Innertube is an API used across all YouTube clients, it was made to simplify the internal structure of the…

7
[favorite_button]
Youtube.js – elephantine-featured wrapper around YouTube’s deepest API
Hello reader! Welcome, let's start-

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
  1. About The Project

  2. Getting Started

  3. Utilization

  4. Contributing
  5. License
  6. Contact
  7. Disclaimer

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.

Advertisements
Vanic
WRITEN BY

Vanic

“Simplicity, patience, compassion.
These three are your greatest treasures.
Simple in actions and thoughts, you return to the source of being.
Patient with both friends and enemies,
you accord with the way things are.
Compassionate toward yourself,
you reconcile all beings in the world.”
― Lao Tzu, Tao Te Ching
Get Connected!
One of the Biggest Social Platform for Entrepreneurs, College Students and all. Come and join our community. Expand your network and get to know new people!

Discussion(s)

No comments yet

🌟 Latest Members

Knowasiak We would like to show you notifications so you don't miss chats & status updates.
Dismiss
Allow Notifications