-
Notifications
You must be signed in to change notification settings - Fork 0
/
DingTalkRobot.cs
97 lines (83 loc) · 3.09 KB
/
DingTalkRobot.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
using System;
using System.IO;
using System.Net;
using System.Security.Cryptography;
namespace DingTalkRobot {
// ref: https://ding-doc.dingtalk.com/doc#/serverapi2/qf2nxq
public class DingTalkRobot {
private static readonly DateTime EPOCH = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
private const string SUCCESS_RESPONSE = "{\"errcode\":0,\"errmsg\":\"ok\"}";
private string m_WebHookURL = "";
private string m_SecretKey = "";
public DingTalkRobot(String url, String secrete) {
m_WebHookURL = url;
m_SecretKey = secrete;
}
public void SendText(String text, params String[] ats) {
String arg0 = "";
String arg2 = "";
for (int i = 0; i < ats.Length; i++) {
if (i > 0) { arg0 += " "; arg2 += ","; }
arg0 += "@" + ats[i];
arg2 += ats[i];
}
SendRaw(String.Format(@"{{
""msgtype"": ""text"",
""text"": {{
""content"": ""{0} {1}""
}},
""at"": {{
""atMobiles"": [{2}],
""isAtAll"": {3}
}}
}}", arg0, text, arg2, arg0.Length > 0 ? "false" : "true"));
}
public void SendMarkDown(String title, string text, params String[] ats) {
String arg1 = "";
String arg3 = "";
for (int i = 0; i < ats.Length; i++) {
if (i > 0) { arg1 += ","; arg3 += ","; }
arg1 += "@" + ats[i];
arg3 += ats[i];
}
SendRaw(String.Format(@"{{
""msgtype"": ""markdown"",
""markdown"": {{
""title"":""{0}"",
""text"": ""{1} {2}""
}},
""at"": {{
""atMobiles"": [{3}],
""isAtAll"": {4}
}}
}}", title, arg1, text, arg3, arg1.Length > 0 ? "false" : "true"));
}
public void SendRaw(String json) {
json = json.Replace("\r\n", "\n");
long timestamp = (long)(DateTime.UtcNow - EPOCH).TotalMilliseconds;
string signature = "";
using (HMACSHA256 hmac = new HMACSHA256(System.Text.Encoding.Default.GetBytes(m_SecretKey))) {
byte[] hashValue = hmac.ComputeHash(System.Text.Encoding.Default.GetBytes(timestamp + "\n" + m_SecretKey));
signature = Uri.EscapeDataString(Convert.ToBase64String(hashValue));
}
WebRequest request = WebRequest.Create(m_WebHookURL + "×tamp=" + timestamp + "&sign=" + signature);
request.Method = "POST";
request.ContentType = "application/json; charset=utf-8";
request.Timeout = 60 * 1000;
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(json);
using (Stream stream = request.GetRequestStream()) {
stream.Write(bytes, 0, bytes.Length);
}
WebResponse response = request.GetResponse();
using (Stream stream = response.GetResponseStream()) {
StreamReader reader = new StreamReader(stream);
string result = reader.ReadToEnd();
if (result.Equals(SUCCESS_RESPONSE)) {
Console.WriteLine("Send DingTalk Robot Message Successfully");
} else {
throw new Exception(result);
}
}
}
}
}