From enterprise wechat robot to Xiaoai classmate, use Serverless to realize life intelligence!

Keywords: JSON curl SHA1 network

Through timing trigger, an enterprise wechat robot can be customized simply and quickly. We can use it to realize small functions such as drinking water, eating reminder, etc., and also to push news, weather and even monitor alarm regularly.

Use enterprise wechat robot

In enterprise wechat, select Add robot:

After that, we can customize the basic functions of the enterprise wechat robot according to the documents:

The following is an example of using curl tool to push text messages to groups (note that to replace url with webhook address of robot, content must be utf8 encoding):

curl 'Enterprise wechat robot address' 
   -H 'Content-Type: application/json' 
   -d '
   {
        "msgtype": "text",
        "text": {
            "content": "hello world"
        }
   }'

Implemented in Python language:

url = ""
data = {
    "msgtype": "markdown",
    "markdown": {
        "content": "hello world",
    }
}
data = json.dumps(data).encode("utf-8")
req_attr = urllib.request.Request(url, data)
resp_attr = urllib.request.urlopen(req_attr)
return_msg = resp_attr.read().decode("utf-8")

At this point, we can deploy the basic functions of a robot through the Serverless Framework, and set the API gateway trigger:

index.py The documents are as follows:

import os
import json
import urllib.request

def main_handler(event, context):
    url = os.environ.get("url")
    data = {
        "msgtype": "markdown",
        "markdown": {
            "content": "hello world",
        }
    }
    data = json.dumps(data).encode("utf-8")
    req_attr = urllib.request.Request(url, data)
    resp_attr = urllib.request.urlopen(req_attr)
    return resp_attr.read().decode("utf-8")

serverless.yaml The documents are as follows:

MyRobot_Base:
  component: '@serverless/tencent-scf'
  inputs:
    name: MyRobot_Base
    runtime: Python3.6
    timeout: 3
    codeUri: ./base_robot
    description: Robot push interface
    region: ap-guangzhou
    environment:
      variables:
        url: webhook address
    handler: index.main_handler
    memorySize: 64
    tags:
      app: myrobot
    events:
      - apigw:
          name: MyRobot
          parameters:
            protocols:
              - http
              - https
            description: Robot push interface
            environment: release
            endpoints:
              - path: /push
                method: ANY

After the deployment is successful, you can see the output address in the command line:

Open in the browser, you can see that the enterprise wechat robot has been triggered:

The above is a simple hello world function. Next, the play begins!

We further transform this basic function:

import os
import json
import urllib.request

def main_handler(event, context):
    url = os.environ.get("url")
    data = {
        "msgtype": "markdown",
        "markdown": {
            "content": event['body'],
        }
    }
    data = json.dumps(data).encode("utf-8")
    req_attr = urllib.request.Request(url, data)
    resp_attr = urllib.request.urlopen(req_attr)
    return resp_attr.read().decode("utf-8")

By changing the content field in data to event['body '], other modules can request this interface to realize robot push function. Of course, this basic function can also be improved, not only in markdown format, but also in more supported formats:

Robot function expansion

Remind drinking / eating function

This function can be realized by timing trigger and accessing cloud function.

For example index.py code:

import os
import json
import urllib.request

def main_handler(event, context):
    url = os.environ.get("url")
    data = "Drink more water every day. Don't forget to add water".encode("utf-8")
    req_attr = urllib.request.Request(url, data)
    resp_attr = urllib.request.urlopen(req_attr)
    return resp_attr.read().decode("utf-8")

serverless.yaml File:

MyRobot_Water:
  component: '@serverless/tencent-scf'
  inputs:
    name: MyRobot_Water
    runtime: Python3.6
    timeout: 3
    codeUri: ./water
    description: Remind the robot of drinking water
    region: ap-guangzhou
    environment:
      variables:
        url: https://service-lf3ug84s-1256773370.gz.apigw.tencentcs.com/release/push
    handler: index.main_handler
    memorySize: 64
    tags:
      app: myrobot
    events:
      - timer:
          name: timer
          parameters:
            cronExpression: '0 */30 9-17 * * * *'
            enable: true

