接入步骤
获取自定义机器人Webhook
1.选择需要添加机器人的群聊,然后依次单击群设置 > 智能群助手。
2.在机器人管理页面选择自定义机器人,输入机器人名字并选择要发送消息的群,同时可以为机器人设置机器人头像。
3.完成必要的安全设置,勾选我已阅读并同意《自定义机器人服务及免责条款》,然后单击完成。这里有三种加密方式,
常用的一般都是使用加密方式,其他两种方式比较简单,这里不错特殊介绍
3.完成安全设置后,复制出机器人的Webhook地址,可用于向这个群发送消息,格式如下
https://oapi.dingtalk.com/robot/send?access_token=XXXXXX
当前自定义机器人支持以下消息类型,请根据自己的使用场景选择合适的类型,详情参见消息类型及数据格式。
- 文本 (text)
- 链接 (link)
- markdown(markdown)
- ActionCard
- FeedCard
代码
[ApiController]
[Route("[controller]/[Action]")]
public class NoticeController : ControllerBase
{
private readonly IHttpClientFactory _httpClientFactory;
public NoticeController(IHttpClientFactory httpClientFactory)
{
_httpClientFactory = httpClientFactory;
}
[ActionName("DingDing")]
[HttpPost]
public async Task<string> DingDing(DindDingInput input)
{
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
var client = _httpClientFactory.CreateClient("dingding");
if (input.AccessToken.Length == 0 || input.Secret.Length == 0)
{
return "非法请求";
}
// 时间戳精确到毫秒,这里需要注意下
var timestamp = ((DateTime.Now.Ticks - TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)).Ticks) / 10000).ToString();
var stringToSign = timestamp + "\n" + input.Secret;
var sign = EncryptWithSHA256(stringToSign, input.Secret);
// https://oapi.dingtalk.com/robot/send?access_token=XXXXXX×tamp=XXX&sign=XXX
var url = new Uri($"https://oapi.dingtalk.com/robot/send?access_token={input.AccessToken}×tamp={timestamp}&sign={sign}");
client.Timeout = new TimeSpan(0, 0, 10);
var context = new DinDingMessageText()
{
Text = new Text() { Content = input.Text },
AT = new MessageAT()
{
AtMobiles = input.AtMobiles
}
};
var response = await client.PostAsJsonAsync(url, context);
var result = await response.Content.ReadAsStringAsync();
Console.WriteLine(result);
return result;
}
/// <summary>
/// Base64 SHA256
/// </summary>
/// <param name="data">待加密数据</param>
/// <param name="secret">密钥</param>
/// <returns></returns>
public static string EncryptWithSHA256(string data, string secret)
{
secret = secret ?? "";
// 1、string 转换成 utf-8 的byte[]
var encoding = Encoding.UTF8;
byte[] keyByte = encoding.GetBytes(secret);
byte[] dataBytes = encoding.GetBytes(data);
// 2、 HMACSHA256加密
using (var hmac256 = new HMACSHA256(keyByte))
{
byte[] hashData = hmac256.ComputeHash(dataBytes);
// 3、转换成base64
var base64Str = Convert.ToBase64String(hashData);
// 4、urlEncode编码
return System.Web.HttpUtility.UrlEncode(base64Str, Encoding.UTF8);
}
}
}
参考文档
- 钉钉开放文档-自定义机器人接入 https://open.dingtalk.com/document/group/custom-robot-access