Serverless+기업 위 챗 기반 nCoV 전염병 상황 모니터링 조수 만 들 기
12749 단어 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",
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);
//
$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);
// ( , )
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 :**
> :
> <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>
> :
> <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>
> :
> <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>
> :
> <font color=\"info\">".$echo_responseszqz."</font>, <font color=\"info\">".$echo_responseszys."</font>, <font color=\"info\">".$echo_responseszzy."</font>, <font color=\"info\">".$echo_responseszsw."</font>
> <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>
>[ ](https://news.qq.com/zt2020/page/feiyan.htm)
";
$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_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 " ";
}
}
?>
쉽 지 않 아 요?데 이 터 를 요청 하여 데 이 터 를 보 냅 니 다.그렇다면 우 리 는 우리 의 업무 코드 를 클 라 우 드 에 어떻게 올 리 는 지 에 중점 을 두 었 다.
여기 클 라 우 드 는 텐 센트 클 라 우 드 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 명령(server less 의 줄 임 말)을 통 해 배치 하고 Cdebug 인 자 를 추가 하여 배치 과정 에서 의 정 보 를 볼 수 있 습 니 다.
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
실행 결 과 는 다음 과 같 습 니 다.이렇게 해서 우 리 는 nCoV 의 온라인 트리거 함수 로봇 을 완 성 했 습 니 다~간단 하지 않 습 니까?어서 와 서 시작 해~
전송 문:
GitHub: github.com/serverless
홈 페이지
자,여기까지 소개 해 드 리 겠 습 니 다.마음 에 드 셨 으 면 좋 겠 습 니 다!
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
python 은 jenkins 를 사용 하여 기업 의 위 챗 알림 을 보 내 는 실현만약 에 제 인 킨 스 의 구축 결 과 를 기업 위 챗 에 보 내 고 알림 을 하려 면 가장 간편 한 방법 은 설치 플러그 인 입 니 다.인터넷 튜 토리 얼 이 많 으 면 중복 적 으로 쓰 지 않 습 니 다.참고 하...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.