Dialogflow es 如何在DialogFlow中编写Gmail身份验证代码?

Dialogflow es 如何在DialogFlow中编写Gmail身份验证代码?,dialogflow-es,gmail-api,actions-on-google,Dialogflow Es,Gmail Api,Actions On Google,我正在尝试构建一个Dialogflow,用于检查Gmail收件箱,该收件箱返回用户邮箱中的消息。我读了这篇文章来写认证码。在身份验证过程中,需要访问授权URL并复制代码并将其传递给oAuth2Client.getToken()方法以生成令牌。我的问题是如何处理Gmail身份验证而无需用户干预Dialogflow实现,这样我就可以使用users.messages.list()函数 下面是我当前需要用户干预的代码: 'use strict'; // Import the Dialogflow mo

我正在尝试构建一个Dialogflow,用于检查Gmail收件箱,该收件箱返回用户邮箱中的消息。我读了这篇文章来写认证码。在身份验证过程中,需要访问授权URL并复制代码并将其传递给
oAuth2Client.getToken()
方法以生成令牌。我的问题是如何处理Gmail身份验证而无需用户干预Dialogflow实现,这样我就可以使用
users.messages.list()
函数

下面是我当前需要用户干预的代码:

'use strict';

// Import the Dialogflow module from the Actions on Google client library.
const {dialogflow} = require('actions-on-google');
// Import the firebase-functions package for deployment.
const functions = require('firebase-functions');
const CHECK_INBOX='chcek inbox';
const fs = require('fs');
const readline = require('readline');
const {google} = require('googleapis');

// If modifying these scopes, delete token.json.
const SCOPES = ['https://www.googleapis.com/auth/gmail.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.
const TOKEN_PATH = 'token.json';
const content='{"installed":{"client_id":"*****","project_id":"*****","auth_uri":"https://accounts.google.com/o/oauth2/auth","token_uri":"https://oauth2.googleapis.com/token","auth_provider_x509_cert_url":"https://www.googleapis.com/oauth2/v1/certs","client_secret":"****","redirect_uris":["urn:ietf:wg:oauth:2.0:oob","http://localhost"]}}';



exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
  const agent = new WebhookClient({ request, response }); /// Thid is to handle the communication with dialogflow
  let intentMap = new Map();
  intentMap.set(CHECK_INBOX, checkInbox);  // It maps the intent 'Make Appointment' to the function 'makeAppointment()'
  agent.handleRequest(intentMap);
});

function chcekInbox(agent){
authorize(JSON.parse(content), listMessages,agent);


}


function authorize(credentials, callback,agent) {
  const {client_secret, client_id, redirect_uris} = credentials.installed;
  const oAuth2Client = new google.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) return getNewToken(oAuth2Client, callback,agent);
    oAuth2Client.setCredentials(JSON.parse(token));
    callback(oAuth2Client,agent);
  });
}

function getNewToken(oAuth2Client, callback,agent) {
  const authUrl = oAuth2Client.generateAuthUrl({
    access_type: 'offline',
    scope: SCOPES,
  });
  console.log('Authorize this app by visiting this url:', authUrl);
  const rl = 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) return console.error('Error retrieving access token', err);
      oAuth2Client.setCredentials(token);
      // Store the token to disk for later program executions
      fs.writeFile(TOKEN_PATH, JSON.stringify(token), (err) => {
        if (err) return console.error(err);
        console.log('Token stored to', TOKEN_PATH);
      });
      callback(oAuth2Client,agent);
    });
  });
}

function listMessages(auth,agent) {
  const gmail = google.gmail({version: 'v1', auth});
  gmail.users.messages.list({
    userId: 'me',
  },(err, res) => {
    if (err) return console.log('The API returned an error: ' + err);
    const messages = res.data.messages;
    if (messages.length) {
      console.log('messages are: :');
      messages.forEach((message) => {
        printMessage(message.id,gmail,agent);
      });
    } else {
      console.log('No messages found.');
    }
  });

}


  function printMessage(messageId,gmail,agent){
    gmail.users.messages.get({
      userId: 'me',
      id:messageId
    },(err, res) => {
      if (err) return console.log('The API returned an error: ' + err);
      const headers = res.data.payload.headers;
      if (headers.length) {
        headers.forEach((header) => {
          if(header.name==="Subject"){
            agent.add(header.value)


          }
        });
      } else {
        console.log('No messages found.');
      }

    });

  }

注意:我使用的是内联编辑器。

只是提醒一下,你想替换const CHECK_INBOX='chcek INBOX';使用const CHECK_INBOX='CHECK INBOX';只是提醒一下,你想替换const CHECK_INBOX='chcek INBOX';使用const CHECK_INBOX='CHECK INBOX';