This function is to remind you to drink water every 30 minutes from 9 a.m. to 5 p.m.

Weather forecast / local news function

To realize the function of weather forecast / news broadcast, we can use the existing news interface. Take Tencent cloud's cloud market as an example, we can find a news API interface:

According to the API document, you can see that the request address is: https://service-aqvnjmiq-1257101137.gz.apigw.tencentcs.com/release/news/search

The Get method can take a parameter: keyword. As the target keyword, write the code:

import ssl, hmac, base64, hashlib, os, json
from datetime import datetime as pydatetime
from urllib.parse import urlencode
from urllib.request import Request, urlopen


def main_handler(event, context):
    source = "market"

    datetime = pydatetime.utcnow().strftime('%a, %d %b %Y %H:%M:%S GMT')
    signStr = "x-date: %snx-source: %s" % (datetime, source)
    sign = base64.b64encode(hmac.new(os.environ.get('secretKey').encode('utf-8'), signStr.encode('utf-8'), hashlib.sha1).digest())
    auth = 'hmac id="%s", algorithm="hmac-sha1", headers="x-date x-source", signature="%s"' % (os.environ.get("secretId"), sign.decode('utf-8'))

    headers = {
        'X-Source': source,
        'X-Date': datetime,
        'Authorization': auth,
    }
    queryParams = {'keyword': 'Science and Technology News'}
    url = 'https://service-aqvnjmiq-1257101137.gz.apigw.tencentcs.com/release/news/search'
    if len(queryParams.keys()) > 0:
        url = url + '?' + urlencode(queryParams)

    content = ""
    for eve in json.loads(urlopen(Request(url, headers=headers)).read().decode("utf-8"))["result"]["list"][0:5]:
        content = content + "* [%s](%s) n"%(eve['title'], eve['url'])

    if content:
        urlopen(Request(os.environ.get('url'), content.encode("utf-8")))

serverless.yaml File:

MyRobot_News:
  component: '@serverless/tencent-scf'
  inputs:
    name: MyRobot_News
    runtime: Python3.6
    timeout: 3
    codeUri: ./news
    description: News push
    region: ap-guangzhou
    environment:
      variables:
        url: https://service-lf3ug84s-1256773370.gz.apigw.tencentcs.com/release/push
        secretId: Cloud market key information
        secretKey: Cloud market key information
    handler: index.main_handler
    memorySize: 64
    tags:
      app: myrobot
    events:
      - timer:
          name: timer
          parameters:
            cronExpression: '0 0 */8 * * * *'
            enable: true

The operation effect is as follows: push the science and technology news of the day to us at 8 o'clock every morning:

Monitoring alarm function

We can also give the enterprise wechat robot the ability to monitor and alarm:

index.py File:

import os
import urllib.request

def getStatusCode(url):
    return urllib.request.urlopen(url).getcode()

def main_handler(event, context):
    url = "http://www.anycodes.cn"
    if getStatusCode(url) == 200:
        print("Your website%s Accessible!" % (url))
    else:
        urllib.request.urlopen(urllib.request.Request(os.environ.get('url'), ("Your website%s No access!" % (url)).encode("utf-8")))
    return None

serverless.yaml File:

MyRobot_Monitor:
  component: '@serverless/tencent-scf'
  inputs:
    name: MyRobot_Monitor
    runtime: Python3.6
    timeout: 3
    codeUri: ./monitor
    description: Website monitoring
    region: ap-guangzhou
    environment:
      variables:
        url: https://service-lf3ug84s-1256773370.gz.apigw.tencentcs.com/release/push
    handler: index.main_handler
    memorySize: 64
    tags:
      app: myrobot
    events:
      - timer:
          name: timer
          parameters:
            cronExpression: '0 */30 * * * * *'
            enable: true

