An Ri
An Ri

Reputation: 476

How to get comments from Google Docs API by Python?

I have one document on google drive and there are notes, comments, that I want to get. Can anyone say, is there a way to do it?

For example, lets start with this

import httplib2
import googleapiclient.discovery
from oauth2client.service_account import ServiceAccountCredentials
from google.oauth2 import service_account
from googleapiclient.http import MediaIoBaseDownload,MediaFileUpload
import os
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = r'C:\Users\Idensas\PycharmProjects\protest\Google\creds.json'


credentials = ServiceAccountCredentials('creds.json',['https://www.googleapis.com/auth/drive'])
httpAuth = credentials.authorize(httplib2.Http())
drive = googleapiclient.discovery.build('drive','v3')


a = drive.files().list(pageSize=10,fields='files(id, name, mimeType,parents)').execute()['files'][0]
print(a)

Here is the output, this is the file where are comments that I want to get.

{'id': '1PsV3D0CrCfTpjkbateXiLZIOsoDVV5ha_WV9FFZ2QEM', 'name': 'task', 'mimeType': 'application/vnd.google-apps.document'}

Upvotes: 0

Views: 1170

Answers (1)

Nikko J.
Nikko J.

Reputation: 5533

Comments can be fetch using Drive API Comments.list.

Try appending this to your code:

file_id = a['id']

try:      
    comments = drive.comments().list(fileId=file_id,fields='comments').execute()      
    for comment in comments.get('comments'):         
        print(comment['content'])
except errors.HttpError as error:
    print('An error occurred: %s' % error)

Sample Doc:

enter image description here

Output:

enter image description here

Note: If the value of a in your code is {'id': '1PsV3D0CrCfTpjkbateXiLZIOsoDVV5ha_WV9FFZ2QEM', 'name': 'task', 'mimeType': 'application/vnd.google-apps.document'}, just append the whole code, else replace the file_id with the id of the document. Also, since you are using service account, you need to share the document to the service account email which can be found in the credentials json file. Another option is to use OAuth 2.0 Client ID which can be found in this Demo.

Upvotes: 1

Related Questions