Files
PetCommunity/cloudfunctions/sendGreeting/index.js
2026-06-05 17:46:51 +08:00

54 lines
1.6 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
const cloud = require('wx-server-sdk')
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV })
const db = cloud.database()
exports.main = async (event, context) => {
const { OPENID } = cloud.getWXContext()
const { toUserId, petId } = event
if (!toUserId) return { code: -1, message: '缺少目标用户' }
if (toUserId === OPENID) return { code: -1, message: '不能给自己打招呼' }
try {
// 防刷5分钟内同一对用户只能打一次招呼
const cooldownMs = 5 * 60 * 1000
const recent = await db.collection('messages')
.where({
fromId: OPENID,
toId: toUserId,
type: 'greeting',
createdAt: db.command.gt(new Date(Date.now() - cooldownMs).toISOString()),
})
.count()
if (recent.total > 0) {
return { code: -1, message: '打招呼太频繁了,稍后再试' }
}
// 获取发送者信息
const senderRes = await db.collection('users')
.where({ openid: OPENID })
.field({ nickName: true, pets: true })
.get()
const sender = senderRes.data[0]
const pet = sender?.pets?.find(p => p._id === petId) || sender?.pets?.[0]
const greeting = `${sender?.nickName || '小伙伴'} 想认识你的宠物!${pet ? `TA 的 ${pet.name} 向你打了个招呼 🐾` : '来聊聊吧 🐾'}`
await db.collection('messages').add({
data: {
fromId: OPENID,
toId: toUserId,
content: greeting,
type: 'greeting',
isRead: false,
createdAt: db.serverDate(),
},
})
return { code: 0, data: null }
} catch (e) {
return { code: -1, message: e.message }
}
}