dienst_echo_whatsappgroep/src/messageHandler.js

67 lines
1.9 KiB
JavaScript

const { findDienst, getPngFilePaths } = require('./dienstService')
const { sendTextMessage, sendImageMessage, notifyAdmin } = require('./whatsappApi')
const BOT_NAME = (process.env.BOT_NAME || 'EdGpt').toLowerCase()
const ALLOWED_GROUP = process.env.ALLOWED_GROUP
function extractDienstnummer(body) {
const match = body.match(/\b(\d{4})\b/)
return match ? match[1] : null
}
function isBotMentioned(message) {
if (message._data?.mentionedJidList?.length > 0) {
return true
}
if (message.body) {
const normalized = message.body.toLowerCase().replace(/\s+/g, '')
if (normalized.includes(`@${BOT_NAME.replace(/\s+/g, '')}`)) {
return true
}
}
return false
}
async function handleWebhook(payload) {
if (payload.dataType !== 'message') return
if (payload.sessionId !== process.env.WHATSAPP_SESSION) return
const message = payload.data?.message
if (!message) return
if (message.fromMe) return
if (message.from !== ALLOWED_GROUP) return
if (!isBotMentioned(message)) return
const dienstnummer = extractDienstnummer(message.body || '')
if (!dienstnummer) return
console.log(`Processing dienst ${dienstnummer} for ${message.author}`)
const author = message.author
if (!author) return
const dienst = findDienst(dienstnummer)
if (!dienst) {
await sendTextMessage(author, `Dienstnummer ${dienstnummer} niet gevonden.`)
return
}
const pngPaths = getPngFilePaths(dienst)
if (!pngPaths || pngPaths.length === 0) {
await sendTextMessage(author, `Geen pagina's gevonden voor dienst ${dienstnummer}.`)
return
}
for (const pngPath of pngPaths) {
const filename = pngPath.split('/').pop()
try {
await sendImageMessage(author, pngPath, filename)
} catch (err) {
const errorMsg = `Fout bij verzenden ${filename} naar ${author}: ${err.message}`
console.error(errorMsg)
await notifyAdmin(errorMsg)
}
}
}
module.exports = { handleWebhook }