sales_tool/functions/upload-minutes-to-drive/source/main.py
2025-11-17 14:21:29 +09:00

128 lines
4 KiB
Python
Executable file

import functions_framework
from google.cloud import secretmanager
from google.oauth2 import service_account
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
import json
import os
SCOPES = ["https://www.googleapis.com/auth/drive", "https://www.googleapis.com/auth/drive.file"]
sm_client = secretmanager.SecretManagerServiceClient()
@functions_framework.http
def handle_request(request):
# POSTリクエストの処理
if request.method != 'POST':
# 他のメソッドに対するエラーレスポンス
return ({'error': 'Method not allowed'}, 405)
try:
request_json = request.get_json()
print(request_json)
folder_id = os.getenv("FOLDER_ID") # 共有ドライブID
file_name = request_json["file_name"] # 会議タイトル
minutes = request_json["minutes"] # 議事録
# Secret Manager からサービスアカウントJSON文字列を取得
service_account_info = get_service_account_info()
# 認証
credentials = get_credentials(service_account_info)
# APIクライアントの構築
drive_service = build("drive", "v3", credentials=credentials)
docs_service = build("docs", "v1", credentials=credentials)
# ファイル作成
document_id = create_new_document(drive_service, folder_id, file_name)
print(f"Created document with ID: {document_id}")
# テキスト内容をセット
append_minutes_to_doc(docs_service, document_id, minutes)
response_data = {
"document_id": document_id, # 作成したドキュメントのID
}
return json.dumps(response_data) , 200, {"Content-Type": "application/json"}
except Exception as e:
# エラー
error_response = {
"error": str(e) #エラー内容
}
print(str(e))
return json.dumps(error_response), 500, {'Content-Type': 'application/json'} #エラー
#
# SecretManagerから秘密鍵を取得
#
def get_service_account_info():
key_path = os.getenv('KEY_PATH') + "/versions/1"
# 秘密鍵取得
response = sm_client.access_secret_version(name=key_path)
# 秘密鍵の値をデコード
secret_key = response.payload.data.decode("UTF-8")
return json.loads(secret_key)
# Google Drive認証
def get_credentials(service_account_info):
credentials = service_account.Credentials.from_service_account_info(
service_account_info,
scopes=SCOPES
)
return credentials
def create_new_document(service,folder_id,title):
"""
Google Sheets APIを使用して新しいスプレッドシートを作成する
:param service: Google Sheets APIのサービスオブジェクト
:param title: スプレッドシートのタイトル
:return: 作成したスプレッドシートのID
"""
file_metadata = {
'name': title,
'parents': [folder_id], # 作成したフォルダのIDを指定
'mimeType': 'application/vnd.google-apps.document',
}
result = (
service.files()
.create(body=file_metadata, fields="id", supportsAllDrives=True)
.execute()
)
return result.get("id")
def append_minutes_to_doc(service, document_id, minutes):
"""
Google Sheets APIを使用してスプレッドシートにログを追加する
:param service: Google Sheets APIのサービスオブジェクト
:param spreadsheet_id: スプレッドシートのID
:param row_data: 追加するログデータ(リスト形式)
"""
requests = [
{
'insertText': {
'location': {
'index': 1,
},
'text': minutes
}
},
]
body = {
'requests': requests
}
# スプレッドシートにログを追加
result = service.documents().batchUpdate(
documentId=document_id,
body=body,
).execute()
return result