Skip to content

GramIO API Reference / gramio/dist / Plugin

Class: Plugin<Errors, Derives, Macros>

Defined in: gramio/index.d.ts:120

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);
    });

Type Parameters

Type ParameterDefault type
Errors extends ErrorDefinitionsobject
Derives extends DeriveDefinitionsDeriveDefinitions
Macros extends MacroDefinitionsobject

Constructors

Constructor

new Plugin<Errors, Derives, Macros>(name, __namedParameters?): Plugin<Errors, Derives, Macros>

Defined in: gramio/index.d.ts:376

Create new Plugin. Please provide name

Parameters

ParameterType
namestring
__namedParameters?{ dependencies?: string[]; }
__namedParameters.dependencies?string[]

Returns

Plugin<Errors, Derives, Macros>

Properties

PropertyTypeDescriptionDefined in
_objectInternal Set of Plugin datagramio/index.d.ts:127
_.composerEventComposer<Context<AnyBot>, { boost_added: BoostAddedContext<AnyBot>; business_connection: BusinessConnectionContext<AnyBot>; business_message: MessageContext<AnyBot> & Require<MessageContext<AnyBot>, "from">; callback_query: CallbackQueryContext<AnyBot>; channel_post: MessageContext<AnyBot>; chat_background_set: ChatBackgroundSetContext<AnyBot>; chat_boost: ChatBoostContext<AnyBot>; chat_join_request: ChatJoinRequestContext<AnyBot>; chat_member: ChatMemberContext<AnyBot>; chat_owner_changed: ChatOwnerChangedContext<AnyBot>; chat_owner_left: ChatOwnerLeftContext<AnyBot>; chat_shared: ChatSharedContext<AnyBot>; checklist_tasks_added: ChecklistTasksAddedContext<AnyBot>; checklist_tasks_done: ChecklistTasksDoneContext<AnyBot>; chosen_inline_result: ChosenInlineResultContext<AnyBot>; delete_chat_photo: DeleteChatPhotoContext<AnyBot>; deleted_business_messages: BusinessMessagesDeletedContext<AnyBot>; direct_message_price_changed: DirectMessagePriceChangedContext<AnyBot>; edited_business_message: MessageContext<AnyBot> & Require<MessageContext<AnyBot>, "from">; edited_channel_post: MessageContext<AnyBot> & Require<MessageContext<AnyBot>, "from">; edited_message: MessageContext<AnyBot> & Require<MessageContext<AnyBot>, "from">; forum_topic_closed: ForumTopicClosedContext<AnyBot>; forum_topic_created: ForumTopicCreatedContext<AnyBot>; forum_topic_edited: ForumTopicEditedContext<AnyBot>; forum_topic_reopened: ForumTopicReopenedContext<AnyBot>; general_forum_topic_hidden: GeneralForumTopicHiddenContext<AnyBot>; general_forum_topic_unhidden: GeneralForumTopicUnhiddenContext<AnyBot>; gift: GiftContext<AnyBot>; gift_upgrade_sent: GiftUpgradeSentContext<AnyBot>; giveaway_completed: GiveawayCompletedContext<AnyBot>; giveaway_created: GiveawayCreatedContext<AnyBot>; giveaway_winners: GiveawayWinnersContext<AnyBot>; group_chat_created: GroupChatCreatedContext<AnyBot>; inline_query: InlineQueryContext<AnyBot>; invoice: InvoiceContext<AnyBot>; left_chat_member: LeftChatMemberContext<AnyBot>; location: LocationContext<AnyBot>; message: MessageContext<AnyBot> & Require<MessageContext<AnyBot>, "from">; message_auto_delete_timer_changed: MessageAutoDeleteTimerChangedContext<AnyBot>; message_reaction: MessageReactionContext<AnyBot>; message_reaction_count: MessageReactionCountContext<AnyBot>; migrate_from_chat_id: MigrateFromChatIdContext<AnyBot>; migrate_to_chat_id: MigrateToChatIdContext<AnyBot>; my_chat_member: ChatMemberContext<AnyBot>; new_chat_members: NewChatMembersContext<AnyBot>; new_chat_photo: NewChatPhotoContext<AnyBot>; new_chat_title: NewChatTitleContext<AnyBot>; paid_message_price_changed: PaidMessagePriceChangedContext<AnyBot>; passport_data: PassportDataContext<AnyBot>; pinned_message: PinnedMessageContext<AnyBot>; poll: PollContext<AnyBot>; poll_answer: PollAnswerContext<AnyBot>; pre_checkout_query: PreCheckoutQueryContext<AnyBot>; proximity_alert_triggered: ProximityAlertTriggeredContext<AnyBot>; purchased_paid_media: PaidMediaPurchasedContext<AnyBot>; refunded_payment: RefundedPaymentContext<AnyBot>; removed_chat_boost: RemovedChatBoostContext<AnyBot>; service_message: MessageContext<AnyBot>; shipping_query: ShippingQueryContext<AnyBot>; successful_payment: SuccessfulPaymentContext<AnyBot>; suggested_post_approval_failed: SuggestedPostApprovalFailedContext<AnyBot>; suggested_post_approved: SuggestedPostApprovedContext<AnyBot>; suggested_post_declined: SuggestedPostDeclinedContext<AnyBot>; suggested_post_paid: SuggestedPostPaidContext<AnyBot>; suggested_post_refunded: SuggestedPostRefundedContext<AnyBot>; unique_gift: UniqueGiftContext<AnyBot>; users_shared: UsersSharedContext<AnyBot>; video_chat_ended: VideoChatEndedContext<AnyBot>; video_chat_participants_invited: VideoChatParticipantsInvitedContext<AnyBot>; video_chat_scheduled: VideoChatScheduledContext<AnyBot>; video_chat_started: VideoChatStartedContext<AnyBot>; web_app_data: WebAppDataContext<AnyBot>; write_access_allowed: WriteAccessAllowedContext<AnyBot>; }, Context<AnyBot>, Context<AnyBot>, { }, { }, { callbackQuery: TThis; chosenInlineResult: TThis; command: TThis; hears: TThis; inlineQuery: TThis; reaction: TThis; startParameter: TThis; }, { }> & objectComposergramio/index.d.ts:139
_.decoratorsRecord<string, unknown>-gramio/index.d.ts:371
_.dependenciesstring[]List of plugin dependencies. If user does't extend from listed there dependencies it throw a errorgramio/index.d.ts:131
_.DerivesDerivesremap generic type. {} in runtimegramio/index.d.ts:135
_.ErrorsErrorsremap generic type. {} in runtimegramio/index.d.ts:133
_.errorsDefinitionsRecord<string, {(...args): any; prototype: Error; }>Map of plugin errorsgramio/index.d.ts:367
_.groups(bot) => AnyBot[]Store plugin groups If you use on or use in group and on plugin-level groups handlers are registered after plugin-level handlersgramio/index.d.ts:359
_.MacrosMacrosremap generic type. {} in runtimegramio/index.d.ts:137
_.namestringName of plugingramio/index.d.ts:129
_.onApiCalls[OnApiCall<any>, MaybeArray<keyof APIMethods>][]Store plugin onApiCalls hooksgramio/index.d.ts:353
_.onErrorsOnError<any, any>[]Store plugin onErrors hooksgramio/index.d.ts:365
_.onResponseErrors[OnResponseError<any>, MaybeArray<keyof APIMethods>][]Store plugin onResponseErrors hooksgramio/index.d.ts:351
_.onResponses[OnResponse<any>, MaybeArray<keyof APIMethods>][]Store plugin onResponses hooksgramio/index.d.ts:349
_.onStartsOnStart[]Store plugin onStarts hooksgramio/index.d.ts:361
_.onStopsOnStop[]Store plugin onStops hooksgramio/index.d.ts:363
_.preRequests[PreRequest<any>, MaybeArray<keyof APIMethods>][]Store plugin preRequests hooksgramio/index.d.ts:347

