using System; using System.IO; using System.Threading; using Google; using Google.Apis.Auth.OAuth2; using Google.Apis.Calendar.v3; using Google.Apis.Calendar.v3.Data; using Google.Apis.Services; public class CalendarApiTest { public static async Task GetLatestEventAsync(string calendarId, string credentialsFilePath) { try { CalendarService service = getCalendarService(credentialsFilePath); // イベントリストのリクエストを作成 var request = service.Events.List(calendarId); request.TimeMin = DateTime.UtcNow; request.ShowDeleted = false; request.SingleEvents = true; request.MaxResults = 10; request.OrderBy = EventsResource.ListRequest.OrderByEnum.StartTime; // イベントリストのリクエストを実行 var events = await request.ExecuteAsync(); if (events.Items != null && events.Items.Count > 0) { Console.WriteLine("最新の予定:"); foreach (var eventItem in events.Items) { var when = eventItem.Start.DateTime.ToString() ?? eventItem.Start.Date; Console.WriteLine($"{eventItem.Summary} ({when})"); } } else { Console.WriteLine("近日中の予定はありません。"); } } catch (GoogleApiException ex) { Console.WriteLine($"Error: {ex.Message}"); Console.WriteLine($"HttpStatusCode: {ex.HttpStatusCode}"); Console.WriteLine($"ErrorDetails: {ex.Error}"); } catch (Exception ex) { Console.WriteLine($"Error: {ex.Message}"); } } public static CalendarService getCalendarService(string credentialsFilePath) { // サービスアカウントの認証情報を読み込む GoogleCredential credential; using (var stream = new FileStream(credentialsFilePath, FileMode.Open, FileAccess.Read)) { credential = GoogleCredential.FromStream(stream).CreateScoped(CalendarService.Scope.CalendarReadonly); } // GoogleカレンダーAPIのサービスを作成 var service = new CalendarService(new BaseClientService.Initializer { HttpClientInitializer = credential, ApplicationName = "VQCalendarAttention", }); return service; } }