[play with cloud function] get through GitHub to enterprise wechat

Time:2022-8-2

Dear, Hello, I’m “front-end Xiaoxin”. I’ve been engaged in front-end development and Android development for a long time, and I’m keen on technology. I’m going farther and farther on the programming road ~


At the internal knowledge sharing meeting of the team on the 18th, my colleagues shared in detail the recent enterprise micro robots for team engineering. The main reason is that there will be a lot of time every day on the way to deal with merge or find colleagues merge. In order to optimize this time, our colleagues use nodejs development services to connect the internally used worker bee platform and enterprise micro platform, so as to automatically send and remind the corresponding colleagues to do code review, When the review is passed, take the initiative to notify the initiator to complete the merger.

What do I want to do?

I wrote an article before[serverless version] enterprise micro cluster robot development, mainly through the regular active pull request to analyze and then notify the enterprise micro robot. This time, I want to use Tencent cloud function to do the server to get through the message notification from GitHub to enterprise micro. This will expand our understanding of cloud function, so let’s do it.
In this case, we need to prepare to create GitHub demonstration project, Tencent cloud function and an enterprise micro robot. When a user initiates, edits or deletes issue, we can notify the managers of the enterprise micro group.

Configure webhooks for the demo project:

The GitHub project in the demo is self created without any requirements. Webhook allows us to send post requests to our pre configured URL interface when a specified event occurs.

  1. Menu location: demo project /settings/webhooks;
  2. Click add webhook to start configuration;
  3. Configuration information includes:

    1. Request the address, which can be configured after the cloud function is created;
    2. Content format: choose the most common JSON data transmission at present;
    3. Security key: configure a random key throughtoolThe generation length is 32 bits, which will be used when the cloud function verifies the data;
    4. Select event: checkLet me select individual events.choiceIssue comments。
  4. Event document: [webhook events and payloads] ()

    Develop cloud functions:

    Create a cloud function:

    This time, in order to save time, we will create cloud functions based on templates. SelectExpress framework template, we specify the function name as GitHub webhook issues comments to distinguish it from its existing functions.

Test service connectivity:

After creation, you can switch to the trigger management menu to see the access path of the service. The default template has created the default page route, /logo route, /user route, /user/: ID route, /404 route and /500 route in advance. We can all access them to try the effect. In addition to keeping the default route to check whether the service is normal, we can consider deleting other routes.
When you open the homepage and see “welcome to the express.js application Tencent cloud serverless provides services for you”, it means that the service has been started normally.

Configure /webhook Routing:

  1. Our scheduled route is/webhook, the way to receive the request isPOST, the received content format isJSONAt this time, we can go to GitHub’s webhook to fill in the information.

  1. Add /webhook routes through the cloud editor. The specific implementation will not be done for the time being. We want to verify connectivity by submitting issues on GitHub.

    app.post(`/webhook`, (req, res) => {
      res.send({code: 200});
    });

    View the request log on GitHub:

    Implement /webhook Routing:

  2. For the convenience of debugging (local), we’d better download the cloud code and write it in the local vscode. After pulling the code, it can be passednodemon ./app.jsStart the service. The default port of the service is9000And it is not allowed to modify in cloud functions, which requires special attention;

  1. Remember the security key we configured for webhook in GitHub? To ensure the security of the data, we need to use the same key in the cloud function to verify the validity of the data(GitHub documentation)。

    app.post(`/webhook`, (req, res) => {
      const signature = req.headers["x-hub-signature-256"];
      if (signature) {
     const payload = req.body;
     const ret = verify(signature, payload);
     //Output verification structure
     console.log("[ ret ] >", ret);
      }
      res.send({ code: 200 });
    });
    const crypto = require("crypto");
    const SECRET_TOKEN = "";
    
    function sign(data) {
      return `sha256=${crypto
     .createHmac("sha256", SECRET_TOKEN)
     .update(JSON.stringify(data))
     .digest("hex")}`;
    }
    
    module.exports = {
      verify: (signature, data) => {
     const sig = Buffer.from(signature);
     const signed = Buffer.from(sign(data));
     if (sig.length !== signed.length) {
       return false;
     }
     return crypto.timingSafeEqual(sig, signed);
      },
    };

    Note 1): because encryption and decryption are rarely done, the 16 bit secret key set at the beginning makes the two encryption results different, which takes a long time. Therefore, it is necessary to set at least 32-bit secret key. XD who knows this can explain it.
    Note 2): the secret key is recommended to be stored in the environment variable of the server, and it is forbidden to store it directly in the code.

  2. By referenceGitHub documentationTo determine the fields that we need to assemble information below, I will not explain the fields if I put the code below. For more field contents, you can query the document:

packaging: (issue, comment, repository, sender) => {
    return `
**There is a new comment * *:\n
    The user [${sender.login}] (${sender.html_url}) added a new comment under the theme of [${issue.title}] (${issue.html_url})], saying [${comment.body}] (${comment.html_url}). Please pay attention to check! \n\n
**Item * *: <font color= "info" > [${repository.name}] (${repository.html_url}) </font>\n
**Comment time * *: <font color= "comment" > ${comment.updated_at}</font>\n
    `;
},
  1. Once again, transform /webhook routing to support sending messages to enterprise and micro robots. Please see the previous article for the configuration and sending of enterprise and micro robots[serverless version] enterprise micro cluster robot development, the source code is lost, and you can leave a message if you need the cloud Code:

    if (verify(signature, payload)) {
      const { action, issue, comment, repository, sender } = payload;
      if (action === "created") {
     const content = packaging(issue, comment, repository, sender);
     notice.requestMDNotice(config.ENTERPRISE_WECHAT_ROBOT_WEB_HOOK, {
       content,
     });
      }
    }

    We can receive the following card information in enterprise wechat:

    Steps to synchronize local code to the cloud:

  2. Select the local code root folder:

  1. Click deploy to start uploading:

  1. Code deployment uploading:

  1. Inconsistency with the current deployment is detected and needs to be republished:

  1. After GitHub creates issue, you can query the correct feedback through the cloud log:

Summary:

We monitor the issue comment event by configuring webhook on GitHub. When the event occurs, we will send the message in a fixed format to the Tencent cloud function we created. After verifying the legitimacy of the data, we will parse the message, assemble the card and forward it to the enterprise robot. In the development, we encountered hmac256 encryption, which is rarely used, and the longest delay is caused by the insufficient length of the secret key. I wonder if the cloud function development in this article is clear?


Welcome to pay attention to my official account “front-end Xiaoxin classmate”, and the original technical articles are pushed at the first time.