You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 

63 lines
1.5 KiB

// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init({
env: cloud.DYNAMIC_CURRENT_ENV
}) // 使用当前云环境
const db = cloud.database()
const kTableName = 'todo'
// 云函数入口函数
exports.main = async (event, context) => {
try {
// --- 步骤1 ---
// 从云开发数据库中查询等待发送的消息列表
const msgArr = await db.collection(kTableName)
// 查询条件
.where({
checked: false,
pushed: false,
}).get();
// ---步骤2---
for (const msgData of msgArr.data) {
// 发送订阅消息
await cloud.openapi.subscribeMessage.send({
touser: msgData._openid, //要发送的用户的openid
page: 'pages/index/index', // 用户通过消息通知点击进入小程序
lang: 'zh_CN',
templateId: 'qyVdbBkue4HUeuzXIeHo8LH938gMPKJMj2bP9zTnQCo',
miniprogramState: 'developer',
data: {
// 事项主题
thing23: {
value: msgData.content === '' ? '无' : sliceBodyStr(msgData.content, 16)
},
// 待办内容
thing1: {
value: '别忘了待办事项哦!'
}
}
});
// ---步骤3---
// 发送成功后将pushed数据状态重置
db.collection(kTableName).doc(msgData._id).update({
data: {
pushed: true,
},
});
}
// ---步骤4---
return msgArr;
} catch (e) {
console.log("推送出错!");
console.log(e);
}
}
// 辅助函数: 将太长的文本截短
function sliceBodyStr(str, length) {
if (str.length <= length) {
return str;
} else {
return str.slice(0, length) + '...';
}
}