WeChat cloud development, subscription message scheduled batch sending implementation code

need:

Make a subscription message reminder similar to lottery result notification

Implementation process:

Each user needs to be authorized to receive subscription messages first. After the authorization is successful, the data is stored in the cloud-developed data collection, and then a timer is written to traverse all the data in the data collection. After obtaining it, it traverses and sends the subscription message. After the transmission is successful, delete the data.

Let’s take a look at the implementation operations and code:

  1. Create a cloud development environment, create a data collection msg, change the data permissions to customized, and all can be modified.
    Insert image description here
  2. The code for the mini program to authorize and submit user information (data is the field for the subscription message, the user Openid, the page to which the subscription message jumps),
  wx.requestSubscribeMessage({
    
    
    tmplIds: ['DYvZoya_RukdkznIQchLWsD296UujyU_pCFGRXa9nnw'],
    success (res) {
    
     
      wx.cloud.callFunction({
    
    
          name: "sendMsg",
          data: {
    
    
            thing5: '111',
            thing1: '22',
            name2: '33',
            thing6: '44',
            openid: 'oESJb5LTR0lu7rUn9mVpAt-xEu2k',
            page: 'pages/index/index',
          },
          success(res) {
    
    
            console.log('个人信息-------------', res)
          },
          fail(err) {
    
    
            console.log('个人信息-------------', err)
 
          }
      })
    }
  })   
  1. Cloud function to store data, create a new cloud function sendMsg, code:
const cloud = require('wx-server-sdk')
 
cloud.init({
    
    
  env: 'shijihyj-5g7mfb4z4011210a '
})
const db = cloud.database()
exports.main = async (event, context) => {
    
    
  db.collection('msg').add({
    
    
    // data 字段表示需新增的 JSON 数据
    data: {
    
    
      thing5: event.thing5,     
      thing1: event.thing1,
      name2: event.name2,
      thing6: event.thing6,
      openid: event.openid,
      page: event.page,
    }
  })
  .then(res => {
    
    
    console.log(res)
    return res
  })
  .catch(console.error)
}
  1. Create the timer myTrigger again
{
    
    
  "permissions": {
    
    
    "openapi": [
      "subscribeMessage.send"
    ]
  },
  "triggers": [
    {
    
    
      "name": "myTrigger",
      "type": "timer",
      "config": "10 * * * * * *"
    }
  ]
}

js file:

const cloud = require('wx-server-sdk')
 
cloud.init({
    
    
  env: 'shijihyj-5g7mfb4z4011210a '
})
const db = cloud.database()
var sendMsg = async (item) =>{
    
    
  
  const result = await cloud.openapi.subscribeMessage.send({
    
    
      touser: item.openid,
      page: item.page,
      lang: 'zh_CN',
      data: {
    
    
        thing5: {
    
    
          value: item.thing5 
        },
        thing1: {
    
    
          value: item.thing1
        },  
          name2: {
    
    
            value: item.name2
          },
          thing6: {
    
    
            value: item.thing6
          }
        },
      templateId: 'DYvZoya_RukdkznIQchLWsD296UujyU_pCFGRXa9nnw',
    })
    const remove = await db.collection('msg').where({
    
    
      openid: item.openid
    }).remove()
}
 
const MAX_LIMIT = 100
exports.main = async (event, context) => {
    
    
  // 先取出集合记录总数
  const countResult = await db.collection('msg').count()
  const total = countResult.total
  // 计算需分几次取
  const batchTimes = Math.ceil(total / 100)
  // 承载所有读操作的 promise 的数组
  const tasks = []
  for (let i = 0; i < batchTimes; i++) {
    
    
    const promise = db.collection('msg').skip(i * MAX_LIMIT).limit(MAX_LIMIT).get()
    tasks.push(promise)
  }
  // 等待所有
var arr = (await Promise.all(tasks)).reduce((acc, cur) => {
    
    
    return {
    
    
      data: acc.data.concat(cur.data),
      errMsg: acc.errMsg,
    }
  })
  for(var i =0;i<arr.data.length;i++){
    
    
    sendMsg(arr.data[i])
  }
}

Guess you like

Origin blog.csdn.net/qq_44625715/article/details/131536630