gramio 0.0.26 → 0.0.28

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.
package/dist/bot.d.ts CHANGED
@@ -2,14 +2,14 @@ import { CallbackData } from "@gramio/callback-data";
2
2
  import type { Context, ContextType, MaybeArray, UpdateName } from "@gramio/contexts";
3
3
  import type { APIMethodParams, APIMethods, SetMyCommandsParams, TelegramBotCommand, TelegramReactionTypeEmojiEmoji, TelegramUser } from "@gramio/types";
4
4
  import { Plugin } from "./plugin";
5
- import type { BotOptions, DeriveDefinitions, ErrorDefinitions, Handler, Hooks, MaybePromise } from "./types";
5
+ import type { BotOptions, DeriveDefinitions, ErrorDefinitions, Handler, Hooks, MaybePromise, SuppressedAPIMethods } from "./types";
6
6
  import { Updates } from "./updates";
7
7
  export declare class Bot<Errors extends ErrorDefinitions = {}, Derives extends DeriveDefinitions = DeriveDefinitions> {
8
8
  /** @internal */
9
9
  __Derives: Derives;
10
10
  readonly options: BotOptions;
11
11
  info: TelegramUser | undefined;
12
- readonly api: APIMethods;
12
+ readonly api: SuppressedAPIMethods;
13
13
  private lazyloadPlugins;
14
14
  private dependencies;
15
15
  private errorsDefinitions;
@@ -20,6 +20,7 @@ export declare class Bot<Errors extends ErrorDefinitions = {}, Derives extends D
20
20
  private runHooks;
21
21
  private runImmutableHooks;
22
22
  private _callApi;
23
+ downloadFile(fileId: string): Promise<ArrayBuffer>;
23
24
  /**
24
25
  * Register custom class-error for type-safe catch in `onError` hook
25
26
  *
@@ -86,6 +87,16 @@ export declare class Bot<Errors extends ErrorDefinitions = {}, Derives extends D
86
87
  callbackQuery<Trigger extends CallbackData | string | RegExp>(trigger: Trigger, handler: (context: Omit<ContextType<typeof this, "callback_query">, "data"> & Derives["global"] & Derives["callback_query"] & {
87
88
  queryData: Trigger extends CallbackData ? ReturnType<Trigger["unpack"]> : RegExpMatchArray | null;
88
89
  }) => unknown): this;
90
+ chosenInlineResult<Ctx = ContextType<typeof this, "chosen_inline_result"> & Derives["global"] & Derives["chosen_inline_result"]>(trigger: RegExp | string | ((context: Ctx) => boolean), handler: (context: Ctx & {
91
+ args: RegExpMatchArray | null;
92
+ }) => unknown): this;
93
+ inlineQuery<Ctx = ContextType<typeof this, "inline_query"> & Derives["global"] & Derives["inline_query"]>(trigger: RegExp | string | ((context: Ctx) => boolean), handler: (context: Ctx & {
94
+ args: RegExpMatchArray | null;
95
+ }) => unknown, options?: {
96
+ onResult?: (context: ContextType<Bot, "chosen_inline_result"> & Derives["global"] & Derives["chosen_inline_result"] & {
97
+ args: RegExpMatchArray | null;
98
+ }) => unknown;
99
+ }): this;
89
100
  hears<Ctx = ContextType<typeof this, "message"> & Derives["global"] & Derives["message"]>(trigger: RegExp | string | ((context: Ctx) => boolean), handler: (context: Ctx & {
90
101
  args: RegExpMatchArray | null;
91
102
  }) => unknown): this;
package/dist/bot.js CHANGED
@@ -149,7 +149,9 @@ let Bot = (() => {
149
149
  const err = new errors_1.TelegramError(data, method, params);
150
150
  // @ts-expect-error
151
151
  this.runImmutableHooks("onResponseError", err, this.api);
152
- throw err;
152
+ if (!params?.suppress)
153
+ throw err;
154
+ return err;
153
155
  }
154
156
  this.runImmutableHooks("onResponse",
155
157
  // TODO: fix type error
@@ -161,6 +163,13 @@ let Bot = (() => {
161
163
  });
162
164
  return data.result;
163
165
  }
166
+ async downloadFile(fileId) {
167
+ const file = await this.api.getFile({ file_id: fileId });
168
+ const url = `https://api.telegram.org/file/bot${this.options.token}/${file.file_path}`;
169
+ const res = await fetch(url);
170
+ const buffer = await res.arrayBuffer();
171
+ return buffer;
172
+ }
164
173
  /**
165
174
  * Register custom class-error for type-safe catch in `onError` hook
166
175
  *
@@ -396,8 +405,47 @@ let Bot = (() => {
396
405
  return handler(context);
397
406
  });
398
407
  }
408
+ chosenInlineResult(trigger, handler) {
409
+ return this.on("chosen_inline_result", (context, next) => {
410
+ if ((typeof trigger === "string" && context.query === trigger) ||
411
+ // @ts-expect-error
412
+ (typeof trigger === "function" && trigger(context)) ||
413
+ (trigger instanceof RegExp &&
414
+ context.query &&
415
+ trigger.test(context.query))) {
416
+ //@ts-expect-error
417
+ context.args =
418
+ trigger instanceof RegExp ? context.query?.match(trigger) : null;
419
+ // TODO: remove
420
+ //@ts-expect-error
421
+ return handler(context);
422
+ }
423
+ return next();
424
+ });
425
+ }
426
+ inlineQuery(trigger, handler, options = {}) {
427
+ // @ts-expect-error fix later...
428
+ if (options.onResult)
429
+ this.chosenInlineResult(trigger, options.onResult);
430
+ return this.on("inline_query", (context, next) => {
431
+ if ((typeof trigger === "string" && context.query === trigger) ||
432
+ // @ts-expect-error
433
+ (typeof trigger === "function" && trigger(context)) ||
434
+ (trigger instanceof RegExp &&
435
+ context.query &&
436
+ trigger.test(context.query))) {
437
+ //@ts-expect-error
438
+ context.args =
439
+ trigger instanceof RegExp ? context.query?.match(trigger) : null;
440
+ // TODO: remove
441
+ //@ts-expect-error
442
+ return handler(context);
443
+ }
444
+ return next();
445
+ });
446
+ }
399
447
  hears(trigger, handler) {
400
- return this.on(["message", "business_message"], (context, next) => {
448
+ return this.on("message", (context, next) => {
401
449
  if ((typeof trigger === "string" && context.text === trigger) ||
402
450
  // @ts-expect-error
403
451
  (typeof trigger === "function" && trigger(context)) ||
package/dist/errors.d.ts CHANGED
@@ -1,9 +1,10 @@
1
- import type { APIMethodParams, APIMethods, TelegramAPIResponseError, TelegramResponseParameters } from "@gramio/types";
1
+ import type { APIMethods, TelegramAPIResponseError, TelegramResponseParameters } from "@gramio/types";
2
+ import type { MaybeSuppressedParams } from "./types";
2
3
  export declare const ErrorKind: unique symbol;
3
4
  export declare class TelegramError<T extends keyof APIMethods> extends Error {
4
5
  method: T;
5
- params: APIMethodParams<T>;
6
+ params: MaybeSuppressedParams<T>;
6
7
  code: number;
7
8
  payload?: TelegramResponseParameters;
8
- constructor(error: TelegramAPIResponseError, method: T, params: APIMethodParams<T>);
9
+ constructor(error: TelegramAPIResponseError, method: T, params: MaybeSuppressedParams<T>);
9
10
  }
package/dist/plugin.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { BotLike, Context, ContextType, MaybeArray, UpdateName } from "@gramio/contexts";
1
+ import type { Context, ContextType, MaybeArray, UpdateName } from "@gramio/contexts";
2
2
  import type { APIMethods } from "@gramio/types";
3
3
  import type { DeriveDefinitions, ErrorDefinitions, Hooks } from "./types";
4
4
  import type { Bot } from "./bot";
@@ -37,10 +37,10 @@ export declare class Plugin<Errors extends ErrorDefinitions = {}, Derives extend
37
37
  new (...args: any): any;
38
38
  prototype: Error;
39
39
  }>(kind: Name, error: NewError): Plugin<Errors & { [name in Name]: InstanceType<NewError>; }, Derives>;
40
- derive<Handler extends Hooks.Derive<Context<BotLike>>>(handler: Handler): Plugin<Errors, Derives & {
40
+ derive<Handler extends Hooks.Derive<Context<Bot>>>(handler: Handler): Plugin<Errors, Derives & {
41
41
  global: Awaited<ReturnType<Handler>>;
42
42
  }>;
43
- derive<Update extends UpdateName, Handler extends Hooks.Derive<ContextType<BotLike, Update>>>(updateName: MaybeArray<Update>, handler: Handler): Plugin<Errors, Derives & {
43
+ derive<Update extends UpdateName, Handler extends Hooks.Derive<ContextType<Bot, Update>>>(updateName: MaybeArray<Update>, handler: Handler): Plugin<Errors, Derives & {
44
44
  [K in Update]: Awaited<ReturnType<Handler>>;
45
45
  }>;
46
46
  preRequest<Methods extends keyof APIMethods, Handler extends Hooks.PreRequest<Methods>>(methods: MaybeArray<Methods>, handler: Handler): this;
package/dist/types.d.ts CHANGED
@@ -1,6 +1,7 @@
1
- import type { BotLike, Context, UpdateName } from "@gramio/contexts";
1
+ import type { Context, UpdateName } from "@gramio/contexts";
2
2
  import type { APIMethodParams, APIMethodReturn, APIMethods, TelegramUser } from "@gramio/types";
3
3
  import type { NextMiddleware } from "middleware-io";
4
+ import type { Bot } from "./bot";
4
5
  import type { TelegramError } from "./errors";
5
6
  export interface BotOptions {
6
7
  token?: string;
@@ -9,7 +10,7 @@ export interface BotOptions {
9
10
  };
10
11
  }
11
12
  export type Handler<T> = (context: T, next: NextMiddleware) => unknown;
12
- interface ErrorHandlerParams<Ctx extends Context<BotLike>, Kind extends string, Err> {
13
+ interface ErrorHandlerParams<Ctx extends Context<Bot>, Kind extends string, Err> {
13
14
  context: Ctx;
14
15
  kind: Kind;
15
16
  error: Err;
@@ -20,9 +21,37 @@ type AnyTelegramError<Methods extends keyof APIMethods = keyof APIMethods> = {
20
21
  type AnyTelegramMethod<Methods extends keyof APIMethods> = {
21
22
  [APIMethod in Methods]: {
22
23
  method: APIMethod;
23
- params: APIMethodParams<APIMethod>;
24
+ params: MaybeSuppressedParams<APIMethod>;
24
25
  };
25
26
  }[Methods];
27
+ export interface Suppress<IsSuppressed extends boolean | undefined = undefined> {
28
+ /**
29
+ * Pass `true` if you want to suppress throwing errors of this method.
30
+ *
31
+ * **But this does not undo getting into the `onResponseError` hook**.
32
+ *
33
+ * @example
34
+ * ```ts
35
+ * const response = await bot.api.sendMessage({
36
+ * suppress: true,
37
+ * chat_id: "@not_found",
38
+ * text: "Suppressed method"
39
+ * });
40
+ *
41
+ * if(response instanceof TelegramError) console.error("sendMessage returns an error...")
42
+ * else console.log("Message has been sent successfully");
43
+ * ```
44
+ *
45
+ * */
46
+ suppress?: IsSuppressed;
47
+ }
48
+ export type MaybeSuppressedParams<Method extends keyof APIMethods, IsSuppressed extends boolean | undefined = undefined> = APIMethodParams<Method> & Suppress<IsSuppressed>;
49
+ export type SuppressedAPIMethodParams<Method extends keyof APIMethods> = undefined extends APIMethodParams<Method> ? Suppress<true> : MaybeSuppressedParams<Method, true>;
50
+ type MaybeSuppressedReturn<Method extends keyof APIMethods, IsSuppressed extends boolean | undefined = undefined> = true extends IsSuppressed ? TelegramError<Method> | APIMethodReturn<Method> : APIMethodReturn<Method>;
51
+ export type SuppressedAPIMethodReturn<Method extends keyof APIMethods> = MaybeSuppressedReturn<Method, true>;
52
+ export type SuppressedAPIMethods<Methods extends keyof APIMethods = keyof APIMethods> = {
53
+ [APIMethod in Methods]: APIMethodParams<APIMethod> extends undefined ? <IsSuppressed extends boolean | undefined = undefined>(params?: Suppress<IsSuppressed>) => Promise<MaybeSuppressedReturn<APIMethod, IsSuppressed>> : undefined extends APIMethodParams<APIMethod> ? <IsSuppressed extends boolean | undefined = undefined>(params?: MaybeSuppressedParams<APIMethod, IsSuppressed>) => Promise<MaybeSuppressedReturn<APIMethod, IsSuppressed>> : <IsSuppressed extends boolean | undefined = undefined>(params: MaybeSuppressedParams<APIMethod, IsSuppressed>) => Promise<MaybeSuppressedReturn<APIMethod, IsSuppressed>>;
54
+ };
26
55
  type AnyTelegramMethodWithReturn<Methods extends keyof APIMethods> = {
27
56
  [APIMethod in Methods]: {
28
57
  method: APIMethod;
@@ -35,10 +64,10 @@ export declare namespace Hooks {
35
64
  type Derive<Ctx> = (context: Ctx) => MaybePromise<Record<string, unknown>>;
36
65
  type PreRequestContext<Methods extends keyof APIMethods> = AnyTelegramMethod<Methods>;
37
66
  type PreRequest<Methods extends keyof APIMethods = keyof APIMethods> = (ctx: PreRequestContext<Methods>) => MaybePromise<PreRequestContext<Methods>>;
38
- type OnErrorContext<Ctx extends Context<BotLike>, T extends ErrorDefinitions> = ErrorHandlerParams<Ctx, "TELEGRAM", AnyTelegramError> | ErrorHandlerParams<Ctx, "UNKNOWN", Error> | {
67
+ type OnErrorContext<Ctx extends Context<Bot>, T extends ErrorDefinitions> = ErrorHandlerParams<Ctx, "TELEGRAM", AnyTelegramError> | ErrorHandlerParams<Ctx, "UNKNOWN", Error> | {
39
68
  [K in keyof T]: ErrorHandlerParams<Ctx, K & string, T[K & string]>;
40
69
  }[keyof T];
41
- type OnError<T extends ErrorDefinitions, Ctx extends Context<BotLike> = Context<BotLike>> = (options: OnErrorContext<Ctx, T>) => unknown;
70
+ type OnError<T extends ErrorDefinitions, Ctx extends Context<any> = Context<Bot>> = (options: OnErrorContext<Ctx, T>) => unknown;
42
71
  type OnStart = (context: {
43
72
  plugins: string[];
44
73
  info: TelegramUser;
@@ -48,7 +77,7 @@ export declare namespace Hooks {
48
77
  plugins: string[];
49
78
  info: TelegramUser;
50
79
  }) => unknown;
51
- type OnResponseError<Methods extends keyof APIMethods = keyof APIMethods> = (context: AnyTelegramError<Methods>, api: BotLike["api"]) => unknown;
80
+ type OnResponseError<Methods extends keyof APIMethods = keyof APIMethods> = (context: AnyTelegramError<Methods>, api: Bot["api"]) => unknown;
52
81
  type OnResponse<Methods extends keyof APIMethods = keyof APIMethods> = (context: AnyTelegramMethodWithReturn<Methods>) => unknown;
53
82
  interface Store<T extends ErrorDefinitions> {
54
83
  preRequest: PreRequest[];
package/dist/updates.js CHANGED
@@ -33,24 +33,31 @@ class Updates {
33
33
  const UpdateContext = contexts_1.contextsMappings[updateType];
34
34
  if (!UpdateContext)
35
35
  throw new Error(updateType);
36
+ const updatePayload = data[updateType];
37
+ if (!updatePayload)
38
+ throw new Error("");
36
39
  try {
37
40
  let context = new UpdateContext({
38
41
  bot: this.bot,
39
42
  update: data,
40
- payload: data[updateType],
43
+ // @ts-expect-error
44
+ payload: updatePayload,
41
45
  type: updateType,
42
46
  updateId: data.update_id,
43
47
  });
44
48
  if ("isEvent" in context && context.isEvent() && context.eventType) {
45
- // @ts-expect-error contextsMappings is any
49
+ const payload = data.message ??
50
+ data.edited_message ??
51
+ data.channel_post ??
52
+ data.edited_channel_post ??
53
+ data.business_message;
54
+ if (!payload)
55
+ throw new Error("Unsupported event??");
46
56
  context = new contexts_1.contextsMappings[context.eventType]({
47
57
  bot: this.bot,
48
58
  update: data,
49
- payload: data.message ??
50
- data.edited_message ??
51
- data.channel_post ??
52
- data.edited_channel_post ??
53
- data.business_message,
59
+ payload,
60
+ // @ts-expect-error
54
61
  type: context.eventType,
55
62
  updateId: data.update_id,
56
63
  });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "gramio",
3
- "version": "0.0.26",
3
+ "version": "0.0.28",
4
4
  "description": "Powerful Telegram Bot API framework",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
@@ -25,19 +25,19 @@
25
25
  "license": "ISC",
26
26
  "devDependencies": {
27
27
  "@biomejs/biome": "1.6.4",
28
- "@types/node": "^20.12.4",
29
- "typescript": "^5.4.3"
28
+ "@types/node": "^20.12.7",
29
+ "typescript": "^5.4.5"
30
30
  },
31
31
  "dependencies": {
32
32
  "@gramio/callback-data": "^0.0.2",
33
- "@gramio/contexts": "^0.0.8",
34
- "@gramio/files": "^0.0.4",
33
+ "@gramio/contexts": "^0.0.9",
34
+ "@gramio/files": "^0.0.5",
35
35
  "@gramio/format": "^0.0.8",
36
- "@gramio/keyboards": "^0.2.3",
36
+ "@gramio/keyboards": "^0.3.0",
37
37
  "@gramio/types": "^7.2.1",
38
38
  "inspectable": "^3.0.0",
39
39
  "middleware-io": "^2.8.1",
40
- "undici": "^6.11.1"
40
+ "undici": "^6.12.0"
41
41
  },
42
42
  "files": [
43
43
  "dist"