bob
bob

Reputation: 625

Send a message to a Channel in Teams via Graph

I try to send a message to a specific channel in teams. It works perfectly with 'https://developer.microsoft.com/de-de/graph/graph-explorer'.

For reciving the access token i do the following. This part works, because i can retrieve user information and other things with it.

$guzzle = new \GuzzleHttp\Client(['verify' => false]);
$tenantId = '<tenant_id>';

$clientId = '<client_id>';
$clientSecret = '<client_secret>';
$url = 'https://login.microsoftonline.com/' . $tenantId . '/oauth2/token?api-version=1.0';
$token = json_decode($guzzle->post($url, [
        'form_params' => [
            'client_id' => $clientId,
            'client_secret' => $clientSecret,
            'resource' => 'https://graph.microsoft.com/',
            'grant_type' => 'client_credentials',
    ],
    'verify' => false
])->getBody()->getContents());
$accessToken = $token->access_token;

This part now is the one that produces the error

$graph = new Graph();
$graph->setAccessToken($accessToken);

$url = '/teams/<team_id>/channels/<channel_id>/messages';


$queryParams = [
    'body' => [
        'content' => 'foo'
    ]
];    
$info = $graph->setApiVersion("beta")->createRequest("POST", $url)
    ->addHeaders(array("Content-Type" => "application/json"))
    ->attachBody($queryParams)
    ->setReturnType(BetaModel\User::class)
    ->execute();
echo '<pre>';
print_r($info);

This produces the following error

{
  "error": {
    "code": "UnknownError",
    "message": "",
    "innerError": {
      "date": "2020-11-11T10:14:03",
      "request-id": "<request_id>",
      "client-request-id": "<client_request_id>"
    }
  }
}

The teams id and the channel id are correct, i can retrieve them by using

/users/<user_id>/joinedTeams

and

/teams/<teams_id>/channels

and as mentioned earlier, it works in the graph explorer page. I know that i somehow need to send the message in an user context, but i can't make it work, and i can't find useful informations, so i am pleased for any. Thanks in advance!

Upvotes: 0

Views: 943

Answers (1)

Carl Zhao
Carl Zhao

Reputation: 9511

This api call currently does not support application permissions, so you cannot use the client credential flow to obtain a token. You need to grant delegated permissions to the application, and then use the auth code flow to obtain the token. see:here.

enter image description here

Upvotes: 1

Related Questions