Lee Seong-hee, Shopee Airpay front End Leader. After graduation in 2014, I joined Tencent AlloyTeam and successively took charge of projects such as QQ group, Pattern live broadcast and Tencent Documents. Later, he joined Tencent Yunyun Development team in 2018. Focus on performance optimization, engineering and small program services. Weibo | zhihu | dead simple

When I arrived at the new company, I found that I also used wechat. But unfortunately, the external enterprise wechat has no robot. This used to use the enterprise micro channel in the goose factory before I feel very inconvenient to remind. Finally, in July, the enterprise wechat finally launched the robot function.

Right – click group chat card to add group bots.

The Webhook address is displayed when you hover over the robot’s head. Clicking on this address will take you to the robot’s development documentation.

The development of the alert robot is actually very simple, in fact, it is to this Webhook address, according to the format provided by the document to send a request, you can realize the message push. For the simplest example, we can use node.js’s Axios library:

const axios = require('axios')

async function bookLunch() {
    let result = await axios.post(baseUrl, {
        msgtype: 'text',
        text: {
            content: 'Big man, order lunch! ',
            mentioned_list: ['@all'[// Can use email or mobile phone number}})return result.data
}

bookLunch.then((res) => {
    console.log(res)
})
Copy the code

So that’s the simplest example. In addition to normal text content, you can also send markdown, graphics and other content, you can see the document by yourself.

But the problem comes: generally speaking, remind, all need to be timed, such as every morning to remind you to write a plan, every Friday evening to remind you to write a weekly newspaper, how can let the robot appear at these time points to remind you? You might want to buy a server and deploy the CronJob service on it to schedule the service periodically. Yes, this is certainly the most popular way. But to buy a server to spend money ah, cheap also cost dozens of dollars a virtual machine, and only in the above run such a simple service is obviously not worth. Is there a cost-effective approach? Yes, use the cloud function!

My personal understanding, the main difference with the traditional service cloud function there are a few points, a type is that it is a kind of event service, triggered by different events (HTTP, data changes, the change of object storage, etc.), a second, it is a long in operation after a certain time cooling or destroyed, the third because of the above two properties, for the services of some of the load is not very high, Cloud functions can save money. For this kind of reminding robot, it is a kind of service with low load, which is very suitable. This kind of reminder service for small teams, in the recent major manufacturers are promoting the period, really can do free.

Here I am most familiar with the cloud function of Tencent Cloud, so I use it to do practice.

Firstly, for convenience, we can use SCF CLI provided by Tencent Cloud to initialize our cloud functions and configuration files. My computer is a Macbook, and I can directly install the following commands for installation:

pip install scf
Copy the code

If it is not a Macbook, you can install Python and PIP first

Then it is time to configure:

scf configure set --region ap-guangzhou --appid 1253970223 --secret-id AKIxxxxxxxxxx --secret-key uxxlxxxxxxxx
Copy the code

Appid, secret-id and secret-key are available on the access key page. Region is the region where you want to deploy the cloud function. For example, on the console home page of the cloud function, you can see the region at the top. Guangzhou is ap-guangzhou, and HongKong is ap-hongkong. Basically ap- plus pinyin for the domestic market or English for foreign cities.

Then we initialize the project (using node.js 8.9 to write the cloud function) :

Initialize the cloud functionSCF init -- Runtime nodejs8.9 --name wework-robotcd wework-robot

Initialize the Node project
npm init -y
Copy the code

Then the cloud function can be obtained:

To use axios this time, let’s install this dependency:

npm i --save axios
Copy the code

Open index.js with the following code and async means that the function can use async/await, a new feature of Node.js.

'use strict';
exports.main_handler = async (event, context, callback) => {
    console.log("%j", event);
    return "hello shopee!"
};
Copy the code

I made some cuts, and it looks like this. Change the function name to main, and since async/await is used you can handle asynchrony without callback. Template. yaml should also be changed to main_handler instead of main

exports.main = async (event, context) => {
    return "hello shopee!"
};
Copy the code

All right. It’s time to write the alert logic. The logic is not hard, but the main thing to notice is timing. After the test, the time in the cloud function uniformly uses the standard international time, that is, Beijing time is 8 hours later than it. The detailed logic can be seen in the following code notes:

const axios = require('axios')
const baseUrl =
    'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=7f399641-40aa-45c8-ad3d-c46e1ee085a7'

async function bookLunch() {
    let result = await axios.post(baseUrl, {
        msgtype: 'text',
        text: {
            content: 'Big man, order lunch! ',
            mentioned_list: ['@all'] // Remind everyone}})return result.data
}

async function bookTaxi() {
    let result = await axios.post(baseUrl, {
        msgtype: 'text',
        text: {
            content: 'You've worked so hard, go home early and have a rest. 9 o 'clock taxi can be reimbursed. ',
            mentioned_list: ['@all']}})return result.data
}

async function remindWeeklyReport() {
    let result = await axios.post(baseUrl, {
        msgtype: 'text',
        text: {
            content: 'It's Friday, write your weekly paper and see if you've been lazy this week! ',
            mentioned_list: ['@all']}})return result.data
}

async function remindGoHome() {
    let result = await axios.post(baseUrl, {
        msgtype: 'text',
        text: {
            content: 'It's half past eleven. Let's go to bed early. '}})returnResult. data} // Whether it is Fridayfunction isFriday(day) {
    returnDay === 5} // Specifies the working dayfunction isWeekDay(day) {
    returnDay > 0 && day < 6} // Whether 30 minutes, one more minute is reserved in case of delayed startup or execution of cloud functionsfunction isHalfHour(min) {
    returnMin >= 30 && min <= 31} // Whether the cloud function is on time, 1 more minute is reserved in case of delayed startup or executionfunction isSharp(min) {
    return min >= 0 && min <= 1
}

exports.main = async (event, context) => {
    letD = new Date() // js time objectletDay = d.goetday () // Get what day of the week it is today, 0 means SundayletHour = d.gether ours() // Get the current timeletMin = d.gettminutes () // Get the current scoreletHourGap = 8 // We are in east 8 hour += hourGap // get the current exact number of times // clicklogConsole. log(' day:${day} hour: ${hour} min: ${min} hourGap: ${hourGap}I'll be notified every Friday from 4:00 to 4:30 to write the weekly reportif (isFriday(day) && hour === 4 && isHalfHour(min)) {
        returnRemindWeeklyReport ()} // remindWeeklyReport()if (isWeekDay(day) && hour === 11 && isSharp(min)) {
        returnAwait bookLunch()} // Remind taxi at 9pm on weekdays can be reimbursedif (isWeekDay(day) && hour === 21 && isSharp(min)) {
        returnAwait bookTaxi()} // Remind to rest at 11:30pm every weekdayif (isWeekDay(day) && hour === 23 && isHalfHour(min)) {
        return await remindGoHome()
    }

    return 'hi shopee! '
}
Copy the code

The logic is written, however, we need it to be executed periodically, say every 30 minutes. At this point, we need to add the “timing trigger”. We can add it to template.yaml, we can remove the comment, and modify it to get:

CronExpression concrete can refer to this document: cloud.tencent.com/document/pr…

Please use the recommended way:

Here are some examples to use directly:

I wrote: 0 */30 * * * mon-fri *, which means the cloud function will be called every 30 minutes from Monday to Friday.

Of course, we also want to enable HTTP triggers to access the cloud function directly with the address for some logical debugging to see if the message actually succeeds.

We can add another HTTP trigger to template.yaml:

All right, we’re all set. We just need to republish using SCF CLI.

# packaged
scf package -t template.yaml 
Generate deploy file 'deploy.yaml' success

# release
scf deploy -t deploy.yaml 
Deploy function 'wework-robot' success
Copy the code

After the release, we can go to the console of Tencent Cloud to have a look, it already exists:

Click on the trigger mode to see if there is a timing trigger and an API gateway trigger (HTTP trigger).

And then you’re done! Look at the results: