Skip to content

User guide

Rahil khan edited this page May 3, 2022 · 1 revision

EasyYoutube user guide

After this guide, you will never be required to see the documentation of this library. This guide will explain everything step-by-step with examples. So let's begin.

Initialization / Authorization

Testing / single account

You will need the following credentials of your google cloud project with API enabled.

  • client id
  • client secret
  • refresh token

For testing, You can get the refresh token from the google oauth2.0 playground. Make sure you have configured to use your own client secret and client id in the playground, like this : custom-credentials

Production / Multiple accounts

In the production stage, you will want the users to use their own accounts in your app. To get the refresh token of their account, follow the authentication guide. On android, you can get it like this:

GoogleSignInOptions options = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestScopes(new Scope("https://www.googleapis.com/auth/youtube.force-ssl"))
            .requestServerAuthCode(YOUR_WEB_CLIENT_ID)
            .requestEmail()
            .build();

Intent signInIntent = GoogleSignIn.getClient(this, options).getSignInIntent();
startActivityForResult(signInIntent,200);

Then in onActivityResult(), store the code in authCode variable:

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == 200){
        GoogleSignIn.getSignedInAccountFromIntent(data)
                .addOnFailureListener(System.out::println)
                .addOnSuccessListener(account -> authCode = account.getServerAuthCode());
    }
}

Now exchange this authcode to get access & refresh tokens. Make a request like this :

POST /token HTTP/1.1
Host: oauth2.googleapis.com
Content-Type: application/x-www-form-urlencoded

code=YOUR_AUTH_CODE&
client_id=your_client_id&
client_secret=your_client_secret&
redirect_uri=YOUR_REDIRECT_URL&
grant_type=authorization_code

This will result in a response like this:

{
  "access_token": "1/fFAGRNJru1FTz70BzhT3Zg",
  "expires_in": 3920,
  "token_type": "Bearer",
  "scope": "https://www.googleapis.com/auth/youtube.force-ssl",
  "refresh_token": "1//xEoDL4iW3cxlI7yDbSRFYNG01kVKM2C-259HOF2aQbI"
}

Reference


After getting the refresh token, Create a Project object from your credentials and pass it to the EasyYoutube constructor. Like this:

try {
    EasyYoutube youtube = new EasyYoutube(new Project(id,secret,refreshToken));
} catch (GeneralSecurityException | IOException e) {
    e.printStackTrace();
}

You can pass multiple projects to the constructor to increase the quota. Just make sure that each cloud account project is authorized to the same google account. Whenever the quota is reached, the library will change the project which will have a fresh quota.

Getting comments

To get comments of a video, use getComments() method. This will bring you 100 newest comment in form of string,

youtube.getComments(videoId)
        .setOnSuccessCallback(result -> {
            // here are your comments
            String[] comments = result;
        })
        .setOnErrorCallback(e -> {
            // Failed to get comments
            e.printStackTrace();
        });

Getting video data

And similerily, for getting video information also.

youtube.getVideo(videoId, VideoMetadata.METADATA_BASIC).setOnCompleteCallback(task -> {
    if (task.isSuccessful) {
        VideoMetadata info = task.result;
    } else
        task.exception.printStackTrace();
});

The METADATA_BASIC will include all the basic and main information of the video like the title, description, thumbnail, channel id and name and etc... The METADATA_ADVANCE constant will involve all these + videos statistics like likes, dislikes, etc.. and the METADATA_FULL will include everything that the VideoMetadata class has.

Note: Fields which are not fetched will be null in the VideoMetadata object.

Replying comments

You can either reply to all comments at once or can choose perticular on the basis of some condition. To reply all comments of a video,

youtube.replyAll(videoId, "Hello World", new ProgressListener() {
    @Override
    public void onProgress(int progress) {
        // total progress
    }
    @Override
    public void onError(Exception e) {
        // if any error occurs
    }
});

This will reply 'Hello world' to the top 100 comments of the video.

To reply only some comments, pass a Predicate befour ProgressListener in replyMatching() method. For Example to reply to comments which starts from 'yes':

youtube.replyMatching(videoId, "Hello World", (Predicate<String>) s -> s.startsWith("Yes"), new ProgressListener() {
    @Override
    public void onProgress(int progress) {
        // total progress
    }
    
    @Override
    public void onError(Exception e) {
        // if any error occurs
    }
});

If the predicate returns true, it will reply to the comment (that is also in the argument) otherwise not. This way you can choose the comments to reply to in particular.


Similierily there are more methods like these. You can read what they do in their Javadoc comment.

That's sit

You have successfully learned to use the EasyYoutube library. Now you can use it for making bots or apps using youtube data API.