UNPKG

gramio

Version:

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

97 lines (92 loc) 2.96 kB
import debug from '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, callSite) { super(error.description); this.name = method; this.method = method; this.params = params; this.code = error.error_code; if (error.parameters) this.payload = error.parameters; if (callSite?.stack) { const callSiteLines = callSite.stack.split("\n"); const relevantFrames = callSiteLines.slice(1); this.stack = `${this.name}: ${this.message} ${relevantFrames.join("\n")}`; } } } 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 simpleHash(str) { let hash = 5381; for (let i = 0; i < str.length; i++) { hash = (hash << 5) + hash + str.charCodeAt(i) | 0; } return (hash >>> 0).toString(36); } 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 { value: await fn(), caught: false }; } catch (error) { return { value: error, caught: true }; } } async function withRetries(resultPromise) { let state = await suppressError(resultPromise); while (state.value instanceof TelegramError) { const retryAfter = state.value.payload?.retry_after; if (retryAfter) { await sleep(retryAfter * 1e3); state = await suppressError(resultPromise); } else { if (state.caught) throw state.value; return state.value; } } if (state.caught) throw state.value; return state.value; } export { ErrorKind as E, IS_BUN as I, TelegramError as T, simpleHash as a, simplifyObject as b, debug$updates as d, sleep as s, timeoutWebhook as t, withRetries as w };