Open3

GCP

ino_hino_h

Googleカレンダー

ino_hino_h

サンプルコード

require('dotenv').config(); // 最初に.envを読み込む
const { google } = require('googleapis');
const fs = require('fs').promises;
const path = require('path');
const http = require('http');
const url = require('url');

// APIに要求する権限を指定
const SCOPES = ['https://www.googleapis.com/auth/calendar.readonly'];

// 環境変数が設定されているか確認
if (!process.env.GOOGLE_CLIENT_ID || !process.env.GOOGLE_CLIENT_SECRET) {
 console.error('エラー: .envファイルにGOOGLE_CLIENT_IDとGOOGLE_CLIENT_SECRETが設定されていません。');
 process.exit(1);
}

// OAuth2クライアントの設定
const oauth2Client = new google.auth.OAuth2(
 process.env.GOOGLE_CLIENT_ID,
 process.env.GOOGLE_CLIENT_SECRET,
 'http://localhost:3000/oauth2callback'
);

async function getAccessToken() {
 try {
   // 認証URLを生成
   const authUrl = oauth2Client.generateAuthUrl({
     access_type: 'offline',
     scope: SCOPES,
     prompt: 'consent',
     force: true // 強制的に新しいトークンを取得
   });

   // ローカルサーバーを起動して認証コードを待機
   const server = http.createServer(async (req, res) => {
     try {
       const queryParams = url.parse(req.url, true).query;
       const code = queryParams.code;

       if (code) {
         // 認証コードを使用してトークンを取得
         const { tokens } = await oauth2Client.getToken(code);
         oauth2Client.setCredentials(tokens);

         // トークンを保存
         await fs.writeFile('token.json', JSON.stringify(tokens));

         res.writeHead(200, { 'Content-Type': 'text/html' });
         res.end('認証が完了しました。このページを閉じてください。');
         server.close();
       }
     } catch (error) {
       console.error('認証エラー:', error);
       res.writeHead(500, { 'Content-Type': 'text/html' });
       res.end('認証中にエラーが発生しました。');
       server.close();
     }
   });

   // サーバーを起動
   server.listen(3000, () => {
     console.log('認証サーバーを起動しました。');
     console.log('以下のURLにアクセスして認証を行ってください:');
     console.log(authUrl);
   });

   // サーバーが閉じられるまで待機
   await new Promise(resolve => server.on('close', resolve));

 } catch (error) {
   console.error('トークン取得エラー:', error);
   throw error;
 }
}

async function main() {
 try {
   // アクセストークンを取得
   await getAccessToken();

   const calendar = google.calendar({ version: 'v3', auth: oauth2Client });
   
   // カレンダーAPIを呼び出し
   const now = new Date().toISOString();
   console.log('次の10件のイベントを取得中');
   
   const response = await calendar.events.list({
     calendarId: 'primary',
     timeMin: now,
     maxResults: 10,
     singleEvents: true,
     orderBy: 'startTime',
   });

   const events = response.data.items;

   if (!events || events.length === 0) {
     console.log('次のイベントはありません。');
     return;
   }

   // イベントの開始日時と名前を表示
   events.forEach(event => {
     const start = event.start.dateTime || event.start.date;
     console.log(`${start} ${event.summary}`);
   });

 } catch (error) {
   console.error('エラーが発生しました:', error.message);
 }
}

// スクリプトが直接実行された場合のみmain()を実行
if (require.main === module) {
 main();
}