週間予定の取得
実行環境
M1 MacbookAir 16GB
import os import datetime import pytz from google.oauth2.credentials import Credentials from googleapiclient.discovery import build # カレンダーAPIのスコープ SCOPES = ['https://www.googleapis.com/auth/calendar.readonly'] def main(): """今週の残りのGoogleカレンダーの予定を取得して表示します。""" creds = None # 既存のトークンファイルを使用 if os.path.exists('token.json'): creds = Credentials.from_authorized_user_file('token.json', SCOPES) else: print("トークンファイルが見つかりません。認証を実行してください。") return # Google Calendar APIサービスを構築 service = build('calendar', 'v3', credentials=creds) # タイムゾーンの設定(日本時間) tz = pytz.timezone('Asia/Tokyo') # 現在の日時を取得 now = datetime.datetime.now(tz) # 今週の終了日(日曜日)を計算 start_of_week = now - datetime.timedelta(days=now.weekday()) end_of_week = start_of_week + datetime.timedelta(days=7) # time_minを現在の日時に設定 time_min = now.isoformat() # time_maxは今週の終了日時 time_max = end_of_week.isoformat() print(f"{time_min} から {time_max} までの予定を取得します。") # イベントを取得 events_result = service.events().list( calendarId='primary', timeMin=time_min, timeMax=time_max, singleEvents=True, orderBy='startTime' ).execute() events = events_result.get('items', []) if not events: print('今週の残りの予定はありません。') else: print('今週の残りの予定:') for event in events: start = event['start'].get('dateTime', event['start'].get('date')) summary = event.get('summary', '(タイトルなし)') print(f"{start} - {summary}") if __name__ == '__main__': main()
を実行したが
2024-10-09T01:28:10.960984+09:00 から 2024-10-14T01:28:10.960984+09:00 までの予定を取得します。 Traceback (most recent call last): File "/Users/snowpool/aw10s/week_calendar_voice/get_week.py", line 60, in <module> main() File "/Users/snowpool/aw10s/week_calendar_voice/get_week.py", line 47, in main ).execute() File "/Users/snowpool/.pyenv/versions/3.10.6/lib/python3.10/site-packages/googleapiclient/_helpers.py", line 130, in positional_wrapper return wrapped(*args, **kwargs) File "/Users/snowpool/.pyenv/versions/3.10.6/lib/python3.10/site-packages/googleapiclient/http.py", line 923, in execute resp, content = _retry_request( File "/Users/snowpool/.pyenv/versions/3.10.6/lib/python3.10/site-packages/googleapiclient/http.py", line 191, in _retry_request resp, content = http.request(uri, method, *args, **kwargs) File "/Users/snowpool/.pyenv/versions/3.10.6/lib/python3.10/site-packages/google_auth_httplib2.py", line 209, in request self.credentials.before_request(self._request, method, uri, request_headers) File "/Users/snowpool/.pyenv/versions/3.10.6/lib/python3.10/site-packages/google/auth/credentials.py", line 135, in before_request self.refresh(request) File "/Users/snowpool/.pyenv/versions/3.10.6/lib/python3.10/site-packages/google/oauth2/credentials.py", line 335, in refresh ) = reauth.refresh_grant( File "/Users/snowpool/.pyenv/versions/3.10.6/lib/python3.10/site-packages/google/oauth2/reauth.py", line 351, in refresh_grant _client._handle_error_response(response_data, retryable_error) File "/Users/snowpool/.pyenv/versions/3.10.6/lib/python3.10/site-packages/google/oauth2/_client.py", line 73, in _handle_error_response raise exceptions.RefreshError( google.auth.exceptions.RefreshError: ('invalid_scope: Bad Request', {'error': 'invalid_scope', 'error_description': 'Bad Request'})
となる
Chatgpt では
SCOPES = ['https://www.googleapis.com/auth/calendar.readonly']
となっているが
SCOPES = ['https://www.googleapis.com/auth/calendar']
というようにスコープを変更したら解決した
これはカレンダー追加がこのスコープで動作するのに
取得の場合はコードが違うので試したら動いた