Accessors

~

Get Signature

get ~(): object

Defined in: gramio/index.d.ts:374

Expose composer internals so composer.extend(plugin) works via duck-typing

Returns
NameTypeDescriptionDefined in
compiledComposedMiddleware<any>-composer/index.d.ts:311
DerivesTDerives-composer/index.d.ts:320
errorsDefinitionsRecord<string, {(...args): any; prototype: Error; }>-composer/index.d.ts:314
extendedSet<string>-composer/index.d.ts:310
macrosRecord<string, MacroDef<any, any>>-composer/index.d.ts:319
middlewaresScopedMiddleware<any>[]-composer/index.d.ts:308
namestring-composer/index.d.ts:312
onErrorsErrorHandler<any>[]-composer/index.d.ts:309
OutContextPhantom type accessor — never set at runtime, used by ContextOf<T>composer/index.d.ts:322
seedunknown-composer/index.d.ts:313
tracerTraceHandler-composer/index.d.ts:318

Methods

decorate()

Call Signature

decorate<Value>(value): Plugin<Errors, Derives & object, Macros>

Defined in: gramio/index.d.ts:410

Type Parameters
Type Parameter
Value extends Record<string, any>
Parameters
ParameterType
valueValue
Returns

Plugin<Errors, Derives & object, Macros>

