This commit is contained in:
bipproduction
2025-10-21 14:57:16 +08:00
parent fe397ef469
commit c446093458
2 changed files with 98 additions and 0 deletions

View File

@@ -1,5 +1,17 @@
import Elysia, { t } from "elysia";
import { prisma } from "../lib/prisma";
import type { WAHookMessage } from "types/wa_messages";
import _ from "lodash";
async function fetchWithTimeout(input: RequestInfo, init: RequestInit, timeoutMs = 120_000) {
const controller = new AbortController()
const id = setTimeout(() => controller.abort(), timeoutMs)
try {
return await fetch(input, { ...init, signal: controller.signal })
} finally {
clearTimeout(id)
}
}
const WaHookRoute = new Elysia({
prefix: "/wa-hook",
@@ -54,6 +66,50 @@ const WaHookRoute = new Elysia({
},
});
const waHook = body as WAHookMessage
const flow = await prisma.chatFlows.findUnique({
where: {
id: "1",
},
})
if (!flow) {
console.log("no flow found")
}
if (flow?.defaultFlow && flow.active) {
const { flowUrl, flowToken } = flow
const question = waHook?.entry[0]?.changes[0]?.value?.messages[0]?.text?.body
const contacts = waHook?.entry[0]?.changes[0]?.value?.contacts[0]
const name = contacts?.profile?.name
const number = contacts?.wa_id
const response = await fetchWithTimeout(`${flowUrl}/prediction/${flow.defaultFlow}`, {
headers: {
Authorization: `Bearer ${flowToken}`,
'Content-Type': 'application/json',
},
method: 'POST',
body: JSON.stringify({
question,
overrideConfig: {
sessionId: `${_.kebabCase(name)}_x_${number}`,
vars: { userName: _.kebabCase(name), userPhone: number },
},
}),
})
const responseText = await response.text()
try {
const result = JSON.parse(responseText)
console.log(result)
} catch (error) {
console.log(error)
console.log(responseText)
}
}
return {
success: true,
message: "WhatsApp Hook received"

42
types/wa_messages.ts Normal file
View File

@@ -0,0 +1,42 @@
type TYPE = "image" | "video" | "audio" | "file" | "text" | "sticker" | "document"
const message = {
"object": "whatsapp_business_account",
"entry": [
{
"id": "783866307805501",
"changes": [
{
"value": {
"messaging_product": "whatsapp",
"metadata": {
"display_phone_number": "6285801681205",
"phone_number_id": "919585147894728"
},
"contacts": [
{
"profile": {
"name": "malik kurosaki"
},
"wa_id": "6289697338821"
}
],
"messages": [
{
"from": "6289697338821",
"id": "wamid.HBgNNjI4OTY5NzMzODgyMRUCABIYIEFDRjdEM0Q3NERFNjhGRERBQkQ4NDAxRTEzRTAzQ0MyAA==",
"timestamp": "1760952787",
"text": {
"body": "halo"
},
"type": "text" as TYPE
}
]
},
"field": "messages"
}
]
}
]
}
export type WAHookMessage = typeof message