From enterprise WeChat robots to Xiaoai classmates, use Serverless to realize intelligent life!

Posted May 27, 20209 min read

Through the timing trigger, a corporate WeChat robot can be customized quickly and easily. We can use it to realize small functions such as drinking water, eating reminders, etc., as well as small functions for regularly pushing news, weather, and even monitoring alarms.

Use corporate WeChat robots

In the enterprise WeChat, choose to add a robot:

Add Robot

After that, we can customize the basic functions of the enterprise WeChat robot according to the document:

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

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

Through the 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 up the API gateway trigger:

The index.py file is 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")

The serverless.yaml file is 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 address output 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 good show begins!

We further reform 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 implement the robot push function. Of course, we can improve this basic function, not just markdown Format, encapsulating more supported formats:

Robot function expansion

Remind to drink water/meal function

This function can be achieved by timing triggers and accessing cloud functions.

For example, the index.py code:

import os
import json
import urllib.request

def main_handler(event, context):
    url = os.environ.get("url")
    data = "Drink plenty of 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 robots who drink 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

The function is to remind you to drink water every 30 minutes from 9 am to 5 pm every day.

Weather forecast/local news function

To implement the weather forecast/news broadcast function, we can implement it through the existing news interface. Taking Tencent Cloud s cloud market as an example, look for a news API interface:

According to the API documentation, you can see the request address is: https://service-aqvnjmiq-1257 ...

The Get method can carry a parameter:keyword, as the target keyword, write 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:%s \ nx-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':'Tech 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 feed
    region:ap-guangzhou
    environment:
      variables:
        url:https://service-lf3ug84s-1256773370.gz.apigw.tencentcs.com/release/push
        secretId:Cloud market secret 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 running effect is as follows. Every day at 8 o'clock, we will push the news of the day:

Monitoring alarm function

We can also give our WeChat robots the ability to monitor and alert:

The 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 can be accessed!"%(url))
    else:
        urllib.request.urlopen(urllib.request.Request(os.environ.get('url'),("Your website%s is not accessible!"%(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 complete, the monitoring script of the website has been started, and check whether the website is available every 30 minutes. If it is not available, an alert will be sent:

Divergence of ideas

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 thousands of households. Whether it is smart homes such as cleaning robots, smart curtains, or entertainment facilities such as smart speakers, IoT technology has become visible.

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

First, we go to the "Xiaoai classmates" open platform to register an account and submit the certification:

Next, we will study the customized functions of Xiaoai. As shown in the figure, in the development document, we can see the ability information provided by the Xiaoai classmate developer platform, and we can also view the detailed information of request and response:

Continue with project design. The goal of this article is to return the title and introduction of the latest popular article of Tencent Cloud + Community to users by saying keywords such as "enter into the cloud + community" to Xiao Ai.

The whole process is shown in the figure:

System Flow Diagram

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 article title 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 = '' 'Tencent Yunjia community's popular articles today 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, use Serverless Framework for deployment, bind API gateway trigger, and see the test result by requesting the address:

As you can see, we have obtained the target data. At this time, we create a skill development on the official website of Xiaoai. After filling in and saving the basic information, select the configuration service and fill in the test address in HTTPS:

After the configuration is complete, start the test. As shown in the following figure, you can see that when we enter the predetermined command "Open Yunjia Community", the system will correctly retrieve the result information and return us:

At this point, we have successfully developed a new feature for "Little Love Classmates" through the Serverless architecture. We can also release and launch this new feature!

to sum up

This article is just a simple demonstration. Through the combination of the enterprise WeChat robot and the Serverless architecture, several codes are used to implement the reminder function, news push function, and business monitoring and alarm function. At the same time, we also divergent thinking, so that Xiao Ai students also have new abilities.

It is not difficult to see that through the Serverless architecture, we can quickly add some new features to the product and give 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, related products and services provide free resources and professional technical support to help your business realize Serverless quickly and conveniently!

For details, please refer to: Serverless Framework Trial Program

One More Thing

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

Copy the link to the PC browser to visit: https://serverless.cloud.tenc ...

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

Portal:

Welcome to visit: Serverless Chinese Network , you can experience more about the development of Serverless applications in Best Practice !


Recommended reading: "Serverless architecture:from principle, designed to project combat"