python/googleDocsAPIquickstart.py

from __future__ import print_function
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request

# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/documents.readonly']
SCOPES = ['https://www.googleapis.com/auth/documents']

# The ID of a sample document.
DOCUMENT_ID = '1OgdsHxBeR9xWvUpDbw3wvPvFlaR20t1XvED1rIch7SY'

def show(pr, nd):
    if type(nd) is list:
        for i in range(len(nd)):
            show(pr + '[' + str(i) +']', nd[i])
    elif type(nd) is dict:
        for k, v in nd.items():
            if k in ('link', 'url', 'content'):
                print(pr + '[' + str(k) + ']', v)
            show(pr + '[' + str(k) + ']', v)
    elif type(nd) not in (int, str, float, bool):
        print(pr, type(nd))
            

        
def main():
    """Shows basic usage of the Docs API.
    Prints the title of a sample document.
    """
    creds = None
    # The file token.pickle stores the user's access and refresh tokens, and is
    # created automatically when the authorization flow completes for the first
    # time.
    if os.path.exists('token.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                '/wkData/pc/googleDocsAPIcredentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)

    service = build('docs', 'v1', credentials=creds)

    # Retrieve the documents contents from the Docs service.
    doc = service.documents().get(documentId=DOCUMENT_ID).execute()

    print('The title of the document is: {}'.format(doc.get('title')))
    cont = doc.get('body').get('content')
    print('cont', cont)
    for v in cont:
        print('value', v.keys(), v['startIndex'] if 'startIndex' in v else '-', v['endIndex'])
        if 'paragraph' in v:
            p = v.get('paragraph')
            print('paragraphStyle', p.get('paragraphStyle'), type(p), type(p.get('elements')))
            for e in p.get('elements'):
                tr = e.get('textRun')
                print('e=', tr.get('content') if tr else '-not', 'textStyle', tr.get('textStyle'))


    show('c', cont)

    rq = {'requests' : [ {'insertText': {'text': '<insertAt20>', 'location': {'index': 20}}}
                        , {'updateTextStyle': {'textStyle': {'link': {'url': 'https://wlkl.ch'}}, 'fields': 'link.url', 'range': {'startIndex': 118, 'endIndex': 132}}}]}
    rs = service.documents().batchUpdate(documentId=DOCUMENT_ID, body=rq).execute()
    print('response', rs)

if __name__ == '__main__':
    main()