Files
aragrp/app/api/consulting/route.ts
T
2026-02-19 22:07:23 +03:30

84 lines
2.4 KiB
TypeScript

import { NextResponse } from 'next/server'
/** API بله سازگار با API تلگرام — مستندات: https://dev.bale.ai */
const BALE_API = 'https://tapi.bale.ai'
export interface ConsultingRequestBody {
fullName: string
organization: string
phone: string
area: string
description?: string
}
function escapeHtml(text: string): string {
return text
.replace(/&/g, '&')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
}
export async function POST(request: Request) {
const token = process.env.BALE_BOT_TOKEN
const chatId = process.env.BALE_CHAT_ID
if (!token || !chatId) {
return NextResponse.json(
{
error:
'بله پیکربندی نشده است. BALE_BOT_TOKEN و BALE_CHAT_ID را در .env.local تنظیم کنید.',
},
{ status: 500 }
)
}
let body: ConsultingRequestBody
try {
body = await request.json()
} catch {
return NextResponse.json({ error: 'بدنه درخواست نامعتبر است' }, { status: 400 })
}
const { fullName, organization, phone, area, description } = body
if (!fullName?.trim() || !organization?.trim() || !phone?.trim() || !area?.trim()) {
return NextResponse.json({ error: 'فیلدهای الزامی خالی است' }, { status: 400 })
}
const lines = [
'📩 <b>درخواست جدید مشاوره سازمانی</b>',
'',
`<b>نام و نام خانوادگی:</b> ${escapeHtml(fullName.trim())}`,
`<b>نام سازمان:</b> ${escapeHtml(organization.trim())}`,
`<b>شماره تماس:</b> ${escapeHtml(phone.trim())}`,
`<b>حوزه مشاوره:</b> ${escapeHtml(area.trim())}`,
]
if (description?.trim()) {
lines.push('', '<b>توضیحات:</b>', escapeHtml(description.trim()))
}
const text = lines.join('\n')
try {
const res = await fetch(`${BALE_API}/bot${token}/sendMessage`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
chat_id: chatId,
text,
parse_mode: 'HTML',
}),
})
const data = await res.json().catch(() => ({}))
if (!res.ok) {
return NextResponse.json(
{ error: data.description || 'ارسال به بله ناموفق بود' },
{ status: 502 }
)
}
return NextResponse.json({ ok: true })
} catch {
return NextResponse.json({ error: 'خطا در ارتباط با بله' }, { status: 502 })
}
}