DingTalk.cs 3.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. using System.Text;
  2. using System.Text.Json.Serialization;
  3. namespace StationProbe
  4. {
  5. internal class DingTalk
  6. {
  7. internal class AcceccTokenResult
  8. {
  9. [JsonPropertyName("errcode")]
  10. public int ErrorCode { get; set; }
  11. [JsonPropertyName("errmsg")]
  12. public string ErrorMsg { get; set; } = string.Empty;
  13. [JsonPropertyName("access_token")]
  14. public string AccessToken { get; set; } = string.Empty;
  15. [JsonPropertyName("expires_in")]
  16. public int ExpiresIn { get; set; }
  17. }
  18. internal class MessageResult
  19. {
  20. [JsonPropertyName("errcode")]
  21. public int ErrorCode { get; set; }
  22. [JsonPropertyName("errmsg")]
  23. public string ErrorMsg { get; set; } = string.Empty;
  24. }
  25. private readonly static HttpClient _client;
  26. static DingTalk()
  27. {
  28. _client = new HttpClient();
  29. }
  30. public static async Task SendMessageAsync(string msg)
  31. {
  32. var response = await _client.GetAsync("https://oapi.dingtalk.com/gettoken?appkey=dinglvrfy5p9zq79ojaj&appsecret=7Tcy-xRj8m3jVM9cNZo62XlbFaxfONgRE0LKImUrka4DgEOt16RN9TJh9cZR63Vl");
  33. var contentStream = await response.Content.ReadAsStreamAsync();
  34. var tokenResult = System.Text.Json.JsonSerializer.Deserialize<AcceccTokenResult>(contentStream);
  35. if (tokenResult != null)
  36. {
  37. if (tokenResult.ErrorCode == 0)
  38. {
  39. var text = new Dictionary<string, object>();
  40. text["content"] = "[" + DateTime.Now.ToString() + "]" + msg;
  41. var message = new Dictionary<string, object>();
  42. message["msgtype"] = "text";
  43. message["text"] = text;
  44. var args = new Dictionary<string, object>();
  45. args["agent_id"] = "1485668405";
  46. args["userid_list"] = "1403411622464238794";
  47. args["msg"] = message;
  48. await using (var ms = new MemoryStream())
  49. {
  50. await System.Text.Json.JsonSerializer.SerializeAsync(ms, args);
  51. var data = ms.ToArray();
  52. var str = Encoding.UTF8.GetString(data);
  53. var content = new StringContent(str, Encoding.UTF8);
  54. var url = "https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2?access_token=" + tokenResult.AccessToken;
  55. response = await _client.PostAsync(url, content);
  56. contentStream = await response.Content.ReadAsStreamAsync();
  57. var messageResult = System.Text.Json.JsonSerializer.Deserialize<MessageResult>(contentStream);
  58. if(messageResult != null)
  59. {
  60. if(messageResult.ErrorCode != 0)
  61. {
  62. throw new InvalidOperationException(messageResult.ErrorMsg);
  63. }
  64. }
  65. }
  66. }
  67. else
  68. {
  69. throw new InvalidOperationException(tokenResult.ErrorMsg);
  70. }
  71. }
  72. }
  73. }
  74. }