Call Signature

decorate<Name, Value>(name, value): Plugin<Errors, Derives & object, Macros>

Defined in: gramio/index.d.ts:415

Type Parameters
Type Parameter
Name extends string
Value
Parameters
ParameterType
nameName
valueValue
Returns

Plugin<Errors, Derives & object, Macros>


derive()

Call Signature

derive<Handler>(handler): Plugin<Errors, Derives & object, Macros>

Defined in: gramio/index.d.ts:404

Derive some data to handlers

Type Parameters
Type Parameter
Handler extends Derive<Context<BotLike> & Derives["global"]>
Parameters
ParameterType
handlerHandler
Returns

Plugin<Errors, Derives & object, Macros>

Example
ts
new Bot("token").derive((context) => {
		return {
			superSend: () => context.send("Derived method")
		}
})

Call Signature

derive<Update, Handler>(updateName, handler): Plugin<Errors, Derives & { [K in UpdateName]: Awaited<ReturnType<Handler>> }, Macros>

Defined in: gramio/index.d.ts:407

Derive some data to handlers

Type Parameters
Type Parameter
Update extends UpdateName
Handler extends Derive<InstanceType<ContextsMapping<BotLike>[Update]> & object & Record<UpdateName | "global", { }>[Update] & Derives["global"] & Derives[Update]>
Parameters
ParameterType
updateNameMaybeArray<Update>
handlerHandler
Returns

Plugin<Errors, Derives & { [K in UpdateName]: Awaited<ReturnType<Handler>> }, Macros>

Example
ts
new Bot("token").derive((context) => {
		return {
			superSend: () => context.send("Derived method")
		}
})

error()

error<Name, NewError>(kind, error): Plugin<Errors & { [name in string]: InstanceType<NewError> }, Derives, Macros>

Defined in: gramio/index.d.ts:388

Register custom class-error in plugin

Type Parameters

Type Parameter
Name extends string
NewError extends {(...args): any; prototype: Error; }

Parameters

ParameterType
kindName
errorNewError

Returns

Plugin<Errors & { [name in string]: InstanceType<NewError> }, Derives, Macros>


extend()

Call Signature

extend<UExposed, UDerives>(composer): Plugin<Errors, Derives & object & UDerives>

Defined in: gramio/index.d.ts:543

Extend plugin with a Composer instance (merges middleware with deduplication)

Type Parameters
Type Parameter
UExposed extends object
UDerives extends Record<string, object>
Parameters
ParameterType
composerEventComposer<any, any, any, any, UExposed, UDerives>
Returns

Plugin<Errors, Derives & object & UDerives>

Call Signature

extend<NewPlugin>(plugin): Plugin<Errors & NewPlugin["_"]["Errors"], Derives & NewPlugin["_"]["Derives"]>

Defined in: gramio/index.d.ts:548

! ** At the moment, it can only pick up types**

Type Parameters
Type Parameter
NewPlugin extends AnyPlugin
Parameters
ParameterType
pluginMaybePromise<NewPlugin>
Returns

