Microsoft Teams Graph API: сбой при добавлении канала в команды с 404 - PullRequest
0 голосов
/ 10 декабря 2018

Я пытался добавить каналы во вновь созданные команды Microsoft, используя Microsoft Graph API и Invoke-RestMethod со следующим Powershell, запущенным в функциях Azure.

Я пробовал и v1.0, и бета-версию, и искал высоко иПримеры для этого:

# code that successfully creates a team based on existing Office 365 Group not shown, but is
# comes from [https://github.com/martinagrom/Ignite2018GroupsGovernanceToolkit][1], f1-CreateGroup and f2-CreateTeam

function AddContent ($folderName) {
Write-Output "Inside of AddContent"
$Body = @{
    "displayName"= "$folderName"
    "description"= "Add decription"
}
$bodyJSON = $body | ConvertTo-Json
Write-Output "Adding channel $($folderName)"
Write-Output "bodyJSON $($bodyJSON)"
try {
    Write-Output "creating channel on https://graph.microsoft.com/beta/teams/$($TeamID)/channels"
    $result = Invoke-RestMethod `
                            -Method POST `
                            -Uri "https://graph.microsoft.com/beta/teams/$($TeamID)/channels" `
                            -ContentType 'application/json' `
                            -Headers $script:APIHeader `
                            -Body $bodyJSON `
                            -ErrorAction Stop

    $TeamResult = $result.id
    Write-Output "Channel created: ID:[$TeamResult]"
} catch [System.Net.WebException] {
    Write-Output "AddChannelOnExistingTeam: $($TeamResult.error.code) => $($TeamResult.error.message)"
    Write-Output "https://graph.microsoft.com/beta/teams/$($TeamID)/channels   ---    $script:APIHeader --- $body"
    If ($_.Exception.Response.StatusCode.value__) {
        $crap = ($_.Exception.Response.StatusCode.value__ ).ToString().Trim();
        Write-Output $crap;
    }
    If  ($_.Exception.Message) {
        $crapMessage = ($_.Exception.Message).ToString().Trim();
        Write-Output $crapMessage;
    }
    $result = $_.Exception.Response.GetResponseStream()
    $reader = New-Object System.IO.StreamReader($result)
    $reader.BaseStream.Position = 0
    $reader.DiscardBufferedData()
    $responseBody = $reader.ReadToEnd();
    Write-Output $responseBody
throw "AddChannelOnExistingTeam: $($TeamResult.error.code) => $($TeamResult.error.message)"
}
catch {
    Write-Output "AddChannelOnExistingTeam: Another Exception caught: [$($_.Exception)]"
    throw "AddChannelOnExistingTeam: $($TeamResult.error.code) => $($TeamResult.error.message)"
}
}

# The team has just been created based on an Office365 group by code (not shown) and the Group/Team ID is in the $TeamResult
# I do a sleep to ensure Team is ready, probably not necessary. Plenty of Write-Out to debug progress. Log futher down
# I grap a list of folder names from a document library and is calling the above function with each name to create a corrosponding channel

Start-Sleep -Seconds 60
$TeamID = $TeamResult
$TeamChannels = $TeamInfo.TeamChannels
Write-Output "TeamChannels $($TeamChannels) on TeamID $($TeamID)"
$sourcesite = $TeamChannels.SubString(0,$TeamChannels.lastIndexOf('/'))
$secpasswd = ConvertTo-SecureString $env:SPO_P -AsPlainText -Force
$mycreds = New-Object System.Management.Automation.PSCredential ($env:SPO_U, $secpasswd)
connect-PnPOnline -Credentials $mycreds -url $sourcesite 
$folders = Get-pnpFolderItem -FolderSiteRelativeUrl $TeamChannels.SubString($TeamChannels.lastIndexOf('/')+1)

ForEach ($folder in $folders) {
if ($folder.Name -ne "Forms") {
    AddContent($folder.Name)
}
}

Создание кода группы и команд из Мартины Гром

И вывод журнала:

2018-12-10T12:15:07.373 [Info] TeamChannels https://contoso.sharepoint.com/sites/Projects/Template on TeamID xxxxxx-e3ab-4e3a-b81d-c540c8e2e6ea
2018-12-10T12:15:08.889 [Info] Inside of AddContent
2018-12-10T12:15:08.889 [Info] Adding channel 01. Gate - Documentation
2018-12-10T12:15:08.889 [Info] bodyJSON {
    "displayName":  "01. Gate - Documentation",
    "description":  "Add decription"
}
2018-12-10T12:15:08.889 [Info] creating channel on https://graph.microsoft.com/beta/teams/xxxxxx-e3ab-4e3a-b81d-c540c8e2e6ea/channels
2018-12-10T12:15:08.920 [Info] AddChannelOnExistingTeam:  =>
2018-12-10T12:15:08.920 [Info] https://graph.microsoft.com/beta/teams/xxxxxx-e3ab-4e3a-b81d-c540c8e2e6ea/channels   ---    System.Collections.Hashtable --- System.Collections.Hashtable
2018-12-10T12:15:08.920 [Info] 404
2018-12-10T12:15:08.920 [Info] The remote server returned an error: (404) Not Found.
2018-12-10T12:15:08.920 [Info] {
  "error": {
    "code": "UnknownError",
    "message": "{\"message\":\"No HTTP resource was found that matches the request URI 'https://api.teams.skype.com/beta/teams('xxxxxx-e3ab-4e3a-b81d-c540c8e2e6ea')/channels'.\"}",
    "innerError": {
      "request-id": "10523b5c-55b7-4a2e-a428-f94b7f0fa88a",
      "date": "2018-12-10T12:15:08"
    }
  }
}

2018-12-10T12:15:08.952 [Error] Exception while executing function: Functions.CreateTeam. System.Management.Automation: AddChannelOnExistingTeam:  => . AddChannelOnExistingTeam:  => .
2018-12-10T12:15:08.983 [Error] Function completed (Failure, Id=xxxxxxx-52cd-45c7-9bd8-5e509353ddfc, Duration=64753ms)

# End of Log

ИтакPOST to https://graph.microsoft.com/beta/teams/TeamID/channels возвращается к https://api.teams.skype.com/beta/teams('TeamID')/channels и завершается ошибкой с 404

Если я иду в Microsoft Graph Explorer и вводит ту же самую информацию, которую создает канал (ы).

Чего мне не хватает?Не хватает разрешений API?Любые советы будут оценены.

1 Ответ

0 голосов
/ 11 декабря 2018

Хорошо, я обнаружил ошибку, чистая слепота копирования-вставки…: (

Скопированный мною Invoke-RestMethod был методом PUT, который выдает ошибку 404 при попытке использовать его для создания каналов.

Поэтому, когда я изменил его на метод POST, он начал работать. Я отредактировал источник.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...