Giới thiệu
Hê Lu. Hôm nay mình sẽ hướng dẫn các bạn sử dụng Webhook của Slack để tạo ra một Chat Bot gửi tin nhắn qua các kênh nhé!!
Let's go!!!!
Tạo Webhook Slack
Để tạo được Webhook trong Slack các bạn làm theo các bước sau:
B1: Các bạn vào link https://api.slack.com/apps của Slack để tạo cho mình một App (Nếu bạn chưa tạo Workspace thì cần tạo WS trước nhé)
B2: Các bạn bấm Create New App

B3: Chọn From scratch

B4: Đặt tên App và chon Workspace cần tạo

B5: Tiếp theo chọn Incomimg Webhooks

B6: Active Webhook và chọn Add new Webhook to Workspace

B7: Chọn Chanel và nhấn Allow

B8: Copy Webhook vừa tạo được và lưu lại chút sẽ dùng đến

Cấu hình Code
Trước tiên các bạn cài cho mình Nuget: RestSharp nhé
Ở đây mình có ra một enum có tên SlackIcon. Enum này sẽ là phần hiển thị một hình ảnh bên phải tin nhắn như sau:

public enum SlackIcon
{
[Description("https://i.imgur.com/Rgi040T.png")]
Success,
[Description("https://i.imgur.com/GNhNUcF.png")]
Error
}
Mình sẽ tạo ra một class để đọc Attribute Description trong Enum có tên EnumHelper
public static class EnumHelper
{
public static string ReadDescription(this T enumChild)
{
var type = typeof(T);
var fieldInfo = type.GetField(enumChild?.ToString() ?? string.Empty);
if (fieldInfo is null) return "";
var attr = (DescriptionAttribute[])
fieldInfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
return attr.Length > 0 ? attr[0].Description : "";
}
}
Tiếp đến là đoạn code gửi tin nhắn thông qua Webhook. Ở đây mình sẽ sử dụng RestSharp
public static class SlackNotification
{
public static async Task SendMessageAsync(
string webhookUrl
, string title
, SlackIcon slackIcon
, string titleUrl
, string content)
{
var client = new RestClient(webhookUrl);
var request = new RestRequest() { Method = Method.Post };
request.AddJsonBody(
new
{
blocks = new List()
{
new
{
type = "section",
text = new
{
type = "mrkdwn",
text = $"*<{titleUrl}|{title.ToUpper()}>*"
}
},
new
{
type = "section",
text = new
{
type = "mrkdwn",
text = $"{content}"
},
accessory = new
{
type = "image",
image_url = $"{slackIcon.ReadDescription()}",
alt_text = "icon thumbnail"
}
}
}
}
);
var response = await client.ExecuteAsync(request);
}
}
Cuối dùng là gọi hàm SendMessageAsync ra để dùng thôi:
var webhoobkURL = "https://hooks.slack.com/services/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";
var title = "Hello World 2";
var icon = SlackIcon.Error;
var titleUrl = "https://code-mega.com";
var content = "Have a nice day!!! \n *Code Mega*";
await SlackNotification.SendMessageAsync(webhoobkURL, title, icon, titleUrl, content);
Vậy là xong rồi. Dễ hơn ăn kẹo đúng không nào.
Source code các bạn Download nên dưới nhé !!!