UNPKG

gramio

Version:

Powerful, extensible and really type-safe Telegram Bot API framework

93 lines (87 loc) 2.66 kB
'use strict'; var debug = require('debug'); const ErrorKind = Symbol("ErrorKind"); class TelegramError extends Error { /** Name of the API Method */ method; /** Params that were sent */ params; /** See {@link TelegramAPIResponseError.error_code}*/ code; /** Describes why a request was unsuccessful. */ payload; /** Construct new TelegramError */ constructor(error, method, params) { super(error.description); this.name = method; this.method = method; this.params = params; this.code = error.error_code; if (error.parameters) this.payload = error.parameters; } } TelegramError.constructor[ErrorKind] = "TELEGRAM"; const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); function convertToString(value) { const typeOfValue = typeof value; if (typeOfValue === "string") return value; if (typeOfValue === "object") return JSON.stringify(value); return String(value); } function simplifyObject(obj) { const result = {}; for (const [key, value] of Object.entries(obj)) { const typeOfValue = typeof value; if (value === void 0 || value === null || typeOfValue === "function") continue; result[key] = convertToString(value); } return result; } const IS_BUN = typeof Bun !== "undefined"; debug("gramio:api"); const debug$updates = debug("gramio:updates"); function timeoutWebhook(task, timeout, mode) { return new Promise((resolve, reject) => { const timeoutTask = setTimeout(() => { if (mode === "throw") { reject( new Error(`Webhook handler execution timed out after ${timeout}ms`) ); } else { resolve(void 0); } }, timeout); task.then(resolve).catch(reject).finally(() => clearTimeout(timeoutTask)); }); } async function suppressError(fn) { try { return [await fn(), false]; } catch (error) { return [error, true]; } } async function withRetries(resultPromise) { let [result, isFromCatch] = await suppressError(resultPromise); while (result instanceof TelegramError) { const retryAfter = result.payload?.retry_after; if (retryAfter) { await sleep(retryAfter * 1e3); [result, isFromCatch] = await suppressError(resultPromise); } else { if (isFromCatch) throw result; return result; } } if (result instanceof Error && isFromCatch) throw result; return result; } exports.ErrorKind = ErrorKind; exports.IS_BUN = IS_BUN; exports.TelegramError = TelegramError; exports.debug$updates = debug$updates; exports.simplifyObject = simplifyObject; exports.sleep = sleep; exports.timeoutWebhook = timeoutWebhook; exports.withRetries = withRetries;