Complete step record of Asp.Net Core docking pin swarm robots

Time:2019-9-28

Preface

As a software used more and more frequently in enterprise office, nails provide interface support for enterprise internal self-research system to get through data under multi-platform. This time, the simplest nail swarm robots are used to complete various forms of message pushing. Referring to the custom robot link in nail development documents, this attempt spent. There is not much time, but there are several points to be noted.

  

1. Building Robots in Nail Cluster to Get Web Hook Addresses

First, you have to have a group of nails. If you don’t have to create a group of nails, you can find the group robot in the top right-hand menu of the group and add a custom robot.

  

And set the message push open (default is open), copy the webhook address of the next line, which will be the address of the message push later.

  

If you’re not sure if the address is valid, you can test it with commands, such as replacing your webhook_token with this command on the Linux platform.

curl 'https://oapi.dingtalk.com/robot/send?access_token=cd1eb120c459ced6a65491af7b1eebbc84790fb672077a969bae8bb203aa1c52' \
 -H 'Content-Type: application/json' \
 -d '
 {"msgtype": "text", 
 "text": {
  "Content": "I'm me, it's different fireworks."
  }
 }'

Then the train returns for testing and receives the message from the swarm robots immediately.

2. Reference document completes encapsulation of basic classes and processes related fields

Next, we can complete the call to WebHook address in the code. We can analyze the document of swarm robots first. We can learn that there are five message types: text, link, markdown, ActionCard and FeedCard. ActionCard can be divided into two categories: whole and independent. According to these types and the given parameters, the design and encapsulation of basic classes are completed. Take text type as an example:

Among them, msgtype is a string of five message types, so an enumeration is designed for this part to distinguish message types.

/// <summary>
/// Enumeration of message types for nail swarm robots
/// </summary>
public enum MsgTypeEnum
{
 text,
 link,
 markdown,
 actionCard,
 feedCard
}

Designing a text class and giving a property Content, we like to use Pascal nomenclature at design time, but nail interface is not allowed. If we don’t do some processing, using Content attribute directly will call incompetent interface, which needs to be noticed. When packaging into JSON using Newton json, we replace it with the specified name. To meet the nail interface requirements.

/// <summary>
/// Text type
/// </summary>
public class Text
{
 /// <summary>
 /// Text content
 /// </summary>
 [JsonProperty(PropertyName = "content")]
 public string Content { get; set; }
}

Secondly, a class encapsulation is made for the designated population, and the replacement names of the attributes in the encapsulation need to be processed as well.

/// <summary>
///@ Designator
/// </summary>
public class At
{
 /// <summary>
 ///@ Contacts
 /// </summary>
 [JsonProperty(PropertyName = "atMobiles")]
 public List<string> AtMobiles { set; get; }

 /// <summary>
 /// Whether @everyone
 /// </summary>
 [JsonProperty(PropertyName = "isAtAll")]
 public bool IsAtAll { set; get; }
}

Through the analysis of five message types, some of the parameters can be shared. After a series of mining of custom nail robot documents, these classes and enumerations are determined.

Next you can call the robot and push it to the nail group using different message types.

3. Complete the call of nail swarm robots

First, complete the injection of HttpClientFactory in the ConfigureService method

This time, the robot is directly invoked under Asp.Net Core WebApi, a new controller of DingTalk is built, and then the injection of IHttpClientFactory is completed. Then the next service invocation is started. For the storage of pinned WebHook_Token, you can choose the configuration file or if you just try, you can use one directly. Variables can be saved.

/// <summary>
/// Sending pin message interface
/// </summary>
[Route("api/[controller]")]
[ApiController]
public class DingTalkController : ControllerBase
{
 private readonly string WebHook_Token = "https://oapi.dingtalk.com/robot/send?access_token=cd1eb120c459ced6a65491af7b1eebbc84790fb672077a969bae8bb203aa1c52";

 private readonly IHttpClientFactory _httpClientFactory;

 public DingTalkController(IHttpClientFactory httpClientFactory)
 {
  _httpClientFactory = httpClientFactory;
 }
}

Taking text text text as an example and completing the push of text message, an action is established to send text message, in which the assembly of parameters required for nail interface is completed, and eventually the message push is completed by using a unified sending method.

/// <summary>
/// Call the Nail Robot to Send Text Content
/// </summary>
/// <returns></returns>
[HttpGet]
[Route(nameof(TextContent))]
public async Task<ActionResult> TextContent()
{
 // Message type
 var msgtype = MsgTypeEnum.text.ToString();

 // Text content
 var text = new Text
 {
  Content = "Look at Wanshan red, layers of trees are dyed; the river is green, the rivers are green, and the rivers are in contention with each other @15675120617"
 };

 // Designated target population
 var at = new At()
 {
  AtMobiles = new List<string>() { "15675120617" },
  IsAtAll = false
 };

 var response = await SendDingTalkMessage(new { msgtype, text, at });

 return Ok(response);
}

For sending methods that need to be designed according to some requirements of nailed documents, such as documents specifying the need to submit requests using Post and using UTF8 encoding, I directly created a new method in the controller (although not reasonable), first serialized and encapsulated the content, and then created a new client through HttpClientFactory and finished it. To send a message.

/// <summary>
/// Execute send message
/// </summary>
/// <param name="sendMessage"></param>
/// <returns></returns>
private async Task<HttpResponseMessage> SendDingTalkMessage(object value)
{
 var sendMessage = JsonConvert.SerializeObject(value);

 var request = new HttpRequestMessage(HttpMethod.Post, WebHook_Token)
 {
  // Nail documents need to specify UTF8 encoding
  Content = new StringContent(sendMessage, Encoding.UTF8, "application/json")
 };

 var client = _httpClientFactory.CreateClient();
 var response = await client.SendAsync(request);

 return response;
}

Start the program and complete the message push through the URL access controller. Note that the naming method of each attribute or the naming method after the conversion of features needs to satisfy the nail interface document (the two parameters after the FeedCard type in the document are not standard).

Warehouse address: https://gitee.com/530521314/koInstance/tree/master/src/koInstance.WebApi

summary

Above is the whole content of this article. I hope that the content of this article has a certain reference value for everyone’s study or work. If you have any questions, you can leave a message and exchange it. Thank you for your support to developpaer.

Recommended Today

The method of obtaining the resolution of display by pyqt5

The code is as follows import sys from PyQt5.QtWidgets import QApplication, QWidget class Example(QWidget): def __init__(self): super().__init__() self.initUI() #Interface drawing to initui method def initUI(self): self.desktop = QApplication.desktop() #Get display resolution size self.screenRect = self.desktop.screenGeometry() self.height = self.screenRect.height() self.width = self.screenRect.width() print(self.height) print(self.width) #Show window self.show() if __name__ == ‘__main__’: #Create applications and objects app […]