Plugin<Errors & NewPlugin["_"]["Errors"], Derives & NewPlugin["_"]["Derives"]>


group()

group(grouped): this

Defined in: gramio/index.d.ts:384

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

Parameters

ParameterType
grouped(bot) => AnyBot

Returns

this


macro()

Call Signature

macro<Name, TDef>(name, definition): Plugin<Errors, Derives, Macros & Record<Name, TDef>>

Defined in: gramio/index.d.ts:423

Register a single named macro definition on this plugin

Type Parameters
Type Parameter
Name extends string
TDef extends MacroDef<any, any>
Parameters
ParameterType
nameName
definitionTDef
Returns

Plugin<Errors, Derives, Macros & Record<Name, TDef>>

Call Signature

macro<TDefs>(definitions): Plugin<Errors, Derives, Macros & TDefs>

Defined in: gramio/index.d.ts:425

Register multiple macro definitions at once

Type Parameters
Type Parameter
TDefs extends Record<string, MacroDef<any, any>>
Parameters
ParameterType
definitionsTDefs
Returns

Plugin<Errors, Derives, Macros & TDefs>


on()

Call Signature

on<Narrowing>(filter, handler): this

Defined in: gramio/index.d.ts:427

Register handler with a type-narrowing filter (auto-discovers matching events)

Type Parameters
Type Parameter
Narrowing
Parameters
ParameterType
filter(ctx) => ctx is Narrowing
handlerHandler<InstanceType<ContextsMapping<BotLike>[CompatibleUpdates$1<BotLike, Narrowing>]> & object & Record<UpdateName | "global", { }>[CompatibleUpdates$1<BotLike, Narrowing>] & Derives["global"] & Narrowing>
Returns

this

Call Signature

on(filter, handler): this

Defined in: gramio/index.d.ts:429

Register handler with a boolean filter (all updates)

Parameters
ParameterType
filter(ctx) => boolean
handlerHandler<Context<BotLike> & Derives["global"]>
Returns

this

Call Signature

on<T, Narrowing>(updateName, filter, handler): this

Defined in: gramio/index.d.ts:431

Register handler to one or many Updates with a type-narrowing filter

Type Parameters
Type Parameter
T extends UpdateName
Narrowing
Parameters
ParameterType
updateNameMaybeArray<T>
filter(ctx) => ctx is Narrowing
handlerHandler<InstanceType<ContextsMapping<BotLike>[T]> & object & Record<UpdateName | "global", { }>[T] & Derives["global"] & Derives[T] & Narrowing>
Returns

this

Call Signature

on<T>(updateName, filter, handler): this

Defined in: gramio/index.d.ts:433

Register handler to one or many Updates with a boolean filter (no type narrowing)

Type Parameters
Type Parameter
T extends UpdateName
Parameters
ParameterType
updateNameMaybeArray<T>
filter(ctx) => boolean
handlerHandler<InstanceType<ContextsMapping<BotLike>[T]> & object & Record<UpdateName | "global", { }>[T] & Derives["global"] & Derives[T]>
Returns

this

Call Signature

on<T>(updateName, handler): this

Defined in: gramio/index.d.ts:435

Register handler to one or many Updates

Type Parameters
Type Parameter
T extends UpdateName
Parameters
ParameterType
updateNameMaybeArray<T>
handlerHandler<InstanceType<ContextsMapping<BotLike>[T]> & object & Record<UpdateName | "global", { }>[T] & Derives["global"] & Derives[T]>
Returns

this


onApiCall()

Call Signature

onApiCall<Methods, Handler>(methods, handler): this

Defined in: gramio/index.d.ts:487

This hook wraps the entire API call, enabling tracing/instrumentation.

Type Parameters
Type Parameter
Methods extends keyof APIMethods
Handler extends OnApiCall<Methods>
Parameters
ParameterType
methodsMaybeArray<Methods>
handlerHandler
Returns

this

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;
});

Call Signature

onApiCall(handler): this

Defined in: gramio/index.d.ts:488

This hook wraps the entire API call, enabling tracing/instrumentation.

