grammy-tools 1.36.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +339 -0
  3. package/out/bot.d.ts +314 -0
  4. package/out/bot.js +669 -0
  5. package/out/composer.d.ts +764 -0
  6. package/out/composer.js +704 -0
  7. package/out/context.d.ts +1618 -0
  8. package/out/context.js +1976 -0
  9. package/out/convenience/constants.d.ts +98 -0
  10. package/out/convenience/constants.js +37 -0
  11. package/out/convenience/frameworks.d.ts +216 -0
  12. package/out/convenience/frameworks.js +370 -0
  13. package/out/convenience/inline_query.d.ts +401 -0
  14. package/out/convenience/inline_query.js +461 -0
  15. package/out/convenience/input_media.d.ts +72 -0
  16. package/out/convenience/input_media.js +82 -0
  17. package/out/convenience/keyboard.d.ts +763 -0
  18. package/out/convenience/keyboard.js +935 -0
  19. package/out/convenience/session.d.ts +345 -0
  20. package/out/convenience/session.js +455 -0
  21. package/out/convenience/webhook.d.ts +59 -0
  22. package/out/convenience/webhook.js +80 -0
  23. package/out/core/api.d.ts +1628 -0
  24. package/out/core/api.js +1907 -0
  25. package/out/core/client.d.ts +180 -0
  26. package/out/core/client.js +226 -0
  27. package/out/core/error.d.ts +53 -0
  28. package/out/core/error.js +87 -0
  29. package/out/core/payload.d.ts +39 -0
  30. package/out/core/payload.js +199 -0
  31. package/out/filter.d.ts +959 -0
  32. package/out/filter.js +378 -0
  33. package/out/mod.d.ts +14 -0
  34. package/out/mod.js +43 -0
  35. package/out/platform.node.d.ts +16 -0
  36. package/out/platform.node.js +43 -0
  37. package/out/shim.node.d.ts +2 -0
  38. package/out/shim.node.js +7 -0
  39. package/out/types.d.ts +1 -0
  40. package/out/types.js +17 -0
  41. package/out/types.node.d.ts +78 -0
  42. package/out/types.node.js +107 -0
  43. package/out/web.d.ts +1 -0
  44. package/out/web.mjs +5172 -0
  45. package/package.json +71 -0