After the deployment is completed, the monitoring script of the website has been started. Check whether the website is available every 30 minutes. If not available, an alarm is sent:

Divergent thinking

Enterprise wechat robots can be given more and more interesting functions through the Serverless architecture, so what other products can be combined with the Serverless architecture to become more interesting?

With the continuous development of network technology, IoT technology has gradually entered into thousands of households. Whether it is a sweeping robot, intelligent curtains and other intelligent home, or intelligent speakers and other entertainment facilities, IoT technology has become visible and accessible.

Xiaoai students can also quickly develop exclusive new functions through the Serverless architecture.

First, we go to the open platform of "little love students" to register an account and submit the authentication:

Next, the customized function of Xiaoai students is studied. As shown in the figure, in the development document, we can see the capability information provided by Xiaoai's developer platform, as well as the detailed information of request and response:

Continue with project design. The goal of this article is to return to Tencent cloud + community's latest popular article title and brief introduction for users by saying "enter cloud + community" and other keywords to Xiaoai students.

The whole process is as shown in the figure:

Function code writing:

# -*- coding: utf8 -*-
import json
import logging
import urllib.request
import urllib.parse

logging.basicConfig(level=logging.NOTSET)


def main_handler(event, context):
    host = "https://cloud.tencent.com/"
    path = "developer/services/ajax/column/article?action=FetchColumnHomeArticleList"
    json_data = {
        "action": "FetchColumnHomeArticleList",
        "payload": {
            "pageNumber": 1,
            "pageSize": 20,
            "version": 1
        }
    }
    data = json.dumps(json_data).encode("utf-8")
    request_attr = urllib.request.Request(url=host + path, data=data)
    response_attr = urllib.request.urlopen(request_attr).read().decode("utf-8")
    json_resp = json.loads(response_attr)
    logging.debug(json_resp)
    temp_str = "The title of the article is%s,The main content is%s"
    list_data = json_resp["data"]["list"][0:5]
    art_list = [temp_str % (eve["title"], eve["abstract"]) for eve in list_data]
    news_str = '''Today's popular articles in Tencent's Yunjia community are as follows:%s''' % (",".join(art_list))
    logging.debug(news_str)

    xiaoai_response = {"version": "1.0",
                       "response": {
                           "open_mic": False,
                           "to_speak": {
                               "type": 0,
                               "text": news_str
                           }
                       },
                       "is_session_end": False
                       }
    return xiaoai_response

After completion, deploy using the Serverless Framework, bind the API gateway trigger, and you can see the test results through the request address:

As you can see, we have obtained the target data. At this time, we create skill development on Xiaoai's official website. After filling in and saving the basic information, we choose to configure the service and fill in the testing address in HTTPS:

After the configuration is completed, start the test, as shown in the following figure. You can see that when we enter the predetermined command "Open Cloud plus community", the system will retrieve the result information correctly and return it to us:

So far, we have successfully developed a new function for "little love students" through the Serverless architecture. We can also release and launch this new function!

summary

This paper is just a simple demonstration. Through the combination of enterprise wechat robot and Serverless architecture, the reminder function, news push function and business monitoring and alarm function are realized with several codes. At the same time, we also divergent thinking, so that little love students also have a new ability.

It is not hard to see that through the Serverless architecture, we can quickly add some new functions to the product and give it new vitality!

Serverless Framework 30 day trial plan

We invite you to experience the most convenient way to develop and deploy Serverless. During the trial period, the related products and services provide free resources and professional technical support to help your business quickly and conveniently realize Serverless!

Details can be found at: Serverless Framework trial plan

One More Thing

What can you do in three seconds? Take a sip, read an email, or - deploy a complete Serverless application?

Copy link to PC browser: https://serverless.cloud.tencent.com/deploy/express

Deploy in 3 seconds and experience the fastest Serverless HTTP Practical development!

Transfer gate:

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

Posted by EvilPrimate on Wed, 27 May 2020 05:58:34 -0700