Quantcast
Channel: Node.jsタグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 8829

Node.jsでGoogle Slides内のテキストを取得してみる

$
0
0

Node.jsでGoogle Slides APIを触ってみるの続きです。

準備

前回の記事を参照して、スライド情報にNode.jsからアクセス出来るようにしましょう。

適当なスライドを用意する

こちらを用意してみました。

https://docs.google.com/presentation/d/1ziVnaFocZ_YF_cuXyXF5PUKGoE62eX-XlnOEslPkKUc/edit#slide=id.p

https://docs.google.com/presentation/d/<ここがプレゼンテーションID>/edit#slide=id.pになるのでこのスライドのプレゼンテーションIDは1ziVnaFocZ_YF_cuXyXF5PUKGoE62eX-XlnOEslPkKUcになります。

Node.jsでGoogle Slidesのテキストを抽出

前回のコードからプレゼンテーションIDの箇所とfunction listSlides(auth)の中身を書き換えてます。

app.js
constfs=require('fs');constreadline=require('readline');const{google}=require('googleapis');//変更箇所: プレゼンテーションID - 試すときは自分のスライドでもやってみましょうconstpresentationId=`1ziVnaFocZ_YF_cuXyXF5PUKGoE62eX-XlnOEslPkKUc`;// If modifying these scopes, delete token.json.constSCOPES=['https://www.googleapis.com/auth/presentations.readonly'];// The file token.json stores the user's access and refresh tokens, and is// created automatically when the authorization flow completes for the first// time.constTOKEN_PATH='token.json';// Load client secrets from a local file.fs.readFile('credentials.json',(err,content)=>{if(err)returnconsole.log('Error loading client secret file:',err);// Authorize a client with credentials, then call the Google Slides API.authorize(JSON.parse(content),listSlides);});/**
 * Create an OAuth2 client with the given credentials, and then execute the
 * given callback function.
 * @param {Object} credentials The authorization client credentials.
 * @param {function} callback The callback to call with the authorized client.
 */functionauthorize(credentials,callback){const{client_secret,client_id,redirect_uris}=credentials.installed;constoAuth2Client=newgoogle.auth.OAuth2(client_id,client_secret,redirect_uris[0]);// Check if we have previously stored a token.fs.readFile(TOKEN_PATH,(err,token)=>{if(err)returngetNewToken(oAuth2Client,callback);oAuth2Client.setCredentials(JSON.parse(token));callback(oAuth2Client);});}/**
 * Get and store new token after prompting for user authorization, and then
 * execute the given callback with the authorized OAuth2 client.
 * @param {google.auth.OAuth2} oAuth2Client The OAuth2 client to get token for.
 * @param {getEventsCallback} callback The callback for the authorized client.
 */functiongetNewToken(oAuth2Client,callback){constauthUrl=oAuth2Client.generateAuthUrl({access_type:'offline',scope:SCOPES,});console.log('Authorize this app by visiting this url:',authUrl);constrl=readline.createInterface({input:process.stdin,output:process.stdout,});rl.question('Enter the code from that page here: ',(code)=>{rl.close();oAuth2Client.getToken(code,(err,token)=>{if(err)returnconsole.error('Error retrieving access token',err);oAuth2Client.setCredentials(token);// Store the token to disk for later program executionsfs.writeFile(TOKEN_PATH,JSON.stringify(token),(err)=>{if(err)returnconsole.error(err);console.log('Token stored to',TOKEN_PATH);});callback(oAuth2Client);});});}/**
 * Prints the number of slides and elements in a sample presentation:
 * https://docs.google.com/presentation/d/1EAYk18WDjIG-zp_0vLm3CsfQh_i8eXc67Jo2O9C6Vuc/edit
 * @param {google.auth.OAuth2} auth The authenticated Google OAuth client.
 * 
 */functionlistSlides(auth){constslides=google.slides({version:'v1',auth});slides.presentations.get({presentationId:presentationId,},(err,res)=>{if(err)returnconsole.log('The API returned an error: '+err);/* 変更箇所: スライド中のテキストを抽出するテスト */constfirstPage=res.data.slides[0];//1スライド目constfirstBox=firstPage.pageElements[0];//最初の要素console.log(firstBox.shape.text.textElements[1].textRun.content);//中身のテキスト確認});}

素でアクセすると

res.data.slides[0].pageElements[0].shape.text.textElements[1].textRun.content

みたいな感じで超深い階層になるみたいです。

  • res.data.slides: スライドXXページごとの配列 今回はタイトルスライドから抜き出すので0指定
  • firstPage.pageElements: 対象ページのオブジェクト(テキストボックスなど)の配列 今回はページの最初の部ジェクトなので0指定

実行

$ node app.js 
Node.jsてすと

ちゃんとテキストがとれましたね。

所感

返ってくるオブジェクトが結構複雑な印象です。

詳細はslides周りのSDKを覗くのが良さそうだけどどんなオブジェクトが返ってくるかはまだ見つけられてないのでconsole.logで探していったほうが早いかも

追記: 今回使ってるpresentations.getのAPIリファレンスはここっぽい

https://developers.google.com/slides/reference/rest/v1/presentations/get


Viewing all articles
Browse latest Browse all 8829

Trending Articles