Parameters
ParameterType
handlerOnApiCall
Returns

this

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;
});

onError()

Call Signature

onError<T>(updateName, handler): this

Defined in: gramio/index.d.ts:540

Set error handler.

Type Parameters
Type Parameter
T extends UpdateName
Parameters
ParameterType
updateNameMaybeArray<T>
handlerOnError<Errors, InstanceType<ContextsMapping<BotLike>[T]> & object & Record<UpdateName | "global", { }>[T] & Derives["global"] & Derives[T]>
Returns

this

Example
ts
bot.onError("message", ({ context, kind, error }) => {
	return context.send(`${kind}: ${error.message}`);
})

Call Signature

onError(handler): this

Defined in: gramio/index.d.ts:541

Set error handler.

Parameters
ParameterType
handlerOnError<Errors, Context<BotLike> & Derives["global"]>
Returns

this

Example
ts
bot.onError("message", ({ context, kind, error }) => {
	return context.send(`${kind}: ${error.message}`);
})

onResponse()

Call Signature

onResponse<Methods, Handler>(methods, handler): this

Defined in: gramio/index.d.ts:465

This hook called when API return successful response

Documentation

Type Parameters
Type Parameter
Methods extends keyof APIMethods
Handler extends OnResponse<Methods>
Parameters
ParameterType
methodsMaybeArray<Methods>
handlerHandler
Returns

this

Call Signature

onResponse(handler): this

Defined in: gramio/index.d.ts:466

This hook called when API return successful response

Documentation

Parameters
ParameterType
handlerOnResponse
Returns

this


onResponseError()

Call Signature

onResponseError<Methods, Handler>(methods, handler): this

Defined in: gramio/index.d.ts:472

This hook called when API return an error

Documentation

Type Parameters
Type Parameter
Methods extends keyof APIMethods
Handler extends OnResponseError<Methods>
Parameters
ParameterType
methodsMaybeArray<Methods>
handlerHandler
Returns

this

Call Signature

onResponseError(handler): this

Defined in: gramio/index.d.ts:473

This hook called when API return an error

Documentation

Parameters
ParameterType
handlerOnResponseError
Returns

this


onStart()

onStart(handler): this

Defined in: gramio/index.d.ts:509

This hook called when the bot is started.

Parameters

ParameterType
handlerOnStart

Returns

this

Example

typescript
import { Bot } from "gramio";

const bot = new Bot(process.env.TOKEN!).onStart(
    ({ plugins, info, updatesFrom }) => {
        console.log(`plugin list - ${plugins.join(", ")}`);
        console.log(`bot username is @${info.username}`);
		   console.log(`updates from ${updatesFrom}`);
    }
);

bot.start();

Documentation


onStop()

onStop(handler): this

Defined in: gramio/index.d.ts:530

This hook called when the bot stops.

Parameters

ParameterType
handlerOnStop

Returns

this

Example

typescript
import { Bot } from "gramio";

const bot = new Bot(process.env.TOKEN!).onStop(
    ({ plugins, info, updatesFrom }) => {
        console.log(`plugin list - ${plugins.join(", ")}`);
        console.log(`bot username is @${info.username}`);
    }
);

bot.start();
bot.stop();

Documentation


preRequest()

Call Signature

preRequest<Methods, Handler>(methods, handler): this

Defined in: gramio/index.d.ts:458

This hook called before sending a request to Telegram Bot API (allows us to impact the sent parameters).

Type Parameters
Type Parameter
Methods extends keyof APIMethods
Handler extends PreRequest<Methods>
Parameters
ParameterType
methodsMaybeArray<Methods>
handlerHandler
Returns

this

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

Call Signature

preRequest(handler): this

Defined in: gramio/index.d.ts:459

This hook called before sending a request to Telegram Bot API (allows us to impact the sent parameters).

Parameters
ParameterType
handlerPreRequest
Returns

this

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


use()

use(handler): this

Defined in: gramio/index.d.ts:437

Register handler to any Updates

Parameters

ParameterType
handlerHandler<Context<BotLike> & Derives["global"]>

Returns

this