feat: add core modules - dienstService, whatsappApi, messageHandler, webhook server

This commit is contained in:
Eddy 2026-05-11 18:52:50 +02:00
commit 3e6b33f103
4 changed files with 163 additions and 0 deletions

62
src/messageHandler.js Normal file
View file

@ -0,0 +1,62 @@
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 && message.body.toLowerCase().includes(`@${BOT_NAME}`)) {
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
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 }