101 lines
3.3 KiB
TypeScript
101 lines
3.3 KiB
TypeScript
export interface TelegramNotifierOptions {
|
|
botToken?: string | (() => string | undefined) | undefined;
|
|
chatId?: string | (() => string | undefined) | undefined;
|
|
delayMs?: number;
|
|
maxRetries?: number;
|
|
fetchFn?: typeof fetch;
|
|
}
|
|
|
|
export class TelegramNotifier {
|
|
private readonly botToken: string | (() => string | undefined) | undefined;
|
|
private readonly chatId: string | (() => string | undefined) | undefined;
|
|
private readonly delayMs: number;
|
|
private readonly maxRetries: number;
|
|
private readonly fetchFn: typeof fetch;
|
|
private lastSendTime = 0;
|
|
|
|
constructor(options: TelegramNotifierOptions = {}) {
|
|
this.botToken = options.botToken;
|
|
this.chatId = options.chatId;
|
|
this.delayMs = options.delayMs ?? 500;
|
|
this.maxRetries = options.maxRetries ?? 3;
|
|
this.fetchFn = options.fetchFn ?? globalThis.fetch;
|
|
}
|
|
|
|
private getBotToken(): string | undefined {
|
|
return typeof this.botToken === "function" ? this.botToken() : this.botToken;
|
|
}
|
|
|
|
private getChatId(): string | undefined {
|
|
return typeof this.chatId === "function" ? this.chatId() : this.chatId;
|
|
}
|
|
|
|
async sendMessage(htmlText: string, overrideChatId?: string): Promise<boolean> {
|
|
const token = this.getBotToken();
|
|
const defaultChatId = this.getChatId();
|
|
const targetChatId = overrideChatId ?? defaultChatId;
|
|
|
|
if (!token || !targetChatId) {
|
|
console.warn("[TelegramNotifier] Não configurado. Mensagem não enviada.");
|
|
return false;
|
|
}
|
|
|
|
await this.paceSend();
|
|
|
|
const url = `https://api.telegram.org/bot${token}/sendMessage`;
|
|
const body = JSON.stringify({
|
|
chat_id: targetChatId,
|
|
text: htmlText,
|
|
parse_mode: "HTML",
|
|
disable_web_page_preview: true,
|
|
});
|
|
|
|
let attempt = 0;
|
|
while (attempt < this.maxRetries) {
|
|
attempt++;
|
|
try {
|
|
const response = await this.fetchFn(url, {
|
|
method: "POST",
|
|
headers: { "content-type": "application/json" },
|
|
signal: AbortSignal.timeout(15_000),
|
|
body,
|
|
});
|
|
|
|
if (response.ok) {
|
|
this.lastSendTime = Date.now();
|
|
return true;
|
|
}
|
|
|
|
if (response.status === 429) {
|
|
const errData = (await response.json().catch(() => ({}))) as any;
|
|
const retryAfterSec = errData?.parameters?.retry_after ?? 1;
|
|
const waitMs = Math.ceil(retryAfterSec * 1000) + 100;
|
|
await new Promise((resolve) => setTimeout(resolve, waitMs));
|
|
continue;
|
|
}
|
|
|
|
const errText = await response.text().catch(() => "");
|
|
console.error(`[TelegramNotifier] Erro ${response.status}: ${errText}`);
|
|
|
|
// Erros de cliente não recuperáveis (ex: 400 chat not found, 403 bot blocked, 404 bot not found)
|
|
if (response.status >= 400 && response.status < 500) {
|
|
break;
|
|
}
|
|
} catch (err: any) {
|
|
console.error(`[TelegramNotifier] Falha tentativa ${attempt}:`, err?.message);
|
|
await new Promise((resolve) => setTimeout(resolve, 300 * attempt));
|
|
}
|
|
}
|
|
|
|
return false;
|
|
}
|
|
|
|
private async paceSend(): Promise<void> {
|
|
if (this.delayMs <= 0) return;
|
|
const now = Date.now();
|
|
const elapsed = now - this.lastSendTime;
|
|
if (elapsed < this.delayMs) {
|
|
await new Promise((resolve) => setTimeout(resolve, this.delayMs - elapsed));
|
|
}
|
|
}
|
|
} |