UNPKG

gramio

Version:

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

823 lines (817 loc) 102 kB
import * as _gramio_callback_data from '@gramio/callback-data'; import { CallbackData } from '@gramio/callback-data'; export * from '@gramio/callback-data'; import * as _gramio_contexts from '@gramio/contexts'; import { UpdateName, MessageEventName, CustomEventName, Context, ContextsMapping, BotLike, ContextType, Attachment, AttachmentsMapping, Dice, MessageOriginUser, MessageOriginChat, MessageOriginChannel, MessageOriginHiddenUser, Message, MessageEntity, TextQuote, User, LinkPreviewOptions, ExternalReplyInfo, Chat, Giveaway, PaidMediaInfo, Game, StoryAttachment, Venue, MessageContext } from '@gramio/contexts'; export * from '@gramio/contexts'; import { FileSource, TelegramFileDownload } from '@gramio/files'; export * from '@gramio/files'; export * from '@gramio/format'; export * from '@gramio/keyboards'; import * as _gramio_types from '@gramio/types'; import { APIMethods, TelegramResponseParameters, TelegramAPIResponseError, TelegramReactionTypeEmojiEmoji, TelegramUser, APIMethodParams, APIMethodReturn, TelegramBotCommandScope, SetWebhookParams, TelegramUpdate, TelegramMessageEntity } from '@gramio/types'; export * from '@gramio/types'; import * as _gramio_composer from '@gramio/composer'; import { ComposerLike, MacroDefinitions, EventContextOf, EventComposer, MacroDef, Next, EventQueue, HandlerOptions, DeriveFromOptions } from '@gramio/composer'; export { ContextCallback, DeriveFromOptions, DeriveHandler, EventComposer, EventQueue, HandlerOptions, MacroDef, MacroDefinitions, MacroDeriveType, MacroHooks, MacroOptionType, Middleware, Next, WithCtx, WithDecorate, WithDerives, WithEventDerive, WithExtend, buildFromOptions, compose, noopNext, skip, stop } from '@gramio/composer'; /** * Telegram Bot API top-level update type name. * Valid values for `allowed_updates` in `getUpdates` / `setWebhook`. */ type AllowedUpdateName = Exclude<UpdateName, MessageEventName | CustomEventName>; /** The 3 types Telegram excludes by default (must be explicitly requested). */ declare const OPT_IN_TYPES: readonly AllowedUpdateName[]; /** * Maps any event name to the `AllowedUpdateName` values needed in `allowed_updates`. * * - Top-level update names → themselves * - Sub-message events (MessageEventName) → all 5 message-carrying parent types * - Unknown names (filter names like "text") → `undefined` (skipped) */ declare function mapEventToAllowedUpdates(event: string): readonly AllowedUpdateName[] | undefined; /** * Detect which of the 3 opt-in types have handlers registered. * Used by `bot.start()` for default auto opt-in behavior. */ declare function detectOptInUpdates(registeredEvents: Set<string>): AllowedUpdateName[]; /** * Fluent, immutable builder for the Telegram Bot API `allowed_updates` list. * * Instances directly extend `Array<AllowedUpdateName>`, so they can be passed * wherever `allowedUpdates` is expected without any conversion. * * @example * ```typescript * import { AllowedUpdatesFilter } from "gramio"; * * // All updates (opt-in types included: chat_member, message_reaction, message_reaction_count) * bot.start({ allowedUpdates: AllowedUpdatesFilter.all }); * * // Telegram's default set (opt-in types excluded) * bot.start({ allowedUpdates: AllowedUpdatesFilter.default }); * * // Explicit list * bot.start({ allowedUpdates: AllowedUpdatesFilter.only("message", "callback_query") }); * * // All except poll events * bot.start({ allowedUpdates: AllowedUpdatesFilter.all.except("poll", "poll_answer") }); * * // Default + opt-in to chat_member * bot.start({ allowedUpdates: AllowedUpdatesFilter.default.add("chat_member") }); * ``` */ declare class AllowedUpdatesFilter extends Array<AllowedUpdateName> { /** @internal use static factory methods instead */ constructor(updates: readonly AllowedUpdateName[]); /** * All update types, including the opt-in ones: * `chat_member`, `message_reaction`, and `message_reaction_count`. */ static get all(): AllowedUpdatesFilter; /** * Telegram's **default** update set. * * Receive all updates _except_ `chat_member`, `message_reaction`, and * `message_reaction_count` — the three types that Telegram requires to be * explicitly listed in `allowed_updates`. * * This matches what Telegram does when `allowed_updates` is omitted or * passed as an empty array. */ static get default(): AllowedUpdatesFilter; /** * Create a filter with **exactly** the specified update types. * * @example * ```typescript * AllowedUpdatesFilter.only("message", "callback_query", "inline_query") * ``` */ static only(...types: AllowedUpdateName[]): AllowedUpdatesFilter; /** * Return a new filter with the given types **added**. * Already-present types are silently deduplicated. * * @example * ```typescript * AllowedUpdatesFilter.default.add("chat_member", "message_reaction") * ``` */ add(...types: AllowedUpdateName[]): AllowedUpdatesFilter; /** * Return a new filter with the given types **removed**. * * @example * ```typescript * AllowedUpdatesFilter.all.except("poll", "poll_answer", "chosen_inline_result") * ``` */ except(...types: AllowedUpdateName[]): AllowedUpdatesFilter; /** Convert to a plain `AllowedUpdateName[]` array. */ toArray(): AllowedUpdateName[]; } /** * Build an {@link AllowedUpdatesFilter} automatically from a bot's registered * `.on()` handlers (including handlers from extended plugins). * * Returns **only** the update types that handlers explicitly register for. * Use this for strict filtering — Telegram will only send these update types. * * **Note:** filter-only `.on(filterFn, handler)` and `.use()` middleware * do not declare specific events and are not included. * Manually `.add()` additional types if needed. * * Call after all handlers/plugins are registered (or after `bot.init()`). * * @example * ```typescript * const bot = new Bot(token) * .command("start", handler) * .callbackQuery("data", handler); * * bot.start({ allowedUpdates: buildAllowedUpdates(bot) }); * // → allowed_updates: ["message", "business_message", "callback_query"] * * // With customization: * bot.start({ allowedUpdates: buildAllowedUpdates(bot).add("poll") }); * ``` */ declare function buildAllowedUpdates(bot: { updates: { composer: { registeredEvents(): Set<string>; }; }; }): AllowedUpdatesFilter; /** Symbol to determine which error kind is it */ declare const ErrorKind: symbol; /** Represent {@link TelegramAPIResponseError} and thrown in API calls */ declare class TelegramError<T extends keyof APIMethods> extends Error { /** Name of the API Method */ method: T; /** Params that were sent */ params: MaybeSuppressedParams<T>; /** See {@link TelegramAPIResponseError.error_code}*/ code: number; /** Describes why a request was unsuccessful. */ payload?: TelegramResponseParameters; /** Construct new TelegramError */ constructor(error: TelegramAPIResponseError, method: T, params: MaybeSuppressedParams<T>, callSite?: Error); } type MaybeArray<T> = T | T[] | ReadonlyArray<T>; type TelegramEventMap = { [K in keyof ContextsMapping<AnyBot>]: InstanceType<ContextsMapping<AnyBot>[K]>; }; /** Concrete context type without GetDerives (which collapses to any with AnyBot) */ type Ctx<K extends keyof ContextsMapping<AnyBot>> = InstanceType<ContextsMapping<AnyBot>[K]>; /** * Extends `ComposerLike<T>` with the two internal members that method * bodies need: macro registry and the cross-method `chosenInlineResult` call. */ type GramIOLike<T> = ComposerLike<T> & { "~": { macros: MacroDefinitions; commandsMeta?: Map<string, unknown>; Derives?: Record<string, object>; }; chosenInlineResult(trigger: any, handler: any, macroOptions?: any): T; }; declare const methods: { reaction<TThis extends GramIOLike<TThis>>(this: TThis, trigger: MaybeArray<TelegramReactionTypeEmojiEmoji>, handler: (context: Ctx<"message_reaction"> & EventContextOf<TThis, "message_reaction">) => unknown, macroOptions?: Record<string, unknown>): TThis; callbackQuery<TThis extends GramIOLike<TThis>, Trigger extends CallbackData | string | RegExp>(this: TThis, trigger: Trigger, handler: (context: Ctx<"callback_query"> & { queryData: Trigger extends CallbackData ? ReturnType<Trigger["unpack"]> : Trigger extends RegExp ? RegExpMatchArray : never; } & EventContextOf<TThis, "callback_query">) => unknown, macroOptions?: Record<string, unknown>): TThis; chosenInlineResult<TThis extends GramIOLike<TThis>, Trigger extends CallbackData | RegExp | string | ((context: Ctx<"chosen_inline_result">) => boolean)>(this: TThis, trigger: Trigger, handler: (context: Ctx<"chosen_inline_result"> & { args: RegExpMatchArray | null; queryData: Trigger extends CallbackData ? ReturnType<Trigger["unpack"]> : never; } & EventContextOf<TThis, "chosen_inline_result">) => unknown, macroOptions?: Record<string, unknown>): TThis; inlineQuery<TThis extends GramIOLike<TThis>>(this: TThis, triggerOrHandler: RegExp | string | ((context: Ctx<"inline_query">) => boolean) | ((context: Ctx<"inline_query"> & { args: RegExpMatchArray | null; } & EventContextOf<TThis, "inline_query">) => unknown), maybeHandler?: (context: Ctx<"inline_query"> & { args: RegExpMatchArray | null; } & EventContextOf<TThis, "inline_query">) => unknown, options?: { onResult?: (context: Ctx<"chosen_inline_result"> & { args: RegExpMatchArray | null; } & EventContextOf<TThis, "chosen_inline_result">) => unknown; } & Record<string, unknown>): TThis; guestQuery<TThis extends GramIOLike<TThis>>(this: TThis, triggerOrHandler: RegExp | string | ((context: Ctx<"guest_message">) => boolean) | ((context: Ctx<"guest_message"> & { args: RegExpMatchArray | null; } & EventContextOf<TThis, "guest_message">) => unknown), maybeHandler?: (context: Ctx<"guest_message"> & { args: RegExpMatchArray | null; } & EventContextOf<TThis, "guest_message">) => unknown, macroOptions?: Record<string, unknown>): TThis; hears<TThis extends GramIOLike<TThis>>(this: TThis, trigger: RegExp | MaybeArray<string> | ((context: Ctx<"message">) => boolean), handler: (context: Ctx<"message"> & { args: RegExpMatchArray | null; } & EventContextOf<TThis, "message">) => unknown, macroOptions?: Record<string, unknown>): TThis; command<TThis extends GramIOLike<TThis>>(this: TThis, command: MaybeArray<string>, handlerOrMeta: ((context: Ctx<"message"> & { args: string | null; } & EventContextOf<TThis, "message">) => unknown) | CommandMeta, handlerOrOptions?: ((context: Ctx<"message"> & { args: string | null; } & EventContextOf<TThis, "message">) => unknown) | Record<string, unknown>, macroOptions?: Record<string, unknown>): TThis; startParameter<TThis extends GramIOLike<TThis>>(this: TThis, parameter: RegExp | MaybeArray<string>, handler: Handler<Ctx<"message"> & { rawStartPayload: string; } & EventContextOf<TThis, "message">>, macroOptions?: Record<string, unknown>): TThis; }; /** Teach EventComposer about GramIO-specific overloads */ declare module "@gramio/composer" { interface EventComposer<TBase, TEventMap, TIn, TOut, TExposed, TDerives, TMethods, TMacros> { extend<P extends AnyPlugin>(plugin: P): EventComposer<TBase, TEventMap, TIn, TOut & P["_"]["Derives"]["global"], TExposed, TDerives & Omit<P["_"]["Derives"], "global">, TMethods, TMacros & P["_"]["Macros"]>; registeredEvents(): Set<string>; callbackQuery: (typeof methods)["callbackQuery"]; command: (typeof methods)["command"]; hears: (typeof methods)["hears"]; reaction: (typeof methods)["reaction"]; inlineQuery: (typeof methods)["inlineQuery"]; guestQuery: (typeof methods)["guestQuery"]; chosenInlineResult: (typeof methods)["chosenInlineResult"]; startParameter: (typeof methods)["startParameter"]; } } declare const Composer: _gramio_composer.EventComposerConstructor<Context<AnyBot>, TelegramEventMap, { reaction<TThis extends GramIOLike<TThis>>(this: TThis, trigger: MaybeArray<TelegramReactionTypeEmojiEmoji>, handler: (context: Ctx<"message_reaction"> & EventContextOf<TThis, "message_reaction">) => unknown, macroOptions?: Record<string, unknown>): TThis; callbackQuery<TThis extends GramIOLike<TThis>, Trigger extends CallbackData | string | RegExp>(this: TThis, trigger: Trigger, handler: (context: Ctx<"callback_query"> & { queryData: Trigger extends CallbackData ? ReturnType<Trigger["unpack"]> : Trigger extends RegExp ? RegExpMatchArray : never; } & EventContextOf<TThis, "callback_query">) => unknown, macroOptions?: Record<string, unknown>): TThis; chosenInlineResult<TThis extends GramIOLike<TThis>, Trigger extends CallbackData | RegExp | string | ((context: Ctx<"chosen_inline_result">) => boolean)>(this: TThis, trigger: Trigger, handler: (context: Ctx<"chosen_inline_result"> & { args: RegExpMatchArray | null; queryData: Trigger extends CallbackData ? ReturnType<Trigger["unpack"]> : never; } & EventContextOf<TThis, "chosen_inline_result">) => unknown, macroOptions?: Record<string, unknown>): TThis; inlineQuery<TThis extends GramIOLike<TThis>>(this: TThis, triggerOrHandler: RegExp | string | ((context: Ctx<"inline_query">) => boolean) | ((context: Ctx<"inline_query"> & { args: RegExpMatchArray | null; } & EventContextOf<TThis, "inline_query">) => unknown), maybeHandler?: (context: Ctx<"inline_query"> & { args: RegExpMatchArray | null; } & EventContextOf<TThis, "inline_query">) => unknown, options?: { onResult?: (context: Ctx<"chosen_inline_result"> & { args: RegExpMatchArray | null; } & EventContextOf<TThis, "chosen_inline_result">) => unknown; } & Record<string, unknown>): TThis; guestQuery<TThis extends GramIOLike<TThis>>(this: TThis, triggerOrHandler: RegExp | string | ((context: Ctx<"guest_message">) => boolean) | ((context: Ctx<"guest_message"> & { args: RegExpMatchArray | null; } & EventContextOf<TThis, "guest_message">) => unknown), maybeHandler?: (context: Ctx<"guest_message"> & { args: RegExpMatchArray | null; } & EventContextOf<TThis, "guest_message">) => unknown, macroOptions?: Record<string, unknown>): TThis; hears<TThis extends GramIOLike<TThis>>(this: TThis, trigger: RegExp | MaybeArray<string> | ((context: Ctx<"message">) => boolean), handler: (context: Ctx<"message"> & { args: RegExpMatchArray | null; } & EventContextOf<TThis, "message">) => unknown, macroOptions?: Record<string, unknown>): TThis; command<TThis extends GramIOLike<TThis>>(this: TThis, command: MaybeArray<string>, handlerOrMeta: ((context: Ctx<"message"> & { args: string | null; } & EventContextOf<TThis, "message">) => unknown) | CommandMeta, handlerOrOptions?: ((context: Ctx<"message"> & { args: string | null; } & EventContextOf<TThis, "message">) => unknown) | Record<string, unknown>, macroOptions?: Record<string, unknown>): TThis; startParameter<TThis extends GramIOLike<TThis>>(this: TThis, parameter: RegExp | MaybeArray<string>, handler: Handler<Ctx<"message"> & { rawStartPayload: string; } & EventContextOf<TThis, "message">>, macroOptions?: Record<string, unknown>): TThis; }>; /** * Yields the subset of UpdateName whose context type contains all keys from Narrowing. */ type CompatibleUpdates$1<B extends BotLike, Narrowing> = { [K in UpdateName]: keyof Narrowing & string extends keyof ContextType<B, K> ? K : never; }[UpdateName]; /** * `Plugin` is an object from which you can extends in Bot instance and adopt types * * @example * ```ts * import { Plugin, Bot } from "gramio"; * * export class PluginError extends Error { * wow: "type" | "safe" = "type"; * } * * const plugin = new Plugin("gramio-example") * .error("PLUGIN", PluginError) * .derive(() => { * return { * some: ["derived", "props"] as const, * }; * }); * * const bot = new Bot(process.env.TOKEN!) * .extend(plugin) * .onError(({ context, kind, error }) => { * if (context.is("message") && kind === "PLUGIN") { * console.log(error.wow); * } * }) * .use((context) => { * console.log(context.some); * }); * ``` */ declare class Plugin<Errors extends ErrorDefinitions = {}, Derives extends DeriveDefinitions = DeriveDefinitions, Macros extends MacroDefinitions = {}> { /** * @internal * Set of Plugin data * * */ _: { /** Name of plugin */ name: string; /** List of plugin dependencies. If user does't extend from listed there dependencies it throw a error */ dependencies: string[]; /** remap generic type. {} in runtime */ Errors: Errors; /** remap generic type. {} in runtime */ Derives: Derives; /** remap generic type. {} in runtime */ Macros: Macros; /** Composer */ composer: EventComposer<Context<AnyBot>, { callback_query: _gramio_contexts.CallbackQueryContext<AnyBot>; chat_join_request: _gramio_contexts.ChatJoinRequestContext<AnyBot>; chat_member: _gramio_contexts.ChatMemberContext<AnyBot>; my_chat_member: _gramio_contexts.ChatMemberContext<AnyBot>; chosen_inline_result: _gramio_contexts.ChosenInlineResultContext<AnyBot>; delete_chat_photo: _gramio_contexts.DeleteChatPhotoContext<AnyBot>; group_chat_created: _gramio_contexts.GroupChatCreatedContext<AnyBot>; inline_query: _gramio_contexts.InlineQueryContext<AnyBot>; invoice: _gramio_contexts.InvoiceContext<AnyBot>; left_chat_member: _gramio_contexts.LeftChatMemberContext<AnyBot>; location: _gramio_contexts.LocationContext<AnyBot>; managed_bot: _gramio_contexts.ManagedBotContext<AnyBot>; managed_bot_created: _gramio_contexts.ManagedBotCreatedContext<AnyBot>; message_auto_delete_timer_changed: _gramio_contexts.MessageAutoDeleteTimerChangedContext<AnyBot>; message: _gramio_contexts.MessageContext<AnyBot> & _gramio_contexts.Require<_gramio_contexts.MessageContext<AnyBot>, "from">; channel_post: _gramio_contexts.MessageContext<AnyBot>; edited_message: _gramio_contexts.MessageContext<AnyBot> & _gramio_contexts.Require<_gramio_contexts.MessageContext<AnyBot>, "from">; edited_channel_post: _gramio_contexts.MessageContext<AnyBot> & _gramio_contexts.Require<_gramio_contexts.MessageContext<AnyBot>, "from">; business_message: _gramio_contexts.MessageContext<AnyBot> & _gramio_contexts.Require<_gramio_contexts.MessageContext<AnyBot>, "from">; edited_business_message: _gramio_contexts.MessageContext<AnyBot> & _gramio_contexts.Require<_gramio_contexts.MessageContext<AnyBot>, "from">; guest_message: _gramio_contexts.MessageContext<AnyBot> & _gramio_contexts.Require<_gramio_contexts.MessageContext<AnyBot>, "from">; deleted_business_messages: _gramio_contexts.BusinessMessagesDeletedContext<AnyBot>; business_connection: _gramio_contexts.BusinessConnectionContext<AnyBot>; migrate_from_chat_id: _gramio_contexts.MigrateFromChatIdContext<AnyBot>; migrate_to_chat_id: _gramio_contexts.MigrateToChatIdContext<AnyBot>; new_chat_members: _gramio_contexts.NewChatMembersContext<AnyBot>; new_chat_photo: _gramio_contexts.NewChatPhotoContext<AnyBot>; new_chat_title: _gramio_contexts.NewChatTitleContext<AnyBot>; passport_data: _gramio_contexts.PassportDataContext<AnyBot>; pinned_message: _gramio_contexts.PinnedMessageContext<AnyBot>; poll_answer: _gramio_contexts.PollAnswerContext<AnyBot>; poll_option_added: _gramio_contexts.PollOptionAddedContext<AnyBot>; poll_option_deleted: _gramio_contexts.PollOptionDeletedContext<AnyBot>; poll: _gramio_contexts.PollContext<AnyBot>; pre_checkout_query: _gramio_contexts.PreCheckoutQueryContext<AnyBot>; proximity_alert_triggered: _gramio_contexts.ProximityAlertTriggeredContext<AnyBot>; write_access_allowed: _gramio_contexts.WriteAccessAllowedContext<AnyBot>; boost_added: _gramio_contexts.BoostAddedContext<AnyBot>; chat_background_set: _gramio_contexts.ChatBackgroundSetContext<AnyBot>; checklist_tasks_done: _gramio_contexts.ChecklistTasksDoneContext<AnyBot>; checklist_tasks_added: _gramio_contexts.ChecklistTasksAddedContext<AnyBot>; direct_message_price_changed: _gramio_contexts.DirectMessagePriceChangedContext<AnyBot>; suggested_post_approved: _gramio_contexts.SuggestedPostApprovedContext<AnyBot>; suggested_post_approval_failed: _gramio_contexts.SuggestedPostApprovalFailedContext<AnyBot>; suggested_post_declined: _gramio_contexts.SuggestedPostDeclinedContext<AnyBot>; suggested_post_paid: _gramio_contexts.SuggestedPostPaidContext<AnyBot>; suggested_post_refunded: _gramio_contexts.SuggestedPostRefundedContext<AnyBot>; forum_topic_created: _gramio_contexts.ForumTopicCreatedContext<AnyBot>; forum_topic_edited: _gramio_contexts.ForumTopicEditedContext<AnyBot>; forum_topic_closed: _gramio_contexts.ForumTopicClosedContext<AnyBot>; forum_topic_reopened: _gramio_contexts.ForumTopicReopenedContext<AnyBot>; general_forum_topic_hidden: _gramio_contexts.GeneralForumTopicHiddenContext<AnyBot>; general_forum_topic_unhidden: _gramio_contexts.GeneralForumTopicUnhiddenContext<AnyBot>; shipping_query: _gramio_contexts.ShippingQueryContext<AnyBot>; successful_payment: _gramio_contexts.SuccessfulPaymentContext<AnyBot>; refunded_payment: _gramio_contexts.RefundedPaymentContext<AnyBot>; users_shared: _gramio_contexts.UsersSharedContext<AnyBot>; chat_shared: _gramio_contexts.ChatSharedContext<AnyBot>; gift: _gramio_contexts.GiftContext<AnyBot>; gift_upgrade_sent: _gramio_contexts.GiftUpgradeSentContext<AnyBot>; unique_gift: _gramio_contexts.UniqueGiftContext<AnyBot>; chat_owner_left: _gramio_contexts.ChatOwnerLeftContext<AnyBot>; chat_owner_changed: _gramio_contexts.ChatOwnerChangedContext<AnyBot>; paid_message_price_changed: _gramio_contexts.PaidMessagePriceChangedContext<AnyBot>; video_chat_ended: _gramio_contexts.VideoChatEndedContext<AnyBot>; video_chat_participants_invited: _gramio_contexts.VideoChatParticipantsInvitedContext<AnyBot>; video_chat_scheduled: _gramio_contexts.VideoChatScheduledContext<AnyBot>; video_chat_started: _gramio_contexts.VideoChatStartedContext<AnyBot>; web_app_data: _gramio_contexts.WebAppDataContext<AnyBot>; service_message: _gramio_contexts.MessageContext<AnyBot>; message_reaction: _gramio_contexts.MessageReactionContext<AnyBot>; message_reaction_count: _gramio_contexts.MessageReactionCountContext<AnyBot>; chat_boost: _gramio_contexts.ChatBoostContext<AnyBot>; removed_chat_boost: _gramio_contexts.RemovedChatBoostContext<AnyBot>; giveaway_created: _gramio_contexts.GiveawayCreatedContext<AnyBot>; giveaway_completed: _gramio_contexts.GiveawayCompletedContext<AnyBot>; giveaway_winners: _gramio_contexts.GiveawayWinnersContext<AnyBot>; purchased_paid_media: _gramio_contexts.PaidMediaPurchasedContext<AnyBot>; }, Context<AnyBot>, Context<AnyBot>, {}, {}, { reaction<TThis extends _gramio_composer.ComposerLike<TThis> & { "~": { macros: MacroDefinitions; commandsMeta?: Map<string, unknown>; Derives?: Record<string, object>; }; chosenInlineResult(trigger: any, handler: any, macroOptions?: any): TThis; }>(this: TThis, trigger: MaybeArray<_gramio_types.TelegramReactionTypeEmojiEmoji>, handler: (context: _gramio_contexts.MessageReactionContext<AnyBot> & _gramio_composer.EventContextOf<TThis, "message_reaction">) => unknown, macroOptions?: Record<string, unknown>): TThis; callbackQuery<TThis extends _gramio_composer.ComposerLike<TThis> & { "~": { macros: MacroDefinitions; commandsMeta?: Map<string, unknown>; Derives?: Record<string, object>; }; chosenInlineResult(trigger: any, handler: any, macroOptions?: any): TThis; }, Trigger extends _gramio_callback_data.CallbackData | string | RegExp>(this: TThis, trigger: Trigger, handler: (context: _gramio_contexts.CallbackQueryContext<AnyBot> & { queryData: Trigger extends _gramio_callback_data.CallbackData ? ReturnType<Trigger["unpack"]> : Trigger extends RegExp ? RegExpMatchArray : never; } & _gramio_composer.EventContextOf<TThis, "callback_query">) => unknown, macroOptions?: Record<string, unknown>): TThis; chosenInlineResult<TThis extends _gramio_composer.ComposerLike<TThis> & { "~": { macros: MacroDefinitions; commandsMeta?: Map<string, unknown>; Derives?: Record<string, object>; }; chosenInlineResult(trigger: any, handler: any, macroOptions?: any): TThis; }, Trigger extends _gramio_callback_data.CallbackData | RegExp | string | ((context: _gramio_contexts.ChosenInlineResultContext<AnyBot>) => boolean)>(this: TThis, trigger: Trigger, handler: (context: _gramio_contexts.ChosenInlineResultContext<AnyBot> & { args: RegExpMatchArray | null; queryData: Trigger extends _gramio_callback_data.CallbackData ? ReturnType<Trigger["unpack"]> : never; } & _gramio_composer.EventContextOf<TThis, "chosen_inline_result">) => unknown, macroOptions?: Record<string, unknown>): TThis; inlineQuery<TThis extends _gramio_composer.ComposerLike<TThis> & { "~": { macros: MacroDefinitions; commandsMeta?: Map<string, unknown>; Derives?: Record<string, object>; }; chosenInlineResult(trigger: any, handler: any, macroOptions?: any): TThis; }>(this: TThis, triggerOrHandler: RegExp | string | ((context: _gramio_contexts.InlineQueryContext<AnyBot>) => boolean) | ((context: _gramio_contexts.InlineQueryContext<AnyBot> & { args: RegExpMatchArray | null; } & _gramio_composer.EventContextOf<TThis, "inline_query">) => unknown), maybeHandler?: (context: _gramio_contexts.InlineQueryContext<AnyBot> & { args: RegExpMatchArray | null; } & _gramio_composer.EventContextOf<TThis, "inline_query">) => unknown, options?: { onResult?: (context: _gramio_contexts.ChosenInlineResultContext<AnyBot> & { args: RegExpMatchArray | null; } & _gramio_composer.EventContextOf<TThis, "chosen_inline_result">) => unknown; } & Record<string, unknown>): TThis; guestQuery<TThis extends _gramio_composer.ComposerLike<TThis> & { "~": { macros: MacroDefinitions; commandsMeta?: Map<string, unknown>; Derives?: Record<string, object>; }; chosenInlineResult(trigger: any, handler: any, macroOptions?: any): TThis; }>(this: TThis, triggerOrHandler: RegExp | string | ((context: _gramio_contexts.MessageContext<AnyBot> & _gramio_contexts.Require<_gramio_contexts.MessageContext<AnyBot>, "from">) => boolean) | ((context: (_gramio_contexts.MessageContext<AnyBot> & _gramio_contexts.Require<_gramio_contexts.MessageContext<AnyBot>, "from">) & { args: RegExpMatchArray | null; } & _gramio_composer.EventContextOf<TThis, "guest_message">) => unknown), maybeHandler?: (context: (_gramio_contexts.MessageContext<AnyBot> & _gramio_contexts.Require<_gramio_contexts.MessageContext<AnyBot>, "from">) & { args: RegExpMatchArray | null; } & _gramio_composer.EventContextOf<TThis, "guest_message">) => unknown, macroOptions?: Record<string, unknown>): TThis; hears<TThis extends _gramio_composer.ComposerLike<TThis> & { "~": { macros: MacroDefinitions; commandsMeta?: Map<string, unknown>; Derives?: Record<string, object>; }; chosenInlineResult(trigger: any, handler: any, macroOptions?: any): TThis; }>(this: TThis, trigger: RegExp | MaybeArray<string> | ((context: _gramio_contexts.MessageContext<AnyBot> & _gramio_contexts.Require<_gramio_contexts.MessageContext<AnyBot>, "from">) => boolean), handler: (context: (_gramio_contexts.MessageContext<AnyBot> & _gramio_contexts.Require<_gramio_contexts.MessageContext<AnyBot>, "from">) & { args: RegExpMatchArray | null; } & _gramio_composer.EventContextOf<TThis, "message">) => unknown, macroOptions?: Record<string, unknown>): TThis; command<TThis extends _gramio_composer.ComposerLike<TThis> & { "~": { macros: MacroDefinitions; commandsMeta?: Map<string, unknown>; Derives?: Record<string, object>; }; chosenInlineResult(trigger: any, handler: any, macroOptions?: any): TThis; }>(this: TThis, command: MaybeArray<string>, handlerOrMeta: ((context: (_gramio_contexts.MessageContext<AnyBot> & _gramio_contexts.Require<_gramio_contexts.MessageContext<AnyBot>, "from">) & { args: string | null; } & _gramio_composer.EventContextOf<TThis, "message">) => unknown) | CommandMeta, handlerOrOptions?: ((context: (_gramio_contexts.MessageContext<AnyBot> & _gramio_contexts.Require<_gramio_contexts.MessageContext<AnyBot>, "from">) & { args: string | null; } & _gramio_composer.EventContextOf<TThis, "message">) => unknown) | Record<string, unknown>, macroOptions?: Record<string, unknown>): TThis; startParameter<TThis extends _gramio_composer.ComposerLike<TThis> & { "~": { macros: MacroDefinitions; commandsMeta?: Map<string, unknown>; Derives?: Record<string, object>; }; chosenInlineResult(trigger: any, handler: any, macroOptions?: any): TThis; }>(this: TThis, parameter: RegExp | MaybeArray<string>, handler: Handler<(_gramio_contexts.MessageContext<AnyBot> & _gramio_contexts.Require<_gramio_contexts.MessageContext<AnyBot>, "from">) & { rawStartPayload: string; } & _gramio_composer.EventContextOf<TThis, "message">>, macroOptions?: Record<string, unknown>): TThis; }, {}> & { reaction<TThis extends _gramio_composer.ComposerLike<TThis> & { "~": { macros: MacroDefinitions; commandsMeta?: Map<string, unknown>; Derives?: Record<string, object>; }; chosenInlineResult(trigger: any, handler: any, macroOptions?: any): TThis; }>(this: TThis, trigger: MaybeArray<_gramio_types.TelegramReactionTypeEmojiEmoji>, handler: (context: _gramio_contexts.MessageReactionContext<AnyBot> & _gramio_composer.EventContextOf<TThis, "message_reaction">) => unknown, macroOptions?: Record<string, unknown>): TThis; callbackQuery<TThis extends _gramio_composer.ComposerLike<TThis> & { "~": { macros: MacroDefinitions; commandsMeta?: Map<string, unknown>; Derives?: Record<string, object>; }; chosenInlineResult(trigger: any, handler: any, macroOptions?: any): TThis; }, Trigger extends _gramio_callback_data.CallbackData | string | RegExp>(this: TThis, trigger: Trigger, handler: (context: _gramio_contexts.CallbackQueryContext<AnyBot> & { queryData: Trigger extends _gramio_callback_data.CallbackData ? ReturnType<Trigger["unpack"]> : Trigger extends RegExp ? RegExpMatchArray : never; } & _gramio_composer.EventContextOf<TThis, "callback_query">) => unknown, macroOptions?: Record<string, unknown>): TThis; chosenInlineResult<TThis extends _gramio_composer.ComposerLike<TThis> & { "~": { macros: MacroDefinitions; commandsMeta?: Map<string, unknown>; Derives?: Record<string, object>; }; chosenInlineResult(trigger: any, handler: any, macroOptions?: any): TThis; }, Trigger extends _gramio_callback_data.CallbackData | RegExp | string | ((context: _gramio_contexts.ChosenInlineResultContext<AnyBot>) => boolean)>(this: TThis, trigger: Trigger, handler: (context: _gramio_contexts.ChosenInlineResultContext<AnyBot> & { args: RegExpMatchArray | null; queryData: Trigger extends _gramio_callback_data.CallbackData ? ReturnType<Trigger["unpack"]> : never; } & _gramio_composer.EventContextOf<TThis, "chosen_inline_result">) => unknown, macroOptions?: Record<string, unknown>): TThis; inlineQuery<TThis extends _gramio_composer.ComposerLike<TThis> & { "~": { macros: MacroDefinitions; commandsMeta?: Map<string, unknown>; Derives?: Record<string, object>; }; chosenInlineResult(trigger: any, handler: any, macroOptions?: any): TThis; }>(this: TThis, triggerOrHandler: RegExp | string | ((context: _gramio_contexts.InlineQueryContext<AnyBot>) => boolean) | ((context: _gramio_contexts.InlineQueryContext<AnyBot> & { args: RegExpMatchArray | null; } & _gramio_composer.EventContextOf<TThis, "inline_query">) => unknown), maybeHandler?: (context: _gramio_contexts.InlineQueryContext<AnyBot> & { args: RegExpMatchArray | null; } & _gramio_composer.EventContextOf<TThis, "inline_query">) => unknown, options?: { onResult?: (context: _gramio_contexts.ChosenInlineResultContext<AnyBot> & { args: RegExpMatchArray | null; } & _gramio_composer.EventContextOf<TThis, "chosen_inline_result">) => unknown; } & Record<string, unknown>): TThis; guestQuery<TThis extends _gramio_composer.ComposerLike<TThis> & { "~": { macros: MacroDefinitions; commandsMeta?: Map<string, unknown>; Derives?: Record<string, object>; }; chosenInlineResult(trigger: any, handler: any, macroOptions?: any): TThis; }>(this: TThis, triggerOrHandler: RegExp | string | ((context: _gramio_contexts.MessageContext<AnyBot> & _gramio_contexts.Require<_gramio_contexts.MessageContext<AnyBot>, "from">) => boolean) | ((context: (_gramio_contexts.MessageContext<AnyBot> & _gramio_contexts.Require<_gramio_contexts.MessageContext<AnyBot>, "from">) & { args: RegExpMatchArray | null; } & _gramio_composer.EventContextOf<TThis, "guest_message">) => unknown), maybeHandler?: (context: (_gramio_contexts.MessageContext<AnyBot> & _gramio_contexts.Require<_gramio_contexts.MessageContext<AnyBot>, "from">) & { args: RegExpMatchArray | null; } & _gramio_composer.EventContextOf<TThis, "guest_message">) => unknown, macroOptions?: Record<string, unknown>): TThis; hears<TThis extends _gramio_composer.ComposerLike<TThis> & { "~": { macros: MacroDefinitions; commandsMeta?: Map<string, unknown>; Derives?: Record<string, object>; }; chosenInlineResult(trigger: any, handler: any, macroOptions?: any): TThis; }>(this: TThis, trigger: RegExp | MaybeArray<string> | ((context: _gramio_contexts.MessageContext<AnyBot> & _gramio_contexts.Require<_gramio_contexts.MessageContext<AnyBot>, "from">) => boolean), handler: (context: (_gramio_contexts.MessageContext<AnyBot> & _gramio_contexts.Require<_gramio_contexts.MessageContext<AnyBot>, "from">) & { args: RegExpMatchArray | null; } & _gramio_composer.EventContextOf<TThis, "message">) => unknown, macroOptions?: Record<string, unknown>): TThis; command<TThis extends _gramio_composer.ComposerLike<TThis> & { "~": { macros: MacroDefinitions; commandsMeta?: Map<string, unknown>; Derives?: Record<string, object>; }; chosenInlineResult(trigger: any, handler: any, macroOptions?: any): TThis; }>(this: TThis, command: MaybeArray<string>, handlerOrMeta: ((context: (_gramio_contexts.MessageContext<AnyBot> & _gramio_contexts.Require<_gramio_contexts.MessageContext<AnyBot>, "from">) & { args: string | null; } & _gramio_composer.EventContextOf<TThis, "message">) => unknown) | CommandMeta, handlerOrOptions?: ((context: (_gramio_contexts.MessageContext<AnyBot> & _gramio_contexts.Require<_gramio_contexts.MessageContext<AnyBot>, "from">) & { args: string | null; } & _gramio_composer.EventContextOf<TThis, "message">) => unknown) | Record<string, unknown>, macroOptions?: Record<string, unknown>): TThis; startParameter<TThis extends _gramio_composer.ComposerLike<TThis> & { "~": { macros: MacroDefinitions; commandsMeta?: Map<string, unknown>; Derives?: Record<string, object>; }; chosenInlineResult(trigger: any, handler: any, macroOptions?: any): TThis; }>(this: TThis, parameter: RegExp | MaybeArray<string>, handler: Handler<(_gramio_contexts.MessageContext<AnyBot> & _gramio_contexts.Require<_gramio_contexts.MessageContext<AnyBot>, "from">) & { rawStartPayload: string; } & _gramio_composer.EventContextOf<TThis, "message">>, macroOptions?: Record<string, unknown>): TThis; }; /** Store plugin preRequests hooks */ preRequests: [Hooks.PreRequest<any>, MaybeArray<keyof APIMethods> | undefined][]; /** Store plugin onResponses hooks */ onResponses: [Hooks.OnResponse<any>, MaybeArray<keyof APIMethods> | undefined][]; /** Store plugin onResponseErrors hooks */ onResponseErrors: [Hooks.OnResponseError<any>, MaybeArray<keyof APIMethods> | undefined][]; /** Store plugin onApiCalls hooks */ onApiCalls: [Hooks.OnApiCall<any>, MaybeArray<keyof APIMethods> | undefined][]; /** * Store plugin groups * * If you use `on` or `use` in group and on plugin-level groups handlers are registered after plugin-level handlers * */ groups: ((bot: AnyBot) => AnyBot)[]; /** Store plugin onStarts hooks */ onStarts: Hooks.OnStart[]; /** Store plugin onStops hooks */ onStops: Hooks.OnStop[]; /** Store plugin onErrors hooks */ onErrors: Hooks.OnError<any, any>[]; /** Map of plugin errors */ errorsDefinitions: Record<string, { new (...args: any): any; prototype: Error; }>; decorators: Record<string, unknown>; }; /** Expose composer internals so `composer.extend(plugin)` works via duck-typing */ get "~"(): Omit<InstanceType<typeof Composer>["~"], "Out" | "Derives"> & { Out: Derives["global"]; Derives: Omit<Derives, "global">; }; /** Create new Plugin. Please provide `name` */ constructor(name: string, { dependencies }?: { dependencies?: string[]; }); /** Currently not isolated!!! * * > [!WARNING] * > If you use `on` or `use` in a `group` and at the plugin level, the group handlers are registered **after** the handlers at the plugin level */ group(grouped: (bot: Bot<Errors, Derives>) => AnyBot): this; /** * Register custom class-error in plugin **/ error<Name extends string, NewError extends { new (...args: any): any; prototype: Error; }>(kind: Name, error: NewError): Plugin<Errors & { [name in Name]: InstanceType<NewError>; }, Derives, Macros>; /** * Derive some data to handlers * * @example * ```ts * new Bot("token").derive((context) => { * return { * superSend: () => context.send("Derived method") * } * }) * ``` */ derive<Handler extends Hooks.Derive<Context<BotLike> & Derives["global"]>>(handler: Handler): Plugin<Errors, Derives & { global: Awaited<ReturnType<Handler>>; }, Macros>; derive<Update extends UpdateName, Handler extends Hooks.Derive<ContextType<BotLike, Update> & Derives["global"] & Derives[Update]>>(updateName: MaybeArray<Update>, handler: Handler): Plugin<Errors, Derives & { [K in Update]: Awaited<ReturnType<Handler>>; }, Macros>; decorate<Value extends Record<string, any>>(value: Value): Plugin<Errors, Derives & { global: { [K in keyof Value]: Value[K]; }; }, Macros>; decorate<Name extends string, Value>(name: Name, value: Value): Plugin<Errors, Derives & { global: { [K in Name]: Value; }; }, Macros>; /** * Register a single named macro definition on this plugin */ macro<const Name extends string, TDef extends MacroDef<any, any>>(name: Name, definition: TDef): Plugin<Errors, Derives, Macros & Record<Name, TDef>>; /** Register multiple macro definitions at once */ macro<const TDefs extends Record<string, MacroDef<any, any>>>(definitions: TDefs): Plugin<Errors, Derives, Macros & TDefs>; /** Register handler with a type-narrowing filter (auto-discovers matching events) */ on<Narrowing>(filter: (ctx: any) => ctx is Narrowing, handler: Handler<ContextType<BotLike, CompatibleUpdates$1<BotLike, Narrowing>> & Derives["global"] & Narrowing>): this; /** Register handler with a boolean filter (all updates) */ on(filter: (ctx: Context<BotLike> & Derives["global"]) => boolean, handler: Handler<Context<BotLike> & Derives["global"]>): this; /** Register handler to one or many Updates with a type-narrowing filter */ on<T extends UpdateName, Narrowing>(updateName: MaybeArray<T>, filter: (ctx: any) => ctx is Narrowing, handler: Handler<ContextType<BotLike, T> & Derives["global"] & Derives[T] & Narrowing>): this; /** Register handler to one or many Updates with a boolean filter (no type narrowing) */ on<T extends UpdateName>(updateName: MaybeArray<T>, filter: (ctx: ContextType<BotLike, T> & Derives["global"] & Derives[T]) => boolean, handler: Handler<ContextType<BotLike, T> & Derives["global"] & Derives[T]>): this; /** Register handler to one or many Updates */ on<T extends UpdateName>(updateName: MaybeArray<T>, handler: Handler<ContextType<BotLike, T> & Derives["global"] & Derives[T]>): this; /** Register handler to any Updates */ use(handler: Handler<Context<BotLike> & Derives["global"]>): this; /** * This hook called before sending a request to Telegram Bot API (allows us to impact the sent parameters). * * @example * ```typescript * import { Bot } from "gramio"; * * const bot = new Bot(process.env.TOKEN!).preRequest((context) => { * if (context.method === "sendMessage") { * context.params.text = "mutate params"; * } * * return context; * }); * * bot.start(); * ``` * * [Documentation](https://gramio.dev/hooks/pre-request.html) * */ preRequest<Methods extends keyof APIMethods, Handler extends Hooks.PreRequest<Methods>>(methods: MaybeArray<Methods>, handler: Handler): this; preRequest(handler: Hooks.PreRequest): this; /** * This hook called when API return successful response * * [Documentation](https://gramio.dev/hooks/on-response.html) * */ onResponse<Methods extends keyof APIMethods, Handler extends Hooks.OnResponse<Methods>>(methods: MaybeArray<Methods>, handler: Handler): this; onResponse(handler: Hooks.OnResponse): this; /** * This hook called when API return an error * * [Documentation](https://gramio.dev/hooks/on-response-error.html) * */ onResponseError<Methods extends keyof APIMethods, Handler extends Hooks.OnResponseError<Methods>>(methods: MaybeArray<Methods>, handler: Handler): this; onResponseError(handler: Hooks.OnResponseError): this; /** * This hook wraps the entire API call, enabling tracing/instrumentation. * * @example * ```typescript * const plugin = new Plugin("example").onApiCall(async (context, next) => { * console.log(`Calling ${context.method}`); * const result = await next(); * console.log(`${context.method} completed`); * return result; * }); * ``` * */ onApiCall<Methods extends keyof APIMethods, Handler extends Hooks.OnApiCall<Methods>>(methods: MaybeArray<Methods>, handler: Handler): this; onApiCall(handler: Hooks.OnApiCall): this; /** * This hook called when the bot is `started`. * * @example * ```typescript * import { Bot } from "gramio"; * * const bot = new Bot(process.env.TOKEN!).onStart( * ({ plugins, info, updatesFrom, bot }) => { * console.log(`plugin list - ${plugins.join(", ")}`); * console.log(`bot username is @${info.username}`); * console.log(`updates from ${updatesFrom}`); * } * ); * * bot.start(); * ``` * * [Documentation](https://gramio.dev/hooks/on-start.html) * */ onStart(handler: Hooks.OnStart): this; /** * This hook called when the bot stops. * * @example * ```typescript * import { Bot } from "gramio"; * * const bot = new Bot(process.env.TOKEN!).onStop( * ({ plugins, info, bot }) => { * console.log(`plugin list - ${plugins.join(", ")}`); * console.log(`bot username is @${info.username}`); * } * ); * * bot.start(); * bot.stop(); * ``` * * [Documentation](https://gramio.dev/hooks/on-stop.html) * */ onStop(handler: Hooks.OnStop): this; /** * Set error handler. * @example * ```ts * bot.onError("message", ({ context, kind, error }) => { * return context.send(`${kind}: ${error.message}`); * }) * ``` */ onError<T extends UpdateName>(updateName: MaybeArray<T>, handler: Hooks.OnError<Errors, ContextType<BotLike, T> & Derives["global"] & Derives[T]>): this; onError(handler: Hooks.OnError<Errors, Context<BotLike> & Derives["global"]>): this; /** Extend plugin with a Composer instance (merges middleware with deduplication) */ extend<UExposed extends object, UDerives extends Record<string, object>>(composer: EventComposer<any, any, any, any, UExposed, UDerives>): Plugin<Errors, Derives & { global: UExposed; } & UDerives>; /** Extend plugin with another Plugin (merges middleware, hooks, decorators, error definitions, groups, and dependencies) */ extend<NewPlugin extends AnyPlugin>(plugin: MaybePromise<NewPlugin>): Plugin<Errors & NewPlugin["_"]["Errors"], Derives & NewPlugin["_"]["Derives"], Macros & NewPlugin["_"]["Macros"]>; } interface Plugin<Errors, Derives, Macros> { /** Register callback query handler */ callbackQuery: (typeof methods)["callbackQuery"]; /** Register command handler */ command: (typeof methods)["command"]; /** Register text/caption pattern handler */ hears: (typeof methods)["hears"]; /** Register reaction handler */ reaction: (typeof methods)["reaction"]; /** Register inline query handler */ inlineQuery: (typeof methods)["inlineQuery"]; /** Register guest query (`guest_message`) handler */ guestQuery: (typeof methods)["guestQuery"]; /** Register chosen inline result handler */ chosenInlineResult: (typeof methods)["chosenInlineResult"]; /** Register deep-link parameter handler */ startParameter: (typeof methods)["startParameter"]; } /** Bot options that you can provide to {@link Bot} constructor */ interface BotOptions { /** Bot token */ token: string; /** When the bot begins to listen for updates, `GramIO` retrieves information about the bot to verify if the **bot token is valid** * and to utilize some bot metadata. For example, this metadata will be used to strip bot mentions in commands. * * If you set it up, `GramIO` will not send a `getMe` request on startup. * * @important * **You should set this up when horizontally scaling your bot or working in serverless environments.** * */ info?: TelegramUser; /** List of plug