Files
MikrotikManager/backend/src/services/alerts-telegram-send.ts
T

14 lines
1.5 KiB
TypeScript

type Payload={chat_id:string;text:string;message_thread_id?:number}
export type TelegramSendResult={ok:true}|{ok:false;outcome:"rejected"|"unknown";error:string}
export async function sendTelegramRequest(token:string,payload:Payload,fetcher:typeof fetch=fetch):Promise<TelegramSendResult>{
const redact=(message:string)=>message.replaceAll(token,"[TOKEN]").replaceAll(encodeURIComponent(token),"[TOKEN]")
try{
const response=await fetcher("https://api.telegram.org/bot"+encodeURIComponent(token)+"/sendMessage",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(payload),signal:AbortSignal.timeout(30_000)})
const raw:unknown=await response.json().catch(()=>undefined)
if(response.ok&&typeof raw==="object"&&raw!==null&&"ok" in raw&&raw.ok===true)return {ok:true}
const description=typeof raw==="object"&&raw!==null&&"description" in raw&&typeof raw.description==="string"?raw.description:"Telegram не подтвердил приём сообщения"
const rejected=typeof raw==="object"&&raw!==null&&"ok" in raw&&raw.ok===false&&"error_code" in raw&&typeof raw.error_code==="number"&&Number.isInteger(raw.error_code)&&raw.error_code>=400&&raw.error_code<600&&"description" in raw&&typeof raw.description==="string"
return {ok:false,outcome:rejected?"rejected":"unknown",error:redact(description)}
}catch{return {ok:false,outcome:"unknown",error:"Результат отправки в Telegram неизвестен: ответ не получен"}}
}