VB.NETでTeamsGraphAPIを使用するサンプルコード
Imports SystemImports System.Net.HttpImports System.Net.Http.HeadersImports System.Threading.TasksModule Module1 Sub Main() Dim clientId As String = "YOUR_CLIENT_ID" Dim clientSecret As String = "YOUR_CLIENT_SECRET" Dim tenantId As String = "YOUR_TENANT_ID" Dim accessToken As String = GetAccessTokenAsync(clientId, clientSecret, tenantId).GetAwaiter().GetResult() If Not String.IsNullOrEmpty(accessToken) Then Console.WriteLine("Access Token: " & accessToken) GetTeamsAndChannelsAsync(accessToken).GetAwaiter().GetResult() Else Console.WriteLine("Failed to retrieve access token.") End If End Sub Async Function GetAccessTokenAsync(clientId As String, clientSecret As String, tenantId As String) As Task(Of String) Dim httpClient As New HttpClient() Dim request As New HttpRequestMessage(HttpMethod.Post, $"https://login.microsoftonline.com/{tenantId}/oauth2/v2.0/token") request.Content = New FormUrlEncodedContent(New Dictionary(Of String, String) From { {"client_id", clientId}, {"scope", "https://graph.microsoft.com/.default"}, {"client_secret", clientSecret}, {"grant_type", "client_credentials"} }) Dim response = Await httpClient.SendAsync(request) Dim responseBody = Await response.Content.ReadAsStringAsync() If response.IsSuccessStatusCode Then Dim accessTokenObject = JObject.Parse(responseBody) Return accessTokenObject("access_token").ToString() Else Console.WriteLine("Failed to retrieve access token. Error: " & responseBody) Return Nothing End If End Function Async Function GetTeamsAndChannelsAsync(accessToken As String) As Task Dim httpClient As New HttpClient() httpClient.DefaultRequestHeaders.Authorization = New AuthenticationHeaderValue("Bearer", accessToken) Dim response = Await httpClient.GetAsync("https://graph.microsoft.com/v1.0/me/joinedTeams?$select=id,displayName") Dim responseBody = Await response.Content.ReadAsStringAsync() If response.IsSuccessStatusCode Then Dim teamsObject = JObject.Parse(responseBody) Dim teams = teamsObject("value") For Each team In teams Dim teamId = team("id").ToString() Dim teamDisplayName = team("displayName").ToString() Console.WriteLine("Team ID: " & teamId & ", Team Name: " & teamDisplayName) Dim channelsResponse = Await httpClient.GetAsync($"https://graph.microsoft.com/v1.0/teams/{teamId}/channels") Dim channelsResponseBody = Await channelsResponse.Content.ReadAsStringAsync() If channelsResponse.IsSuccessStatusCode Then Dim channelsObject = JObject.Parse(channelsResponseBody) Dim channels = channelsObject("value") For Each channel In channels Dim channelId = channel("id").ToString() Dim channelDisplayName = channel("displayName").ToString() Console.WriteLine(" Channel ID: " & channelId & ", Channel Name: " & channelDisplayName) Next Else Console.WriteLine("Failed to retrieve channels for team " & teamDisplayName) End If Next Else Console.WriteLine("Failed to retrieve joined teams.") End If End FunctionEnd Module