1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586 |
- using System.Text;
- using System.Text.Json.Serialization;
- namespace StationProbe
- {
- internal class DingTalk
- {
- internal class AcceccTokenResult
- {
- [JsonPropertyName("errcode")]
- public int ErrorCode { get; set; }
- [JsonPropertyName("errmsg")]
- public string ErrorMsg { get; set; } = string.Empty;
- [JsonPropertyName("access_token")]
- public string AccessToken { get; set; } = string.Empty;
- [JsonPropertyName("expires_in")]
- public int ExpiresIn { get; set; }
- }
- internal class MessageResult
- {
- [JsonPropertyName("errcode")]
- public int ErrorCode { get; set; }
- [JsonPropertyName("errmsg")]
- public string ErrorMsg { get; set; } = string.Empty;
- }
- private readonly static HttpClient _client;
- static DingTalk()
- {
- _client = new HttpClient();
- }
- public static async Task SendMessageAsync(string msg)
- {
- var response = await _client.GetAsync("https://oapi.dingtalk.com/gettoken?appkey=dinglvrfy5p9zq79ojaj&appsecret=7Tcy-xRj8m3jVM9cNZo62XlbFaxfONgRE0LKImUrka4DgEOt16RN9TJh9cZR63Vl");
- var contentStream = await response.Content.ReadAsStreamAsync();
- var tokenResult = System.Text.Json.JsonSerializer.Deserialize<AcceccTokenResult>(contentStream);
- if (tokenResult != null)
- {
- if (tokenResult.ErrorCode == 0)
- {
- var text = new Dictionary<string, object>();
- text["content"] = "[" + DateTime.Now.ToString() + "]" + msg;
- var message = new Dictionary<string, object>();
- message["msgtype"] = "text";
- message["text"] = text;
- var args = new Dictionary<string, object>();
- args["agent_id"] = "1485668405";
- args["userid_list"] = "1403411622464238794";
- args["msg"] = message;
- await using (var ms = new MemoryStream())
- {
- await System.Text.Json.JsonSerializer.SerializeAsync(ms, args);
- var data = ms.ToArray();
- var str = Encoding.UTF8.GetString(data);
- var content = new StringContent(str, Encoding.UTF8);
- var url = "https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2?access_token=" + tokenResult.AccessToken;
- response = await _client.PostAsync(url, content);
- contentStream = await response.Content.ReadAsStreamAsync();
- var messageResult = System.Text.Json.JsonSerializer.Deserialize<MessageResult>(contentStream);
- if(messageResult != null)
- {
- if(messageResult.ErrorCode != 0)
- {
- throw new InvalidOperationException(messageResult.ErrorMsg);
- }
- }
- }
- }
- else
- {
- throw new InvalidOperationException(tokenResult.ErrorMsg);
- }
- }
- }
- }
- }
|