Dear, hello, everyone. I am “Front-end Xiaoxin”. 😇 has been engaged in front-end development and Android development for a long time


background

Our company has been using enterprise wechat as a communication tool for employees, and many groups have added group chat robots to remind them of tasks. Naturally, one application scenario of group chat robots is to perform defined tasks, such as regularly sending meeting reminders, filling in weekly reports and so on. Often, we need to have a personal PC or cloud server that is not turned off to support the group chat bot to run for a long time (Windows ads can be found and closed in the task scheduler). Personal PCS are not suitable for running for a long time (Windows users know, soon will become stuck). Cloud server also needs to cost a lot of money, so we need to have a Serverless platform to solve this problem (the free amount is also enough, absolutely over value).

Case introduced

By using the cloud function of Serverless product in Tencent cloud platform to provide service support, we completed a case of the weather situation of the day sent by an enterprise wechat group robot at 8:00 a.m. every day. To realize this case, you need to do the following preparations:

  1. Sign up for Tencent’s cloud platform: cloud.tencent.com/
  2. Register enterprise wechat platform: work.weixin.qq.com/
  3. Use VSCodeIDE and install the plug-in Tencent Serverless Toolkit for VSCode

How the enterprise micro group robot sends messages:

Implement enterprise micro group of message sending robots mainly through to Webhook address assigned to the robot sends a request to complete, if you are a group manager when you pull the robot into the group of robots will be given the corresponding Webhook robot information address, especially paying special attention to: must protect the robot Webhook address, avoid leaking! Don’t t share it on Github, on blogs, where it can be viewed publicly, or bad guys can use your bots to spam.

  • Enterprise micro group of robot configuration instructions: work.weixin.qq.com/api/doc/900…

Project environment preparation:

  1. Initialization project:npm init -y
  2. Initialize Ts configuration:tsc --init
  3. Install AXIOS to request data:yarn add axios

Module division:

  1. Model.ts: message model (corresponding API documentation), creating message model functions;
/** * Message type */
export enum MsgType {
    /** Markdown type */
    markdown = "markdown",}/** * Markdow message model */
export type MarkdownContext = {
    /** Markdown content, up to 4096 bytes, must be UTF8 encoding */
    content: string,}/** * Message model base class */
export type Message<T> = {
    msgtype: MsgType & T,
    [type: string]: T,
}

/** * Create a message to be sent *@param type 
 * @param content 
 * @returns * /
function createMessage<T> (type: MsgType, content: T) {
    return {
        msgtype: type[type]: content,
    } as Message<T>;
}

/** * Create a markdown message *@param content 
 * @returns * /
export function createFileMessage(content: FileContext) {
    return createMessage<FileContext>(MsgType.file, content);
}
Copy the code
  1. Notice. ts: sends various types of notification functions;
import axios from 'axios';
import { createFileMessage, createImageMessage, createMarkdownMessage, createNewsMessage, createTextMessage, FileContext, ImageContext, MarkdownContext, Message, NewsContext, TextContext } from './model';

function request<T> (webhook: string, message: Message<T>) {
    if(! webhook)throw new Error("Please set the correct webhook address of the robot");
    axios.post(webhook, message).then(res= > {
        const { status, data } = res;
        if (status === 200 && data) {
            console.log(data.errcode === 0 ? "Sent successfully" : data.errmsg);
        }
    }).catch(err= > {
        console.log(err); })}/** Initiate Markdown message notification */
export const requestMDNotice = (webhook: string, mdContext: MarkdownContext) = > request<MarkdownContext>(webhook, createMarkdownMessage(mdContext));
Copy the code
  1. Index. ts: entry performs weather information retrieval and calls to send Markdown type messages.
import { requestMDNotice } from "./notice";
import axios from 'axios';
import { AMAP_WEATHER_API, ENTERPRISE_WECHAT_ROBOT_WEB_HOOK } from "./config";
axios.get(AMAP_WEATHER_API).then(res= > {
    const { status, data } = res;
    if (status === 200 && data) {
        if (data.status === '1' && data.infocode === '10000') {
            let message = ' '
            data.lives.forEach((live: any) = > {
                message += ` # # # # # today${live.province}.${live.city}Weather * Weather:${live.weather}* the temperature:${live.temperature}Degree Celsius * Wind direction:${live.winddirection}* wind:${live.windpower}Grade * Humidity:${live.humidity}* Data release date:${live.reporttime}\n
                `
            });
            // Send a notice in MD format to the wechat group of the enterprise
            requestMDNotice(ENTERPRISE_WECHAT_ROBOT_WEB_HOOK, {
                content: message
            })
        }
    }
})
Copy the code
  1. Autonavi Weather query API and Webhook address configuration for robot:
// Enterprise wechat group robot webhook address
export const  ENTERPRISE_WECHAT_ROBOT_WEB_HOOK = "Please fill in the Webhook address of your robot.";
// Autonavi weather query API, city address in autonavi development document query
export const  AMAP_WEATHER_API = "Please fill in your Own Weather Enquiry Address"
Copy the code

Run debugging:

  • Execute our entry file directly via ts-Node:ts-node .\src\index.tsAfter the output is sent successfully, you can see the latest message in the enterprise micro group.

The cloud function performs the task of periodically sending weather conditions:

Install and understand Tencent Cloud function development plug-in “Tencent Serverless Toolkit for VS Code” :

  • Pull the list of cloud functions in the cloud and trigger the cloud function.
  • Quickly create a cloud function project locally.
  • Use simulated COS, CMQ, CKafka, API gateway and other trigger events to trigger the function to run.
  • Upload the function code to the cloud and update the function configuration.
  • Run and debug function code in the cloud.

Initialize and write cloud functions:

  1. Open an empty folder with VSCode;
  2. Look for Tencent cloud LogoTo open the plug-in, bind user credentials and region for the first use;
  3. Create a function in the local function window => Select Nodejs version => fill in the function name to get the following basic template:

  1. Ts compiled our robot to send notification code to JS version, run directlytscAfter that, the content will be covered by the cloud functionsrcThe directory (the index.js file needs to be copied into the main_handler function);
  2. Because we have utilityaxiosModule to send requests, so the cloud function project also needs to install: into the cloud function project**src**Directory execution:npm init -y && yarn add axios;

Upload and deploy debugging in the cloud

  • The development of the cloud function is completed at this point. Upload the cloud function through the local function window (node_module is recommended to be installed on the console first if the content is too much), and perform deployment and test on the console;

Configuring Trigger Management (Scheduled Task)

  • Create a new trigger in the trigger management menu to execute the scheduled task. Cron expression is adjusted with the crontab. Guru /every-day query.

Conclusion:

The content points involved in this article are: Autonavi development platform weather query API use, Tencent cloud Serverless cloud function use, enterprise micro group robot configuration and API, together to complete today’s actual combat case, you have any interesting application scenarios? Tell me about? 😂


Welcome to follow my public account “Front-end Xiaoxin students”, the first time to push original technical articles.