nodeJS实现企业微信机器人每天定时发消息实例 定时任务

nodeJS实现企业微信机器人每天定时发消息实例

背景

由于企业微信办公需要,“每天定时推送某消息用来提醒群里面所有人或者部分人”,于是决定用企业微信自带的机器人来实现此功能,来代替人为的每天发送同样的消息,具体方法我来一一讲述。
需要用到企业微信群、企业微信机器人、一台服务器(或者一台不关机的电脑)、nodeJS、node-schedule、request等;

企业微信API

具体见官网说明:https://work.weixin.qq.com/help?person_id=1&doc_id=13376

效果
666.png
代码
   //引入需要的模块
    // node-schedule 为定时任务模块
    // request 为请求第三方接口模块
    const schedule = require("node-schedule");
    const request = require('request');
   
  //resData对象各属性请参考官方文档
  // https://work.weixin.qq.com/help?doc_id=13376
    var resData = {
        "msgtype": "text",
        "text": {
            "content": "需要发送的消息",
            "mentioned_list": ["wangqing","@all"],
            "mentioned_mobile_list":["13800001111","@all"]
        }
    };

    function requestfun() {
          // url 为企业机器人的webhook
         request({
            url: "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=xxxx",
            method: "POST",
            headers: {
                "content-type": "application/json",
            },
            body: JSON.stringify(resData)
        }, function (error, response, body) {
            console.log('提示成功!');
        });
    }

    const scheduleCronstyle = () => {
        //每分钟的第30秒定时执行一次:
        schedule.scheduleJob('0 15 18 * * 1-5', () => {
            requestfun();
            // console.log('scheduleCronstyle:' + new Date());
        });
    }

    scheduleCronstyle();
    console.log('Start successfully');

node-schedule 关于 scheduleJob方法的参数规则讲解。

 schedule.scheduleJob('0 15 18 * * 1-5', () => {
        requestfun();
    // console.log('scheduleCronstyle:' + new Date());
    });   
  //上面参数解释:
      周一到周五,每天18点15分0秒的时候执行 requestfun();
      
    //其它各个参数:
    *    *    *    *    *    *
    ┬    ┬    ┬    ┬    ┬    ┬
    │    │    │    │    │    │
    │    │    │    │    │    └ day of week (0 - 7) (0 or 7 is Sun)
    │    │    │    │    └───── month (1 - 12)
    │    │    │    └────────── day of month (1 - 31)
    │    │    └─────────────── hour (0 - 23)
    │    └──────────────────── minute (0 - 59)
    └───────────────────────── second (0 - 59, OPTIONAL)        

   每分钟的第30秒触发: '30 * * * * *'
   每小时的1分30秒触发 :'30 1 * * * *'
   每天的凌晨1点1分30秒触发 :'30 1 1 * * *'
   每月的1日1点1分30秒触发 :'30 1 1 1 * *'
   2016年的1月1日1点1分30秒触发 :'30 1 1 1 2016 *'
   每周1的1点1分30秒触发 :'30 1 1 * * 1'
  
  //每个参数还可以配置范围值 (numa-numb)
  每周1的1点1分30秒-40秒触发 :'30-40 1 1 * * 1'      

注意:运行该程序后不能关闭改程序,需一直运行在服务器或者电脑上;电脑或服务器重启需重新运行该程序

GitHub地址:https://github.com/chenwenbo236/timedTasks.git

关于 node-schedule request 的详细教程,可自行百度。
如有什么问题,可以指出,谢谢!

你可能感兴趣的:(nodeJS实现企业微信机器人每天定时发消息实例 定时任务)