[C#] 钉钉机器人通知

2022-04-19 14:05:11 浏览数 (1)

操作步骤

  1. 【钉钉桌面客户端】-> 【群设置】-> 【智能群助手】-> 【添加新建机器人-选自定义】-> 【设置机器人名称头像】-> 【注意⚠️设置自定义关键字: TanCloud】 ->【添加成功后复制其WebHook地址】

注意⚠️ 新增机器人时需在安全设置块需设置其自定义关键字: TanCloud ,其它安全设置加签或IP段不填写

  1. 【保存机器人的WebHook地址access_token值】

例如:webHook地址:https://oapi.dingtalk.com/robot/send?access_token=43aac28a236e001285ed84e473f8eabee70f63c7a70287acb0e0f8b65fade64f 其机器人access_token值为 43aac28a236e001285ed84e473f8eabee70f63c7a70287acb0e0f8b65fade64f

  1. 【告警通知】->【新增接收人】 ->【选择钉钉机器人通知方式】->【设置钉钉机器人ACCESS_TOKEN】

消息类型及数据格式

text类型

参数

参数类型

是否必填

说明

msgtype

String

消息类型,此时固定为:text。

content

String

消息内容。

atMobiles

Array

被@人的手机号。注意 在content里添加@人的手机号,且只有在群内的成员才可被@,非群内成员手机号会被脱敏。

atUserIds

Array

被@人的用户userid。注意 在content里添加@人的userid。

isAtAll

Boolean

是否@所有人。

常见问题

当出现以下错误时,表示消息校验未通过,请查看机器人的安全设置。

代码语言:javascript复制
public class DingDing
{
    private
#nullable disable
        HttpClient _Client;

    /// <summary>
    ///     Webhook 地址
    /// </summary>
    public static string WebHookUrl =
        "https://oapi.dingtalk.com/robot/send?access_token=a12ef9c896c75c8cb0327ee4b845d4ccfcfe6c1b46b671c95e50fb5494ed9bd4";


    /// <summary>
    ///     关键字 1
    ///     机器人设置的关键字
    /// </summary>
    private const string keyWord = "【提示】";


    /// <summary>
    ///     缓存 Json
    /// </summary>
    private static readonly StringBuilder jsonStringBuilder = new(512);

    //private static List<string> defaultPhoneNumbers = new List<string>() { };
    /// <summary>
    ///     发送 Post 数据
    /// </summary>
    /// <param name="data">数据</param>
    /// <returns>Json</returns>
    public static string Post(string data)
    {
        var httpWebRequest = (HttpWebRequest)WebRequest.Create(WebHookUrl);
        httpWebRequest.ContentType = "application/json";
        httpWebRequest.Method = WebRequestMethods.Http.Post;
        if (data != null)
        {
            var dataBytes = Encoding.UTF8.GetBytes(data);
            httpWebRequest.ContentLength = dataBytes.Length;
            using (var reqStream = httpWebRequest.GetRequestStream())
            {
                reqStream.Write(dataBytes, 0, dataBytes.Length);
                httpWebRequest.GetRequestStream().Write(dataBytes, 0, dataBytes.Length);
            }
        }

        using (var httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse())
        {
            var responseStream = httpWebResponse.GetResponseStream();
            return responseStream == null ? null : new StreamReader(responseStream, Encoding.UTF8).ReadToEnd();
        }
    }

    /// <summary>
    ///     发送 text 类型
    /// </summary>
    /// <param name="text">内容</param>
    /// <param name="phoneNumbers">@谁?支持多人</param>
    /// <param name="isAtAll">@所有人</param>
    public static void SendText(string text, List<string> phoneNumbers = null, bool isAtAll = false)
    {
        phoneNumbers ??= new List<string>();
        text = "节点["   Environment.MachineName   "] "   text;
        jsonStringBuilder.Clear();
        var listToString = string.Join(",", phoneNumbers);
        jsonStringBuilder.Append(
            $"{{"msgtype":"text","text":{{"content":"{keyWord   text}"}},"at":{{"atMobiles":[{listToString}],"isAtAll":{isAtAll.ToString().ToLower()}}}}}");
        var ReturnJson = Post(jsonStringBuilder.ToString());
        Utils.log.Information("钉钉反馈:{txt}", ReturnJson);
    }
    /// <summary>
    ///     发送 Link 类型
    /// </summary>
    /// <param name="title">标题</param>
    /// <param name="text">内容</param>
    /// <param name="imageUrl">图片链接</param>
    /// <param name="contentUrl">消息跳转链接</param>
    public static void SendLink(string title, string text, string imageUrl = "http://www.whhbzdh.cn/img/bhb.png",
        string contentUrl =
            "https://mp.weixin.qq.com/s?__biz=MzUwOTk5ODYzOA==&mid=2247508593&idx=2&sn=39e21b35ef7e7971d39da65b866aadb4&chksm=f90b4130ce7cc8265906bc88576c6ba4ebadeaf68edda446f263d133cf8e28090acc50f3364f&token=1727274237&lang=zh_CN#rd")
    {
        text = "节点["   Environment.MachineName   "] "   text;

        jsonStringBuilder.Clear();
        jsonStringBuilder.Append("{"msgtype":"link","link":{"  
                                 $""title":"{keyWord   title}","  
                                 $""text":"{text}","  
                                 $""picUrl":"{imageUrl}","  
                                 $""messageUrl":"{contentUrl}"}}}}");
        var ReturnJson = Post(jsonStringBuilder.ToString());
        Utils.log.Information("钉钉反馈:{txt}", ReturnJson);
    }
    /// <summary>
    ///     发送markdown类消息
    /// </summary>
    /// <param name="title">标题</param>
    /// <param name="text">消息主体</param>
    /// <param name="atMobiles">@人员电话</param>
    /// <param name="isAtAll">是否@群所有成员</param>
    /// <param name="imageUrl"></param>
    public static void SendMarkdown(string title, string text, string imageUrl, List<string> phoneNumbers = null,
        bool isAtAll = false)
    {
        text = "节点["   Environment.MachineName   "] "   text;
        phoneNumbers ??= new List<string>();

        var listToString = string.Join(",", phoneNumbers);
        jsonStringBuilder.Clear();
        jsonStringBuilder.Append($"{{"msgtype":"markdown",""  
                                 $"markdown":{{"title":"{keyWord   title}","  
                                 $""text":"{text} "  
                                 $"![screenshot]({imageUrl})\n> [whhb](http://www.whhbzdh.cn/) \n"}},"  
                                 $""at":{{"atMobiles":["{listToString}"],"  
                                 $""isAtAll":{isAtAll.ToString().ToLower()}}}}}");
        var ReturnJson = Post(jsonStringBuilder.ToString());
        Utils.log.Information("钉钉反馈:{txt}", ReturnJson);
    }
    /// <summary>
    ///     整体发送ActionCard类型消息
    /// </summary>
    /// <param name="title">标题</param>
    /// <param name="imageUrl">图片Url</param>
    /// <param name="texttitle">文本标题</param>
    /// <param name="text">文本</param>
    /// <param name="btnTitle">按钮标题</param>
    /// <param name="buttonUrl">按钮Url</param>
    /// <param name="btnOrientation">按钮排列   0-按钮竖直排列,1-按钮横向排列</param>
    public static void SendActionCard(string title, string imageUrl, string texttitle, string text, string btnTitle,
        string buttonUrl, string btnOrientation)
    {
        text = "节点["   Environment.MachineName   "] "   text;

        jsonStringBuilder.Clear();
        jsonStringBuilder.Append($"{{"actionCard":{{"title":"{keyWord   title}","  
                                 $""text":"![screenshot]({imageUrl}) \r\n ### {texttitle} \r\n {text}","  
                                 $""btnOrientation":"{btnOrientation}","  
                                 $""singleTitle":"{btnTitle}","  
                                 $""singleURL":"{buttonUrl}"}},"  
                                 $""msgtype":"actionCard"}}");
        var ReturnJson = Post(jsonStringBuilder.ToString());
        Utils.log.Information("钉钉反馈:{txt}", ReturnJson);
    }
    /// <summary>
    ///     独立发送 ActionCard类型消息
    /// </summary>
    /// <param name="title">标题</param>
    /// <param name="imageUrl">图片Url</param>
    /// <param name="texttitle">文本标题</param>
    /// <param name="text">文本</param>
    /// <param name="buttonUrl1">按钮1Url</param>
    /// <param name="buttonUrl2">按钮2Url</param>
    /// <param name="singleURL1">按钮1访问Url</param>
    /// <param name="singleURL2">按钮2访问Url</param>
    /// <param name="btnOrientation"></param>
    public static void SendActionCard(string title, string imageUrl, string texttitle, string text, string buttonUrl1,
        string buttonUrl2, string singleURL1, string singleURL2, string btnOrientation)
    {
        text = "节点["   Environment.MachineName   "] "   text;

        jsonStringBuilder.Clear();
        jsonStringBuilder.Append($"{{"actionCard":{{"title":"{keyWord   title}","  
                                 $""text":"![screenshot]({imageUrl}) \r\n ### {texttitle} \r\n {text}","  
                                 $""btnOrientation":"{btnOrientation}","  
                                 $""btns":[{{"title":"{buttonUrl1}","  
                                 $""actionURL":"{singleURL1}"}},"  
                                 $"{{"title":"{buttonUrl2}","  
                                 $""actionURL":"{singleURL2}"}}]}},"  
                                 $""msgtype":"actionCard"}}");
        var ReturnJson = Post(jsonStringBuilder.ToString());
        Utils.log.Information("钉钉反馈:{txt}", ReturnJson);
    }
    /// <summary>
    ///     发送 FeedCard类型消息
    /// </summary>
    /// <param name="title1">标题 单条信息文本</param>
    /// <param name="messageUrl1">点击单条信息到跳转链接</param>
    /// <param name="imageUrl1">单条信息后面图片的URL</param>
    /// <param name="title2"></param>
    /// <param name="messageUrl2"></param>
    /// <param name="imageUrl2"></param>
    public static void SendFeedCard(string title1, string messageUrl1, string imageUrl1, string title2,
        string messageUrl2, string imageUrl2)
    {
        jsonStringBuilder.Clear();
        jsonStringBuilder.Append($"{{"feedCard":{{"links":[{{"title":"{keyWord   title1}","  
                                 $""messageURL":"{messageUrl1}","  
                                 $""picURL":"{imageUrl1}"}},"  
                                 $"{{"title":"{title2}","  
                                 $""messageURL":"{messageUrl2}","  
                                 $""picURL":"{imageUrl2}"}}]}},"  
                                 $""msgtype":"feedCard"}}");
        var ReturnJson = Post(jsonStringBuilder.ToString());
    }
}

0 人点赞