Skip to content

Tích hợp Teams vào application with C#

Hello các bạn

Hôm nay mình sẽ viết về tút tích hợp team vào hệ thống application để có thể notification tới các member trong team/ mục đích chính là dùng để monitoring các event trong hệ thống hoặc applicaiton của mình.

Ok, bắt đầu nào

Teams (microsoft teams) là gì thì mình gửi link nhé

OK.  cấu hình nào

bước 1. mở 1 cái team lên và tạo 01 channel hoặc chuột phải vào 1 channel và chọn Connector

bước 2.  vào ô search và gõ “Incoming Webhook”

bước 3. chọn configure và các bạn có 1 incoming webhook rồi

document details thì có thể tìm hiểu tại link 

ok giờ vào phần code nhé

github: https://github.com/quyennguyenvan/Microsoft-team-Intergration-C-

mở visual studio và chọn console application / language chọn C#

các extension cần có:  1 Newtonsoft

mình cần có 1 class đóng gói các message và cấu trúc message
thường 1 message lên team gồm có basic như sau:
Type

Title

Text (text ở đây được hiểu là message nhé)

vậy mình có 1 class về message như sau


public class PayloadMessage
{
[JsonProperty("type")]
public string Type { get; set; }
[JsonProperty("title")]
public string Title { get; set; }

[JsonProperty("text")]
public string Text { get; set; }
}

mình cần tiếp 1 class có thể connection tới cái incoming webhook và send cái mớ content của mình lên cái channel mà mình vừa config xong.


public class TeamClient
{
private readonly Uri webHookUri;
private readonly HttpClient httpClient = new HttpClient();
//constructor

public TeamClient(Uri webHookUri)
{
this.webHookUri = webHookUri;
}
public async Task<HttpResponseMessage> SendMessageAsync(string message, string title, string username)
{
PayloadMessage payloadMessage = new PayloadMessage
{
//Username = username,
Type = "MessageCard",
Title = "Daily chat",
Text = message
};
//serializePayload
var serializePayload = JsonConvert.SerializeObject(payloadMessage);
var response = await httpClient.PostAsync(webHookUri,
new StringContent(serializePayload, Encoding.UTF8, "application/json"));
return response;
}
}

ok. bước cuối cùng có thứ để gửi lên channel rồi thì giờ trigger nó và sending message thôi


class Program
{
static void Main(string[] args)
{
Task.WaitAll(IntegrateWithTeamsAsync());

}

private static async Task IntegrateWithTeamsAsync()
{
var webhookUrl = new Uri("your uri");

var slackClient = new TeamClient(webhookUrl);
while (true)
{
Console.Write("Type a message: ");
var message = Console.ReadLine();
var response = await slackClient.SendMessageAsync(message, "iambotakasafe", "quyen nguyen");
var isValid = response.IsSuccessStatusCode ? "valid" : "invalid";
Console.WriteLine($"Received {isValid} response.");
}
}
}

//demo
build code r tự xem chứ đê mô cái gì

 

Published inDevlopment

Ném gạch nào