Building a small assistant of nCoV epidemic monitoring based on wechat of Serverless enterprise

Recently, some epidemic information is very worrying. In order to facilitate everyone to master the epidemic information, I made a small assistant about nCoV epidemic monitoring in my spare time. The main function is to push epidemic information through the WebHook of enterprise wechat. Here we will share the overall code idea and architecture of Serverless. Author: tabor

Realization effect

The general effect we want to achieve is as follows:

First of all, we need to solve the problem of data source. Here we can use python crawler to do this, but because individuals are lazy, we use it directly 2019-nCoV-Crawler , this project has integrated the existing API, so we can call it directly. Of course, students with ability can also deploy Python by themselves. I deployed Python by myself, but this is not the focus of this time. I won't go into details.

Now, we have data, but how can the data reach the server? How to trigger? Of course, CVM can also be used, but it seems to be too clumsy and consumes a lot, so you need to build all the environments yourself. Therefore, we choose Serverless mode to deploy.

Core logic

Let's take a look at the code part of the whole business. After all, this is the core of the whole robot. Let's look at the code (requesting three interfaces):

<?php
function main_handler($event, $context) {
// Guangdong Province
$curlsz = curl_init();
curl_setopt_array($curlsz, array(
  CURLOPT_URL => "https://Lab.isaaclin.cn/ncov/api/area? Latest = 0 & Province = Guangdong Province ",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 3000,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "GET",
  CURLOPT_HTTPHEADER => array(
    "Accept: */*",
    "Cache-Control: no-cache",
    "Connection: keep-alive",
    "Host: lab.isaaclin.cn",
    "Postman-Token: 680e5ea7-5c2e-4fb6-9295-7e336f2252c6,abd73e01-2a60-42b5-9bbe-92aa83805a7e",
    "User-Agent: PostmanRuntime/7.15.0",
    "accept-encoding: gzip, deflate",
    "cache-control: no-cache"
  ),
));

$responsesz = curl_exec($curlsz);
$echo_responsesz = json_decode($responsesz, true);
$err = curl_error($curlsz);
curl_close($curlsz);

// Situation of Hubei Province
$curlhb = curl_init();
curl_setopt_array($curlhb, array(
  CURLOPT_URL => "https://lab.isaaclin.cn/nCoV/api/area?latest=0&province=Hubei Province,
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 3000,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "GET",
  CURLOPT_HTTPHEADER => array(
    "Accept: */*",
    "Cache-Control: no-cache",
    "Connection: keep-alive",
    "Host: lab.isaaclin.cn",
    "Postman-Token: 680e5ea7-5c2e-4fb6-9295-7e336f2252c6,abd73e01-2a60-42b5-9bbe-92aa83805a7e",
    "User-Agent: PostmanRuntime/7.15.0",
    "accept-encoding: gzip, deflate",
    "cache-control: no-cache"
  ),
));

$responsehb = curl_exec($curlhb);
$echo_responsehb = json_decode($responsehb, true);
$err = curl_error($curlhb);
curl_close($curlhb);

// General situation of the country
$curlall = curl_init();
curl_setopt_array($curlall, array(
  CURLOPT_URL => "https://lab.isaaclin.cn/nCoV/api/overall",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 3000,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "GET",
  CURLOPT_HTTPHEADER => array(
    "Accept: */*",
    "Cache-Control: no-cache",
    "Connection: keep-alive",
    "Host: lab.isaaclin.cn",
    "Postman-Token: 680e5ea7-5c2e-4fb6-9295-7e336f2252c6,abd73e01-2a60-42b5-9bbe-92aa83805a7e",
    "User-Agent: PostmanRuntime/7.15.0",
    "accept-encoding: gzip, deflate",
    "cache-control: no-cache"
  ),
));

$responseall = curl_exec($curlall);
$echo_responseall = json_decode($responseall, true);
$err = curl_error($curlall);
curl_close($curlall);

//Judge whether it is Shenzhen area (the logic here is relatively simple, but enough)
if ($echo_responsesz['results'][0]['cities'][0]['cityName'] == 'Shenzhen') {
  $echo_responseszqz = $echo_responsesz['results'][0]['cities'][0]['confirmedCount'];
  $echo_responseszys = $echo_responsesz['results'][0]['cities'][0]['suspectedCount'];
  $echo_responseszzy = $echo_responsesz['results'][0]['cities'][0]['curedCount'];
  $echo_responseszsw = $echo_responsesz['results'][0]['cities'][0]['deadCount'];
} else {
  $echo_responseszqz = $echo_responsesz['results'][0]['cities'][1]['confirmedCount'];
  $echo_responseszys = $echo_responsesz['results'][0]['cities'][1]['suspectedCount'];
  $echo_responseszzy = $echo_responsesz['results'][0]['cities'][1]['curedCount'];
  $echo_responseszsw = $echo_responsesz['results'][0]['cities'][1]['deadCount'];
}

if ($err) {
  echo "cURL Error #:" . $err;
} else {
//Epidemic monitoring and warning robot
$sc = $sc=" **2019-nCoV Synchronization of epidemic information:** \n
> Nationwide epidemic: 
> Confirmed number<font color=\"info\">".$echo_responseall['results'][0]['confirmedCount']."</font>,Number of suspected infections<font color=\"info\">".$echo_responseall['results'][0]['suspectedCount']."</font>,Cure number<font color=\"info\">".$echo_responseall['results'][0]['curedCount']."</font>,death toll<font color=\"info\">".$echo_responseall['results'][0]['deadCount']."</font>\n
> Guangdong Province: 
> Confirmed number<font color=\"info\">".$echo_responsesz['results'][0]['confirmedCount']."</font>,Number of suspected infections<font color=\"info\">".$echo_responsesz['results'][0]['suspectedCount']."</font>,Cure number<font color=\"info\">".$echo_responsesz['results'][0]['curedCount']."</font>,death toll<font color=\"info\">".$echo_responsesz['results'][0]['deadCount']."</font>\n
> Hubei province: 
> Confirmed number<font color=\"info\">".$echo_responsehb['results'][0]['confirmedCount']."</font>,Number of suspected infections<font color=\"info\">".$echo_responsehb['results'][0]['suspectedCount']."</font>,Cure number<font color=\"info\">".$echo_responsehb['results'][0]['curedCount']."</font>,death toll<font color=\"info\">".$echo_responsehb['results'][0]['deadCount']."</font>\n
> Shenzhen City: 
> Confirmed number<font color=\"info\">".$echo_responseszqz."</font>,Number of suspected infections<font color=\"info\">".$echo_responseszys."</font>,Cure number<font color=\"info\">".$echo_responseszzy."</font>,death toll<font color=\"info\">".$echo_responseszsw."</font>\n

> <font color=\"info\">".$echo_responseall['results'][0]['note1']."</font>
> <font color=\"info\">".$echo_responseall['results'][0]['note2']."</font>
> <font color=\"info\">".$echo_responseall['results'][0]['note3']."</font>
> <font color=\"info\">".$echo_responseall['results'][0]['remark1']."</font>
> <font color=\"info\">".$echo_responseall['results'][0]['remark2']."</font>
> <font color=\"info\"> Information provenance:".$echo_responseall['results'][0]['generalRemark']."</font> \n
>[More data](https://news.qq.com/zt2020/page/feiyan.htm) \n
";
$post = array('msgtype' => 'markdown', 'markdown' => array('content' => $sc));
$curl = curl_init();
curl_setopt_array($curl, array(
  CURLOPT_URL => "https://Qyapi. Weixin. QQ. COM / CGI bin / webhook / send? Key = ", / / the address here is filled in as the HOOK path of enterprise wechat, https://work.weixin.qq.com/api/doc/90000/90136/91770
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 10,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "POST",
  CURLOPT_POSTFIELDS => json_encode($post,JSON_UNESCAPED_UNICODE),
  CURLOPT_HTTPHEADER => array(
    "Cache-Control: no-cache",
    "Postman-Token: ab32082b-ce64-4832-b51f-8f2f1b3e98ef"
  ),
));

$response = curl_exec($curl);
$err = curl_error($curl);

curl_close($curl);

return "Successful operation"; 
}

}

?>

Isn't it simple? Request data, send data.

So we will focus on how to upload our business code to the cloud? The cloud here is Tencent cloud Serverless service SCF cloud function . The whole deployment and use process are free. For developers, the free quota is sufficient for small projects. There is no need to worry about extra charges.

For the Serverless deployment, the popular Serverless Framework is selected, and the use and deployment are completely free. Then I will introduce the specific deployment process.

Installing the Serverless framework

First, let's install a development framework of Serverless Framework:

$ npm install -g serverless

Then, we create a function Directory:

$ mkdir nCov-function
$ cd nCov-function

The contents of the related function directory are as follows:

|- code
  |- index.php  // This is where the business code is stored
|- serverless.yml //serverless profile

Configure Yml file

Next, we will focus on configuring the function yml file:

# serverless.yml
myFunction:
  component: "@serverless/tencent-scf"  //Reference Tencent SCF component
  inputs:
    name: nCoVFunction   //Function name
    enableRoleAuth: true
    codeUri: ./code  //Code local storage location
    handler: index.main_handler
    runtime: Php5
    region: ap-shanghai //Function operation region
    description: My Serverless nCoV Function.
    memorySize: 128  //Running memory
    timeout: 20  //Timeout time
    exclude:
      - .gitignore
      - .git/**
      - node_modules/**
      - .serverless
      - .env
    include:
      - ./nCoVFunction.zip
    environment:
      variables:
        TEST: vale
    vpcConfig:
      subnetId: ''
      vpcId: ''
    events:
      - timer:  // Timing trigger
          name: timer
          parameters:
            cronExpression: '0 0 10,21 * * * *'  //Tomorrow at 10 a.m. and 21 p.m
            enable: true

With everything in place, we can deploy SLS directly.

Deploy to cloud

The sls command (short for serverless) is used for deployment, and the – debug parameter can be added to view the information during deployment:

taborchen$ sls --debug

  DEBUG ─ Resolving the template's static variables.
  DEBUG ─ Collecting components from the template.
  DEBUG ─ Downloading any NPM components found in the template.
  DEBUG ─ Analyzing the template's components dependencies.
  DEBUG ─ Creating the template's components graph.
  DEBUG ─ Syncing template state.
  DEBUG ─ Executing the template's components graph.
  DEBUG ─ Compressing function nCoVFunction file to /Users/taborchen/Desktop/work/yiqing/.ser
verless/nCoVFunction.zip.
  DEBUG ─ Compressed function nCoVFunction file successful
  DEBUG ─ Uploading service package to cos[sls-cloudfunction-ap-shanghai-code]. sls-cloudfunc
tion-default-nCoVFunction-1580960644.zip
  DEBUG ─ Uploaded package successful /Users/taborchen/Desktop/work/yiqing/.serverless/nCoVFu
nction.zip
  DEBUG ─ Creating function nCoVFunction
  DEBUG ─ Created function nCoVFunction successful
  DEBUG ─ Setting tags for function nCoVFunction
  DEBUG ─ Creating trigger for function nCoVFunction
  DEBUG ─ Created timer trigger timer for function nCoVFunction success.
  DEBUG ─ Deployed function nCoVFunction successful

The operation results are as follows:

In this way, we have completed an online trigger function robot of nCoV, isn't it very simple? Come on, let's get started

Portal:

- GitHub: github.com/serverless

- Official Website: serverless.com

Welcome to: Serverless Chinese network , you can Best practices Experience more about Serverless application development!

Recommended reading: Serverless architecture: from principle, design to project implementation

Published 60 original articles, won praise 37, visited 10000+
Private letter follow

Tags: curl Python encoding PHP

Posted on Sun, 09 Feb 2020 21:36:18 -0800 by 23style