1. 程式人生 > 程式設計 >基於 Serverless +企業微信打造 nCoV 疫情監控小助手

基於 Serverless +企業微信打造 nCoV 疫情監控小助手

最近的一些疫情資訊很讓人揪心,為了方便大家掌握疫情資訊,在空閒之餘做了一個關於 nCoV 的疫情監控小助手。主要的功能是通過企業微信的 WebHook 來推送疫情資訊。這裡將使用 Serverless 的整體程式碼思路和架構方式分享給大家。本文作者:tabor

實現效果

我們想要實現的大致的效果是這樣的:

基於 Serverless +企業微信打造 nCoV 疫情監控小助手

首先,我們需要解決的是資料來源問題,這裡我們可以使用 python 爬蟲來做這件事情,但是由於個人比較懶所以直接用的 2019-nCoV-Crawler ,這個專案已經集成了現有的 API,所以我們直接呼叫即可。當然有能力的同學也可以自己部署 Python,我這邊是自己部署的,但是這不是本次的重點,就不在贅述。

現在,我們有了資料,但是資料怎麼打到伺服器呢?又該如何觸發?當然使用 CVM 也是可以的,但是似乎太笨拙,並且消耗量很大,需要自己搭好所有環境。所以,這裡我們選用 Serverless 方式來部署。

核心邏輯

我們來看看整體業務的程式碼部分吧,畢竟這裡是整個機器人的核心。我們來看程式碼(請求三次介面):

<?php
function main_handler($event,$context) {
// 廣東省情況
$curlsz = curl_init();
curl_setopt_array($curlsz,array(
 CURLOPT_URL => "https://lab.isaaclin.cn/nCoV/api/area?latest=0&province=%E5%B9%BF%E4%B8%9C%E7%9C%81",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);
// 湖北省情況
$curlhb = curl_init();
curl_setopt_array($curlhb,array(
 CURLOPT_URL => "https://lab.isaaclin.cn/nCoV/api/area?latest=0&province=%E6%B9%96%E5%8C%97%E7%9C%81",));
$responsehb = curl_exec($curlhb);
$echo_responsehb = json_decode($responsehb,true);
$err = curl_error($curlhb);
curl_close($curlhb);
// 全國總體情況
$curlall = curl_init();
curl_setopt_array($curlall,array(
 CURLOPT_URL => "https://lab.isaaclin.cn/nCoV/api/overall",));
$responseall = curl_exec($curlall);
$echo_responseall = json_decode($responseall,true);
$err = curl_error($curlall);
curl_close($curlall);
//判斷是否為深圳地域(這裡邏輯寫的比較簡單,但是夠用了)
if ($echo_responsesz['results'][0]['cities'][0]['cityName'] == '深圳') {
 $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 {
//疫情監控告警機器人
$sc = $sc=" **2019-nCoV 疫情資訊同步:** \n
> 全國疫情: 
> 確診人數<font color=\"info\">".$echo_responseall['results'][0]['confirmedCount']."</font>,疑似感染人數<font color=\"info\">".$echo_responseall['results'][0]['suspectedCount']."</font>,治癒人數<font color=\"info\">".$echo_responseall['results'][0]['curedCount']."</font>,死亡人數<font color=\"info\">".$echo_responseall['results'][0]['deadCount']."</font>\n
> 廣東省: 
> 確診人數<font color=\"info\">".$echo_responsesz['results'][0]['confirmedCount']."</font>,疑似感染人數<font color=\"info\">".$echo_responsesz['results'][0]['suspectedCount']."</font>,治癒人數<font color=\"info\">".$echo_responsesz['results'][0]['curedCount']."</font>,死亡人數<font color=\"info\">".$echo_responsesz['results'][0]['deadCount']."</font>\n
> 湖北省: 
> 確診人數<font color=\"info\">".$echo_responsehb['results'][0]['confirmedCount']."</font>,疑似感染人數<font color=\"info\">".$echo_responsehb['results'][0]['suspectedCount']."</font>,治癒人數<font color=\"info\">".$echo_responsehb['results'][0]['curedCount']."</font>,死亡人數<font color=\"info\">".$echo_responsehb['results'][0]['deadCount']."</font>\n
> 深圳市: 
> 確診人數<font color=\"info\">".$echo_responseszqz."</font>,疑似感染人數<font color=\"info\">".$echo_responseszys."</font>,治癒人數<font color=\"info\">".$echo_responseszzy."</font>,死亡人數<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\"> 資訊出處:".$echo_responseall['results'][0]['generalRemark']."</font> \n
>[更多資料請檢視](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=",//這裡的地址填寫為企業微信的HOOK路徑,https://work.weixin.qq.com/api/doc/90000/90136/91770
 CURLOPT_RETURNTRANSFER => true,CURLOPT_TIMEOUT => 10,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 "執行成功"; 
}
}
?>

是不是很簡單呢?請求資料,傳送資料。

那麼我們接下了重點看下如何將我們的業務程式碼上傳到雲端呢?
這裡的雲端我用的是騰訊雲 Serverless 服務 SCF雲函式 。整個部署,使用過程都是免費的,對於開發者來講小專案使用的話免費額度是完全夠用的。無需擔心額外付費。

Serverless 部署,選用的是比較流行的 Serverless Framework,使用和部署也是完全免費的,那麼下面我就來介紹下具體的部署過程吧。

安裝 Serverless 框架

首先,第一步,我們來安裝一個 Serverless Framework 的開發框架:

$ npm install -g serverless

然後,我們建立一個函式目錄:

$ mkdir nCov-function
$ cd nCov-function

相關函式目錄的內容如下:

|- code
 |- index.php // 這裡就是上面的業務程式碼存放位置
|- serverless.yml //serverless 配置檔案

配置 Yml 檔案

接下來,是我們的重頭戲,配置函式 yml 檔案:

# serverless.yml
myFunction:
 component: "@serverless/tencent-scf" //引用tencent-scf component
 inputs:
 name: nCoVFunction //函式名稱
 enableRoleAuth: true
 codeUri: ./code //程式碼本地存放位置
 handler: index.main_handler
 runtime: Php5
 region: ap-shanghai //函式執行地域
 description: My Serverless nCoV Function.
 memorySize: 128 //執行記憶體
 timeout: 20 //超時時間
 exclude:
 - .gitignore
 - .git/**
 - node_modules/**
 - .serverless
 - .env
 include:
 - ./nCoVFunction.zip
 environment:
 variables:
 TEST: vale
 vpcConfig:
 subnetId: ''
 vpcId: ''
 events:
 - timer: // 定時觸發器
  name: timer
  parameters:
  cronExpression: '0 0 10,21 * * * *' //明天早上10點,晚上21點
  enable: true

萬事具備,我們就可以直接部署 SLS 了。

部署到雲端

通過 sls 命令(serverless 的縮寫)進行部署,並可以新增 –debug 引數檢視部署過程中的資訊:

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/工作/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/工作/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

執行結果如下:

基於 Serverless +企業微信打造 nCoV 疫情監控小助手

這樣,我們就完成了一個 nCoV 的線上觸發函式機器人~是不是很簡單呢?快來開始動手吧~

傳送門:

GitHub: github.com/serverless

官網:serverless.com

好了,就給大家介紹到這來,希望大家喜歡!