钉钉的每个群都可以建若干个机器人,有默认的比如github,也可以自定义。我们使用自定义,建立自己的机器人,然后得到一串的URL,只要向这个URL进行POST请求后,就能将消息通知到对应的群中。机器人的创建可以参照。
发送通知的代码如下
private string WEB_HOOK = "https://oapi.dingtalk.com/robot/send?access_token=XXXXX"; private void buttonTest_Click(object sender, EventArgs e) { try { string msg = textBox1.Text; String textMsg = "{ \"msgtype\": \"text\", \"text\": {\"content\": \"" + msg + "\"}}"; string s = Post(WEB_HOOK, textMsg, null); MessageBox.Show(s); } catch (Exception ex) { MessageBox.Show(ex.Message); } } #region Post ///通知结果如下图/// 以Post方式提交命令 /// /// 请求的URL /// 请求的json参数 /// 请求头的key-value字典 public static String Post(string apiurl, string jsonString, Dictionaryheaders = null) { WebRequest request = WebRequest.Create(@apiurl); request.Method = "POST"; request.ContentType = "application/json"; if (headers != null) { foreach (var keyValue in headers) { if (keyValue.Key == "Content-Type") { request.ContentType = keyValue.Value; continue; } request.Headers.Add(keyValue.Key, keyValue.Value); } } if (String.IsNullOrEmpty(jsonString)) { request.ContentLength = 0; } else { byte[] bs = Encoding.UTF8.GetBytes(jsonString); request.ContentLength = bs.Length; Stream newStream = request.GetRequestStream(); newStream.Write(bs, 0, bs.Length); newStream.Close(); } WebResponse response = request.GetResponse(); Stream stream = response.GetResponseStream(); Encoding encode = Encoding.UTF8; StreamReader reader = new StreamReader(stream, encode); string resultJson = reader.ReadToEnd(); return resultJson; } #endregion
其他消息的类型的可以参照官方文档生成数据即可。
欢迎打描左侧二维码打赏。
转载请注明明出处。