Phodal Huang

Serverless has natural advantages in being event-driven, one of which is chatbots. Can do chat robot is not an easy thing, wechat and QQ can only use Hack way.

Therefore, IT occurred to me that wechat public account is not a better choice. When a user enters a keyword, respond accordingly. On the whole, they’re pretty much alike. At this point, you can start trying out a Serverless service running online.

In this case, there are several steps:

  • Create the Serverless service
  • Introducing node – wechat
  • Configure the APP_ID and TOKEN
  • Configure Route 53 and API Gateway
  • Add wechat public account service
  • The deployment of

Create the Serverless service

First, let’s create our service:

serverless create --template aws-nodejs --path serverless-wechat
Copy the code

This step is as simple as ever.

Introducing node – wechat

Then I found the Node-wechat library, which uses Express for routing, as shown in the following example:

const express = require('express'); const app = express(); var wechat = require('wechat'); Var config = {token: 'token', AppID: 'appID ', encodingAESKey: 'encodinAESKey', checkSignature: true // Optional. The default value is true. Because the wechat public platform interface debugging tool does not send signatures in plaintext mode, please set it to false if you want to use this test tool. app.use(express.query()); App. Use ('/wechat', config, function (req, res, next) {var message = req.weixin; If (message.fromuserName === 'diaosi') {// Reply res.reply('hehe'); }}));Copy the code

Above is our index.js file.

Then we use a method similar to the Serverless Application Development Guide: React Server Rendering for Serverless + Express to make a layer of proxy using AWS – Serverless – Express:

const awsServerlessExpress = require('aws-serverless-express');
const app = require('./index');
const server = awsServerlessExpress.createServer(app);

exports.runserver = (event, context) => {
   console.log("EVENT: " + JSON.stringify(event));
   awsServerlessExpress.proxy(server, event, context)
}
Copy the code

The next step is to do the configuration.

Configure the APP_ID and TOKEN

First, modify the configuration code in our index.js file:

let config = {
  token: process.env.TOKEN,
  appid: process.env.APP_ID,
  encodingAESKey: process.env.AESKey,
  checkSignature: true
};
Copy the code

The token, ID, and encodingAESKey will be read from the serverless. Yml file. Our serverless. Yml file will be read from another file:


functions:
  runserver:
    handler: handler.runserver
    events:
      - http: ANY /
      - http: 'ANY {proxy+}'
    environment:
      TOKEN: ${file(./config.yml):TOKEN}
      APP_ID: ${file(./config.yml):APP_ID}
      AESKey: ${file(./config.yml):AESKey}
Copy the code

Read from config.yml:

TOKEN: TOKEN
APP_ID: APP_ID
AESKey: AESKey
Copy the code

This is to make sure we can secure the key.

With everything ready, perform:

serverless deploy
Copy the code

The corresponding API is generated:

stack: serverless-wechat-dev
api keys:
  None
endpoints:
  ANY - https://e8tct5f0v2.execute-api.us-east-1.amazonaws.com/dev
  ANY - https://e8tct5f0v2.execute-api.us-east-1.amazonaws.com/dev/{proxy+}
functions:
  runserver: serverless-wechat-dev-runserver
Copy the code

So, I put this address in the background of the public account, and found that the public account does not support API Gateway. You have to find a way to use custom domain names, which you then need to create using Route 53.

Configure Route 53 and API Gateway

As mentioned earlier in the Serverless Application Development Guide: API Gateway and Route53 Custom Domain Names, follow these steps to configure Route53.

A domain name is registered on Route 53. If not, go to Route 53.

Only then can you request a certificate for your domain name

The region that needs to be selected is US-East-1 for this region to work with the API Gateway.

In this process, you need to verify the ownership of the domain name. Therefore, you need to find a place to register domain name mailbox, such as I use netease domain name mailbox.

$ yarn add --dev serverless-domain-manager
Copy the code

or

$ npm install serverless-domain-manager --save-dev
Copy the code
plugins:
  - serverless-domain-manager

custom:
  customDomain:
    domainName: wechat.wdsm.io
    basePath: ''
    stage: ${self:provider.stage}
    createRoute53Record: true
Copy the code
serverless create_domain
Copy the code

Log:

Serverless: Domain was created, may take up to 40 mins to be initialized.
Copy the code

AWS CLI

{
    "items": [
        {
            "certificateArn": "arn:aws:acm:us-east-1:706605665335:certificate/278c252a-7aaf-41df-bcf1-adc279347557",
            "distributionDomainName": "d1pp7oijqquj95.cloudfront.net",
            "certificateUploadDate": 1509592737,
            "domainName": "wechat.wdsm.io"
        }
    ]
}
Copy the code

Now, execute Serverless Deploy again to complete the step.

Add wechat public account service

We can then create a few simple services, such as searching for content from Google:

google(keyword, function (err, res) { let result = R.map(R.compose(updateItemField, R.values, R.pick(['title', 'link'])))(res.links); Response.reply (' What you want to search for on Google is: '+ result); });Copy the code

Or, search my blog for related content:

request.get('https://www.phodal.com/api/app/blog_detail/?search=' + keyword, { headers: { 'User-Agent': 'google' } }, function (error, res, body) { if (res.statusCode === 200) { let parsed = JSON.parse(body); const data = parsed; var result = R.map(R.compose(updatePhodalItemField, R.values, R.pick(['title', 'slug'])))(data); Response.reply ({content: 'on' phodal.com 'there are x results, the first 10 are as follows:' + result, type: 'text'}); }});Copy the code

The final code is: github.com/phodal/mp/b…

The deployment of

Finally, let’s happily execute Serverless deploy, which corresponds to the following log:

stack: serverless-wechat-dev
api keys:
  None
endpoints:
  ANY - https://e8tct5f0v2.execute-api.us-east-1.amazonaws.com/dev
  ANY - https://e8tct5f0v2.execute-api.us-east-1.amazonaws.com/dev/{proxy+}
functions:
  runserver: serverless-wechat-dev-runserver
Serverless Domain Manager Summary
Domain Name
  wechat.wdsm.io
Distribution Domain Name
  d1pp7oijqquj95.cloudfront.net
Copy the code

If you want to use this service, just:

serverless install -u https://github.com/phodal/mp -mp
Copy the code

Perform:

yarn install
Copy the code

Create your config.yml file again:

cp config.yml.template config.yml
Copy the code

Finally, you can deploy happily.

If you are testing, you can execute Serverless Remove to remove the service.