13

I am trying to make a custom method in my desktop application (using C#), to post a message to a Microsoft team.

But I still don't know what kind of tool or services to get done.

Is it possible to achieve it? if yes, how?

I found a NuGet package regarding MS Teams in Visual Studio but was without luck.

As in the Visual studio marketplace. What I found is https://marketplace.visualstudio.com/items?itemName=ms-vsts.vss-services-teams

But it seems like doesn't meet my requirement.

Maytham Fahmi
  • 31,138
  • 14
  • 118
  • 137
orlandeu man
  • 220
  • 1
  • 3
  • 14

3 Answers3

33

Yes, it is possible to send notifications from your software/desktop application to MS teams. You can either use Microsoft Graph API for MS teams or the MS Teams Incoming hooks feature.

I found it much easier to use incoming hooks.

You can follow 4 steps to send message notifications to your channels:

  1. In your teams, right-click on your channel. And search for Incoming Webhook.
    Right click channel
  2. Installing/Adding Incoming Webhook if not added yet. enter image description here
  3. Configure Incoming Webhook, by providing a webhook name. Click on Create Configure Incoming webhook
  • It will generate a link with unique GUIDs, copy the link enter image description here
  1. Last step, use this command line in the PowerShell
curl.exe -H "Content-Type:application/json" -d "{'text':'Servers x is started.'}" https://example.webhook.office.com/webhookb2/4dee1c26-036c-4bd2-af75-eb1abd901d18@3c69a296-d747-4ef3-9cc5-e94ee78db030/IncomingWebhook/87557542b42d8d3b04453c4a606f2b92/b852b3d0-84b6-4d98-a547-ae5f53452235

Note: the URL in the command line contains some faked GUID unique id reference, but you need to replace it with the one you get from webhooks.

You can either call this line in the command line, PowerShell, or any other programming language that can make a post request and incorporated it in your code. In this case for answering the question, I implemented the post requirest in c#:

using (var httpClient = new HttpClient())
{
    using (var request = new HttpRequestMessage(new HttpMethod("POST"), "https://example.webhook.office.com/webhookb2/4dee1c26-036c-4bd2-af75-eb1abd901d18@3c69a296-d747-4ef3-9cc5-e94ee78db030/IncomingWebhook/87557542b42d8d3b04453c4a606f2b92/b852b3d0-84b6-4d98-a547-ae5f53452235"))
    {
        request.Content = new StringContent("{'text':'Servers x is started.'}");
        request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json"); 

        var response = await httpClient.SendAsync(request);
    }
}

Now when I run the command or C# code I get a message in that channel:

Message Demo


In case you need to remove the hook that you have added, click on Configured then Configure. And Manage the webhook: Manage Web Hook And remove Remove Web Hook

Disclaimer: I wrote an article on my personal blog that covers this topic.

Maytham Fahmi
  • 31,138
  • 14
  • 118
  • 137
3

We have achieved the same with the help of graph API

NB: Sending message to channel is currently beta but will soon move to graph V1 endpoint.

using HTTP:

POST https://graph.microsoft.com/beta/teams/{id}/channels/{id}/messages
Content-type: application/json

{
  "body": {
    "content": "Hello World"
  }
}

using C#:

GraphServiceClient graphClient = new GraphServiceClient( authProvider );

var chatMessage = new ChatMessage
{
    Subject = null,
    Body = new ItemBody
    {
        ContentType = BodyType.Html,
        Content = "<attachment id=\"74d20c7f34aa4a7fb74e2b30004247c5\"></attachment>"
    },
    Attachments = new List<ChatMessageAttachment>()
    {
        new ChatMessageAttachment
        {
            Id = "74d20c7f34aa4a7fb74e2b30004247c5",
            ContentType = "application/vnd.microsoft.card.thumbnail",
            ContentUrl = null,
            Content = "{\r\n  \"title\": \"This is an example of posting a card\",\r\n  \"subtitle\": \"<h3>This is the subtitle</h3>\",\r\n  \"text\": \"Here is some body text. <br>\\r\\nAnd a <a href=\\\"http://microsoft.com/\\\">hyperlink</a>. <br>\\r\\nAnd below that is some buttons:\",\r\n  \"buttons\": [\r\n    {\r\n      \"type\": \"messageBack\",\r\n      \"title\": \"Login to FakeBot\",\r\n      \"text\": \"login\",\r\n      \"displayText\": \"login\",\r\n      \"value\": \"login\"\r\n    }\r\n  ]\r\n}",
            Name = null,
            ThumbnailUrl = null
        }
    }
};

await graphClient.Teams["{id}"].Channels["{id}"].Messages
    .Request()
    .AddAsync(chatMessage);

You may need to look at the official documentation for more clarity. Here is the link below

https://learn.microsoft.com/en-us/graph/api/channel-post-messages?view=graph-rest-beta&tabs=csharp

In my case I was using Angular and calling the endpoints.

Hope it gives some idea.

Ragavan Rajan
  • 4,171
  • 1
  • 25
  • 43
  • How do I create `authProvider` for GraphServiceClient – orlandeu man Jul 17 '19 at 03:12
  • everytime I try to initiate `.CreateClientApplication()` it got red wiggly line. i don't know what's wrong. – orlandeu man Jul 17 '19 at 04:07
  • Are you using oAuthV2 to connect to the Graph Service ? And not sure where you are calling the `createClientApplication() ` – Ragavan Rajan Jul 17 '19 at 04:15
  • `var endpoint = "https://login.microsoftonline.com/organizations/oauth2/v2.0/token";` Create graphservice.cs file – Ragavan Rajan Jul 17 '19 at 04:20
  • May be this definitely help. `https://github.com/microsoftgraph/csharp-teams-sample-graph` try to clone it and tweak your logic. Thanks – Ragavan Rajan Jul 17 '19 at 04:21
  • sorry for not clear enough. in you post `GraphServiceClient( authProvider );`. so try do initiate the auth. with this reference `https://learn.microsoft.com/en-us/graph/sdks/choose-authentication-providers?tabs=CS#integrated-windows-provider` but it always get red wiggly line for `.CreateClientApplication()` – orlandeu man Jul 17 '19 at 09:28
  • been tackling it, but until now, i still don't know to solve my problem. because still confuse of `GRAPH API` and connect it with teams – orlandeu man Jul 17 '19 at 09:29
  • Hi Ragavan. I have been tried testing so many API of Graph API. I think learned quite a few like creating channel. what I want to ask is, How do i post a message to a channel? (I am using C#) i got an error on `new ChatMessage` as it was red line – orlandeu man Jul 22 '19 at 08:34
  • and i using this nugget. `Install-Package Microsoft.Graph Install-Package Microsoft.Graph.Auth -IncludePrerelease` – orlandeu man Jul 22 '19 at 08:39
  • Sure happy to help. posting message to a channel is still under `beta`. `POST /teams/{id}/channels/{id}/messages`. Better to point to you to the official docs https://learn.microsoft.com/en-us/graph/api/channel-post-messages?view=graph-rest-beta&tabs=http – Ragavan Rajan Jul 22 '19 at 10:03
  • If my answer is helpful to you in some way. Kindly do not forget to vote it or accept it. Thanks – Ragavan Rajan Jul 22 '19 at 10:04
  • hi rajan, quick question how do i know what properties are support or use for post message ? `inside chatMessage` like `subject`,`body`. because i want to make a custom / simple post. thanks – orlandeu man Jul 23 '19 at 08:36
  • Body and content should be by default. Try adding the breakpoint and hit from postman on your end point. – Ragavan Rajan Jul 23 '19 at 21:42
  • Thanks for your feedback. I got another question, so every time I run my application, I was prompt to login with Microsoft account. is it possible for user not to login every time they run the program? so they directly post messages to teams – orlandeu man Jul 25 '19 at 06:56
  • Sure. Once Authenticated save the token in session storage. You need to check for default expiry time of token. Hope this will give you some idea – Ragavan Rajan Jul 25 '19 at 08:20
  • could you help me? i post a 2nd thread https://stackoverflow.com/questions/57198357/how-to-use-microsoft-graph-api-without-login-prompt – orlandeu man Jul 25 '19 at 09:28
  • Hello sorry to reopen this subject i have this answer from postman when i try my api route : Message POST is allowed in application-only context only for import purposes DId you encounter this on your path ? – Razgort Nov 15 '22 at 12:17
-1

Posting messages in teams can be acheived with the help of Connectors. Follow the doc to create incoming webhook and post the message using message card.

Community
  • 1
  • 1
Trinetra-MSFT
  • 957
  • 5
  • 9
  • would you tell me how's the logic? I mean, when I click a button on my desktop application, it would send a message into my MS.Team group – orlandeu man Jul 16 '19 at 10:50
  • I have try ask in this post. but it seems it only work for azure devOps. – orlandeu man Jul 16 '19 at 10:51
  • and i have tried another approach by SQL SERVER trigger on MS.Flow. so when i insert data on my application it would post message to Teams. but the problem is the trigger won't work on `premise data`. – orlandeu man Jul 16 '19 at 10:53