@@ -0,0 +1,180 @@
1
+ import { type ApiMethods as Telegram, type ApiResponse, type Opts } from "../types.js";
2
+ export type Methods<R extends RawApi> = string & keyof R;
3
+ /**
4
+ * Represents the raw Telegram Bot API with all methods specified 1:1 as
5
+ * documented on the website (https://core.telegram.org/bots/api).
6
+ *
7
+ * Every method takes an optional `AbortSignal` object that allows to cancel the
8
+ * API call if desired.
9
+ */
10
+ export type RawApi = {
11
+ [M in keyof Telegram]: Parameters<Telegram[M]>[0] extends undefined ? (signal?: AbortSignal) => Promise<ReturnType<Telegram[M]>> : (args: Opts<M>, signal?: AbortSignal) => Promise<ReturnType<Telegram[M]>>;
12
+ };
13
+ export type Payload<M extends Methods<R>, R extends RawApi> = M extends unknown ? R[M] extends (signal?: AbortSignal) => unknown ? {} : R[M] extends (args: any, signal?: AbortSignal) => unknown ? Parameters<R[M]>[0] : never : never;
14
+ /**
15
+ * Small utility interface that abstracts from webhook reply calls of different
16
+ * web frameworks.
17
+ */
18
+ export interface WebhookReplyEnvelope {
19
+ send?: (payload: string) => void | Promise<void>;
20
+ }
21
+ /**
22
+ * Type of a function that can perform an API call. Used for Transformers.
23
+ */
24
+ export type ApiCallFn<R extends RawApi = RawApi> = <M extends Methods<R>>(method: M, payload: Payload<M, R>, signal?: AbortSignal) => Promise<ApiResponse<ApiCallResult<M, R>>>;
25
+ type ApiCallResult<M extends Methods<R>, R extends RawApi> = R[M] extends (...args: unknown[]) => unknown ? Awaited<ReturnType<R[M]>> : never;
26
+ /**
27
+ * API call transformers are functions that can access and modify the method and
28
+ * payload of an API call on the fly. This can be useful if you want to
29
+ * implement rate limiting or other things against the Telegram Bot API.
30
+ *
31
+ * Confer the grammY
32
+ * [documentation](https://grammy.dev/advanced/transformers) to read more
33
+ * about how to use transformers.
34
+ */
35
+ export type Transformer<R extends RawApi = RawApi> = <M extends Methods<R>>(prev: ApiCallFn<R>, method: M, payload: Payload<M, R>, signal?: AbortSignal) => Promise<ApiResponse<ApiCallResult<M, R>>>;
36
+ export type TransformerConsumer<R extends RawApi = RawApi> = TransformableApi<R>["use"];
37
+ /**
38
+ * A transformable API enhances the `RawApi` type by transformers.
39
+ */
40
+ export interface TransformableApi<R extends RawApi = RawApi> {
41
+ /**
42
+ * Access to the raw API that the transformers will be installed on.
43
+ */
44
+ raw: R;
45
+ /**
46
+ * Can be used to register any number of transformers on the API.
47
+ */
48
+ use: (...transformers: Transformer<R>[]) => this;
49
+ /**
50
+ * Returns a readonly list or the currently installed transformers. The list
51
+ * is sorted by time of installation where index 0 represents the
52
+ * transformer that was installed first.
53
+ */
54
+ installedTransformers: Transformer<R>[];
55
+ }
56
+ /**
57
+ * Options to pass to the API client that eventually connects to the Telegram
58
+ * Bot API server and makes the HTTP requests.
59
+ */
60
+ export interface ApiClientOptions {
61
+ /**
62
+ * Root URL of the Telegram Bot API server. Default:
63
+ * https://api.telegram.org
64
+ */
65
+ apiRoot?: string;
66
+ /**
67
+ * Specifies whether to use the [test
68
+ * environment](https://core.telegram.org/bots/webapps#using-bots-in-the-test-environment).
69
+ * Can be either `"prod"` (default) or `"test"`.
70
+ *
71
+ * The testing infrastructure is separate from the regular production
72
+ * infrastructure. No chats, accounts, or other data is shared between them.
73
+ * If you set this option to `"test"`, you will need to make your Telegram
74
+ * client connect to the testing data centers of Telegram, register your
75
+ * phone number again, open a new chat with @BotFather, and create a
76
+ * separate bot.
77
+ */
78
+ environment?: "prod" | "test";
79
+ /**
80
+ * URL builder function for API calls. Can be used to modify which API
81
+ * server should be called.
82
+ *
83
+ * @param root The URL that was passed in `apiRoot`, or its default value
84
+ * @param token The bot's token that was passed when creating the bot
85
+ * @param method The API method to be called, e.g. `getMe`
86
+ * @param env The value that was passed in `environment`, or its default value
87
+ * @returns The URL that will be fetched during the API call
88
+ */
89
+ buildUrl?: (root: string, token: string, method: string, env: "prod" | "test") => string | URL;
90
+ /**
91
+ * Maximum number of seconds that a request to the Bot API server may take.
92
+ * If a request has not completed before this time has elapsed, grammY
93
+ * aborts the request and errors. Without such a timeout, networking issues
94
+ * may cause your bot to leave open a connection indefinitely, which may
95
+ * effectively make your bot freeze.
96
+ *
97
+ * You probably do not have to care about this option. In rare cases, you
98
+ * may want to adjust it if you are transferring large files via slow
99
+ * connections to your own Bot API server.
100
+ *
101
+ * The default number of seconds is `500`, which corresponds to 8 minutes
102
+ * and 20 seconds. Note that this is also the value that is hard-coded in
103
+ * the official Bot API server, so you cannot perform any successful
104
+ * requests that exceed this time frame (even if you would allow it in
105
+ * grammY). Setting this option to higher than the default only makes sense
106
+ * with a custom Bot API server.
107
+ */
108
+ timeoutSeconds?: number;
109
+ /**
110
+ * If the bot is running on webhooks, as soon as the bot receives an update
111
+ * from Telegram, it is possible to make up to one API call in the response
112
+ * to the webhook request. As a benefit, this saves your bot from making up
113
+ * to one HTTP request per update. However, there are a number of drawbacks
114
+ * to using this:
115
+ * 1) You will not be able to handle potential errors of the respective API
116
+ * call. This includes rate limiting errors, so sent messages can be
117
+ * swallowed by the Bot API server and there is no way to detect if a
118
+ * message was actually sent or not.
119
+ * 2) More importantly, you also won't have access to the response object,
120
+ * so e.g. calling `sendMessage` will not give you access to the message
121
+ * you sent.
122
+ * 3) Furthermore, it is not possible to cancel the request. The
123
+ * `AbortSignal` will be disregarded.
124
+ * 4) Note also that the types in grammY do not reflect the consequences of
125
+ * a performed webhook callback! For instance, they indicate that you
126
+ * always receive a response object, so it is your own responsibility to
127
+ * make sure you're not screwing up while using this minor performance
128
+ * optimization.
129
+ *
130
+ * With this warning out of the way, here is what you can do with the
131
+ * `canUseWebhookReply` option: it can be used to pass a function that
132
+ * determines whether to use webhook reply for the given method. It will
133
+ * only be invoked if the payload can be sent as JSON. It will not be
134
+ * invoked again for a given update after it returned `true`, indicating
135
+ * that the API call should be performed as a webhook send. In other words,
136
+ * subsequent API calls (during the same update) will always perform their
137
+ * own HTTP requests.
138
+ *
139
+ * @param method The method to call
140
+ */
141
+ canUseWebhookReply?: (method: string) => boolean;
142
+ /**
143
+ * Base configuration for `fetch` calls. Specify any additional parameters
144
+ * to use when fetching a method of the Telegram Bot API. Default: `{
145
+ * compress: true }` (Node), `{}` (Deno)
146
+ */
147
+ baseFetchConfig?: Omit<NonNullable<Parameters<typeof fetch>[1]>, "method" | "headers" | "body">;
148
+ /**
149
+ * `fetch` function to use for making HTTP requests. Default: `node-fetch` in Node.js, `fetch` in Deno.
150
+ */
151
+ fetch?: typeof fetch;
152
+ /**
153
+ * When the network connection is unreliable and some API requests fail
154
+ * because of that, grammY will throw errors that tell you exactly which
155
+ * requests failed. However, the error messages do not disclose the fetched
156
+ * URL as it contains your bot's token. Logging it may lead to token leaks.
157
+ *
158
+ * If you are sure that no logs are ever posted in Telegram chats, GitHub
159
+ * issues, or otherwise shared, you can set this option to `true` in order
160
+ * to obtain more detailed logs that may help you debug your bot. The
161
+ * default value is `false`, meaning that the bot token is not logged.
162
+ */
163
+ sensitiveLogs?: boolean;
164
+ }
165
+ /**
166
+ * Creates a new transformable API, i.e. an object that lets you perform raw API
167
+ * calls to the Telegram Bot API server but pass the calls through a stack of
168
+ * transformers before. This will create a new API client instance under the
169
+ * hood that will be used to connect to the Telegram servers. You therefore need
170
+ * to pass the bot token. In addition, you may pass API client options as well
171
+ * as a webhook reply envelope that allows the client to perform up to one HTTP
172
+ * request in response to a webhook call if this is desired.
173
+ *
174
+ * @param token The bot's token
175
+ * @param options A number of options to pass to the created API client
176
+ * @param webhookReplyEnvelope The webhook reply envelope that will be used
177
+ */
178
+ export declare function createRawApi<R extends RawApi>(token: string, options?: ApiClientOptions, webhookReplyEnvelope?: WebhookReplyEnvelope): TransformableApi<R>;
179
+ import { AbortSignal, fetch } from "./../shim.node.js";
180
+ export {};
@@ -0,0 +1,226 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createRawApi = createRawApi;
4
+ const platform_node_js_1 = require("../platform.node.js");
5
+ const error_js_1 = require("./error.js");
6
+ const payload_js_1 = require("./payload.js");
7
+ const debug = (0, platform_node_js_1.debug)("grammy:core");
8
+ // Transformer base functions
9
+ function concatTransformer(prev, trans) {
10
+ return (method, payload, signal) => trans(prev, method, payload, signal);
11
+ }
12
+ class ApiClient {
13
+ constructor(token, options = {}, webhookReplyEnvelope = {}) {
14
+ var _a, _b, _c, _d, _e, _f;
15
+ this.token = token;
16
+ this.webhookReplyEnvelope = webhookReplyEnvelope;
17
+ this.hasUsedWebhookReply = false;
18
+ this.installedTransformers = [];
19
+ this.call = async (method, p, signal) => {
20
+ const payload = p !== null && p !== void 0 ? p : {};
21
+ debug(`Calling ${method}`);
22
+ if (signal !== undefined)
23
+ validateSignal(method, payload, signal);
24
+ // General config
25
+ const opts = this.options;
26
+ const formDataRequired = (0, payload_js_1.requiresFormDataUpload)(payload);
27
+ // Short-circuit on webhook reply
28
+ if (this.webhookReplyEnvelope.send !== undefined &&
29
+ !this.hasUsedWebhookReply &&
30
+ !formDataRequired &&
31
+ opts.canUseWebhookReply(method)) {
32
+ this.hasUsedWebhookReply = true;
33
+ const config = (0, payload_js_1.createJsonPayload)({ ...payload, method });
34
+ await this.webhookReplyEnvelope.send(config.body);
35
+ return { ok: true, result: true };
36
+ }
37
+ // Handle timeouts and errors in the underlying form-data stream
38
+ const controller = createAbortControllerFromSignal(signal);
39
+ const timeout = createTimeout(controller, opts.timeoutSeconds, method);
40
+ const streamErr = createStreamError(controller);
41
+ // Build request URL and config
42
+ const url = opts.buildUrl(opts.apiRoot, this.token, method, opts.environment);
43
+ const config = formDataRequired
44
+ ? (0, payload_js_1.createFormDataPayload)(payload, (err) => streamErr.catch(err))
45
+ : (0, payload_js_1.createJsonPayload)(payload);
46
+ const sig = controller.signal;
47
+ const options = { ...opts.baseFetchConfig, signal: sig, ...config };
48
+ // Perform fetch call, and handle networking errors
49
+ const successPromise = this.fetch(url instanceof URL ? url.href : url, options).catch((0, error_js_1.toHttpError)(method, opts.sensitiveLogs));
50
+ // Those are the three possible outcomes of the fetch call:
51
+ const operations = [successPromise, streamErr.promise, timeout.promise];
52
+ // Wait for result
53
+ try {
54
+ const res = await Promise.race(operations);
55
+ return await res.json();
56
+ }
57
+ finally {
58
+ if (timeout.handle !== undefined)
59
+ clearTimeout(timeout.handle);
60
+ }
61
+ };
62
+ const apiRoot = (_a = options.apiRoot) !== null && _a !== void 0 ? _a : "https://api.telegram.org";
63
+ const environment = (_b = options.environment) !== null && _b !== void 0 ? _b : "prod";
64
+ // In an ideal world, `fetch` is independent of the context being called,
65
+ // but in a Cloudflare worker, any context other than global throws an error.
66
+ // That is why we need to call custom fetch or fetch without context.
67
+ const { fetch: customFetch } = options;
68
+ const fetchFn = customFetch !== null && customFetch !== void 0 ? customFetch : shim_node_js_1.fetch;
69
+ this.options = {
70
+ apiRoot,
71
+ environment,
72
+ buildUrl: (_c = options.buildUrl) !== null && _c !== void 0 ? _c : defaultBuildUrl,
73
+ timeoutSeconds: (_d = options.timeoutSeconds) !== null && _d !== void 0 ? _d : 500,
74
+ baseFetchConfig: {
75
+ ...(0, platform_node_js_1.baseFetchConfig)(apiRoot),
76
+ ...options.baseFetchConfig,
77
+ },
78
+ canUseWebhookReply: (_e = options.canUseWebhookReply) !== null && _e !== void 0 ? _e : (() => false),
79
+ sensitiveLogs: (_f = options.sensitiveLogs) !== null && _f !== void 0 ? _f : false,
80
+ fetch: ((...args) => fetchFn(...args)),
81
+ };
82
+ this.fetch = this.options.fetch;
83
+ if (this.options.apiRoot.endsWith("/")) {
84
+ throw new Error(`Remove the trailing '/' from the 'apiRoot' option (use '${this.options.apiRoot.substring(0, this.options.apiRoot.length - 1)}' instead of '${this.options.apiRoot}')`);
85
+ }
86
+ }
87
+ use(...transformers) {
88
+ this.call = transformers.reduce(concatTransformer, this.call);
89
+ this.installedTransformers.push(...transformers);
90
+ return this;
91
+ }
92
+ async callApi(method, payload, signal) {
93
+ const data = await this.call(method, payload, signal);
94
+ if (data.ok)
95
+ return data.result;
96
+ else
97
+ throw (0, error_js_1.toGrammyError)(data, method, payload);
98
+ }
99
+ }
100
+ /**
101
+ * Creates a new transformable API, i.e. an object that lets you perform raw API
102
+ * calls to the Telegram Bot API server but pass the calls through a stack of
103
+ * transformers before. This will create a new API client instance under the
104
+ * hood that will be used to connect to the Telegram servers. You therefore need
105
+ * to pass the bot token. In addition, you may pass API client options as well
106
+ * as a webhook reply envelope that allows the client to perform up to one HTTP
107
+ * request in response to a webhook call if this is desired.
108
+ *
109
+ * @param token The bot's token
110
+ * @param options A number of options to pass to the created API client
111
+ * @param webhookReplyEnvelope The webhook reply envelope that will be used
112
+ */
113
+ function createRawApi(token, options, webhookReplyEnvelope) {
114
+ const client = new ApiClient(token, options, webhookReplyEnvelope);
115
+ const proxyHandler = {
116
+ get(_, m) {
117
+ return m === "toJSON"
118
+ ? "__internal"
119
+ // Methods with zero parameters are called without any payload,
120
+ // so we have to manually inject an empty payload.
121
+ : m === "getMe" ||
122
+ m === "getWebhookInfo" ||
123
+ m === "getForumTopicIconStickers" ||
124
+ m === "getAvailableGifts" ||
125
+ m === "logOut" ||
126
+ m === "close"
127
+ ? client.callApi.bind(client, m, {})
128
+ : client.callApi.bind(client, m);
129
+ },
130
+ ...proxyMethods,
131
+ };
132
+ const raw = new Proxy({}, proxyHandler);
133
+ const installedTransformers = client.installedTransformers;
134
+ const api = {
135
+ raw,
136
+ installedTransformers,
137
+ use: (...t) => {
138
+ client.use(...t);
139
+ return api;
140
+ },
141
+ };
142
+ return api;
143
+ }
144
+ const defaultBuildUrl = (root, token, method, env) => {
145
+ const prefix = env === "test" ? "test/" : "";
146
+ return `${root}/bot${token}/${prefix}${method}`;
147
+ };
148
+ const proxyMethods = {
149
+ set() {
150
+ return false;
151
+ },
152
+ defineProperty() {
153
+ return false;
154
+ },
155
+ deleteProperty() {
156
+ return false;
157
+ },
158
+ ownKeys() {
159
+ return [];
160
+ },
161
+ };
162
+ /** Creates a timeout error which aborts a given controller */
163
+ function createTimeout(controller, seconds, method) {
164
+ let handle = undefined;
165
+ const promise = new Promise((_, reject) => {
166
+ handle = setTimeout(() => {
167
+ const msg = `Request to '${method}' timed out after ${seconds} seconds`;
168
+ reject(new Error(msg));
169
+ controller.abort();
170
+ }, 1000 * seconds);
171
+ });
172
+ return { promise, handle };
173
+ }
174
+ /** Creates a stream error which abort a given controller */
175
+ function createStreamError(abortController) {
176
+ let onError = (err) => {
177
+ // Re-throw by default, but will be overwritten immediately
178
+ throw err;
179
+ };
180
+ const promise = new Promise((_, reject) => {
181
+ onError = (err) => {
182
+ reject(err);
183
+ abortController.abort();
184
+ };
185
+ });
186
+ return { promise, catch: onError };
187
+ }
188
+ function createAbortControllerFromSignal(signal) {
189
+ const abortController = new shim_node_js_1.AbortController();
190
+ if (signal === undefined)
191
+ return abortController;
192
+ const sig = signal;
193
+ function abort() {
194
+ abortController.abort();
195
+ sig.removeEventListener("abort", abort);
196
+ }
197
+ if (sig.aborted)
198
+ abort();
199
+ else
200
+ sig.addEventListener("abort", abort);
201
+ return { abort, signal: abortController.signal };
202
+ }
203
+ function validateSignal(method, payload, signal) {
204
+ // We use a very simple heuristic to check for AbortSignal instances
205
+ // in order to avoid doing a runtime-specific version of `instanceof`.
206
+ if (typeof (signal === null || signal === void 0 ? void 0 : signal.addEventListener) === "function") {
207
+ return;
208
+ }
209
+ let payload0 = JSON.stringify(payload);
210
+ if (payload0.length > 20) {
211
+ payload0 = payload0.substring(0, 16) + " ...";
212
+ }
213
+ let payload1 = JSON.stringify(signal);
214
+ if (payload1.length > 20) {
215
+ payload1 = payload1.substring(0, 16) + " ...";
216
+ }
217
+ throw new Error(`Incorrect abort signal instance found! \
218
+ You passed two payloads to '${method}' but you should merge \
219
+ the second one containing '${payload1}' into the first one \
220
+ containing '${payload0}'! If you are using context shortcuts, \
221
+ you may want to use a method on 'ctx.api' instead.
222
+
223
+ If you want to prevent such mistakes in the future, \
224
+ consider using TypeScript. https://www.typescriptlang.org/`);
225
+ }
226
+ const shim_node_js_1 = require("./../shim.node.js");
@@ -0,0 +1,53 @@
1
+ import { type ApiError, type ResponseParameters } from "../types.js";
2
+ /**
3
+ * This class represents errors that are thrown by grammY because the Telegram
4
+ * Bot API responded with an error.
5
+ *
6
+ * Instances of this class hold the information that the Telegram backend
7
+ * returned.
8
+ *
9
+ * If this error is thrown, grammY could successfully communicate with the
10
+ * Telegram Bot API servers, however, an error code was returned for the
11
+ * respective method call.
12
+ */
13
+ export declare class GrammyError extends Error implements ApiError {
14
+ /** The called method name which caused this error to be thrown. */
15
+ readonly method: string;
16
+ /** The payload that was passed when calling the method. */
17
+ readonly payload: Record<string, unknown>;
18
+ /** Flag that this request was unsuccessful. Always `false`. */
19
+ readonly ok: false;
20
+ /** An integer holding Telegram's error code. Subject to change. */
21
+ readonly error_code: number;
22
+ /** A human-readable description of the error. */
23
+ readonly description: string;
24
+ /** Further parameters that may help to automatically handle the error. */
25
+ readonly parameters: ResponseParameters;
26
+ constructor(message: string, err: ApiError,
27
+ /** The called method name which caused this error to be thrown. */
28
+ method: string,
29
+ /** The payload that was passed when calling the method. */
30
+ payload: Record<string, unknown>);
31
+ }
32
+ export declare function toGrammyError(err: ApiError, method: string, payload: Record<string, unknown>): GrammyError;
33
+ /**
34
+ * This class represents errors that are thrown by grammY because an HTTP call
35
+ * to the Telegram Bot API failed.
36
+ *
37
+ * Instances of this class hold the error object that was created because the
38
+ * fetch call failed. It can be inspected to determine why exactly the network
39
+ * request failed.
40
+ *
41
+ * If an [API transformer
42
+ * function](https://grammy.dev/advanced/transformers) throws an error,
43
+ * grammY will regard this as if the network request failed. The contained error
44
+ * will then be the error that was thrown by the transformer function.
45
+ */
46
+ export declare class HttpError extends Error {
47
+ /** The thrown error object. */
48
+ readonly error: unknown;
49
+ constructor(message: string,
50
+ /** The thrown error object. */
51
+ error: unknown);
52
+ }
53
+ export declare function toHttpError(method: string, sensitiveLogs: boolean): (err: unknown) => never;
@@ -0,0 +1,87 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.HttpError = exports.GrammyError = void 0;
4
+ exports.toGrammyError = toGrammyError;
5
+ exports.toHttpError = toHttpError;
6
+ const platform_node_js_1 = require("../platform.node.js");
7
+ const debug = (0, platform_node_js_1.debug)("grammy:warn");
8
+ /**
9
+ * This class represents errors that are thrown by grammY because the Telegram
10
+ * Bot API responded with an error.
11
+ *
12
+ * Instances of this class hold the information that the Telegram backend
13
+ * returned.
14
+ *
15
+ * If this error is thrown, grammY could successfully communicate with the
16
+ * Telegram Bot API servers, however, an error code was returned for the
17
+ * respective method call.
18
+ */
19
+ class GrammyError extends Error {
20
+ constructor(message, err,
21
+ /** The called method name which caused this error to be thrown. */
22
+ method,
23
+ /** The payload that was passed when calling the method. */
24
+ payload) {
25
+ var _a;
26
+ super(`${message} (${err.error_code}: ${err.description})`);
27
+ this.method = method;
28
+ this.payload = payload;
29
+ /** Flag that this request was unsuccessful. Always `false`. */
30
+ this.ok = false;
31
+ this.name = "GrammyError";
32
+ this.error_code = err.error_code;
33
+ this.description = err.description;
34
+ this.parameters = (_a = err.parameters) !== null && _a !== void 0 ? _a : {};
35
+ }
36
+ }
37
+ exports.GrammyError = GrammyError;
38
+ function toGrammyError(err, method, payload) {
39
+ switch (err.error_code) {
40
+ case 401:
41
+ debug("Error 401 means that your bot token is wrong, talk to https://t.me/BotFather to check it.");
42
+ break;
43
+ case 409:
44
+ debug("Error 409 means that you are running your bot several times on long polling. Consider revoking the bot token if you believe that no other instance is running.");
45
+ break;
46
+ }
47
+ return new GrammyError(`Call to '${method}' failed!`, err, method, payload);
48
+ }
49
+ /**
50
+ * This class represents errors that are thrown by grammY because an HTTP call
51
+ * to the Telegram Bot API failed.
52
+ *
53
+ * Instances of this class hold the error object that was created because the
54
+ * fetch call failed. It can be inspected to determine why exactly the network
55
+ * request failed.
56
+ *
57
+ * If an [API transformer
58
+ * function](https://grammy.dev/advanced/transformers) throws an error,
59
+ * grammY will regard this as if the network request failed. The contained error
60
+ * will then be the error that was thrown by the transformer function.
61
+ */
62
+ class HttpError extends Error {
63
+ constructor(message,
64
+ /** The thrown error object. */
65
+ error) {
66
+ super(message);
67
+ this.error = error;
68
+ this.name = "HttpError";
69
+ }
70
+ }
71
+ exports.HttpError = HttpError;
72
+ function isTelegramError(err) {
73
+ return (typeof err === "object" &&
74
+ err !== null &&
75
+ "status" in err &&
76
+ "statusText" in err);
77
+ }
78
+ function toHttpError(method, sensitiveLogs) {
79
+ return (err) => {
80
+ let msg = `Network request for '${method}' failed!`;
81
+ if (isTelegramError(err))
82
+ msg += ` (${err.status}: ${err.statusText})`;
83
+ if (sensitiveLogs && err instanceof Error)
84
+ msg += ` ${err.message}`;
85
+ throw new HttpError(msg, err);
86
+ };
87
+ }
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Determines for a given payload if it may be sent as JSON, or if it has to be
3
+ * uploaded via multipart/form-data. Returns `true` in the latter case and
4
+ * `false` in the former.
5
+ *
6
+ * @param payload The payload to analyze
7
+ */
8
+ export declare function requiresFormDataUpload(payload: unknown): boolean;
9
+ /**
10
+ * Turns a payload into an options object that can be passed to a `fetch` call
11
+ * by setting the necessary headers and method. May only be called for payloads
12
+ * `P` that let `requiresFormDataUpload(P)` return `false`.
13
+ *
14
+ * @param payload The payload to wrap
15
+ */
16
+ export declare function createJsonPayload(payload: Record<string, unknown>): {
17
+ method: string;
18
+ headers: {
19
+ "content-type": string;
20
+ connection: string;
21
+ };
22
+ body: string;
23
+ };
24
+ /**
25
+ * Turns a payload into an options object that can be passed to a `fetch` call
26
+ * by setting the necessary headers and method. Note that this method creates a
27
+ * multipart/form-data stream under the hood. If possible, a JSON payload should
28
+ * be created instead for performance reasons.
29
+ *
30
+ * @param payload The payload to wrap
31
+ */
32
+ export declare function createFormDataPayload(payload: Record<string, unknown>, onError: (err: unknown) => void): {
33
+ method: string;
34
+ headers: {
35
+ "content-type": string;
36
+ connection: string;
37
+ };
38
+ body: import("stream").Readable;
39
+ };