Skip to content

GramIO API Reference / gramio/dist / Bot

Class: Bot<Errors, Derives, Macros>

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

Bot instance

Example

ts
import { Bot } from "gramio";

const bot = new Bot("") // put you token here
    .command("start", (context) => context.send("Hi!"))
    .onStart(console.log);

bot.start();

Type Parameters

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

Constructors

Constructor

new Bot<Errors, Derives, Macros>(token, options?): Bot<Errors, Derives, Macros>

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

Parameters

ParameterType
tokenstring
options?Omit<BotOptions, "token" | "api"> & object

Returns

Bot<Errors, Derives, Macros>

Constructor

new Bot<Errors, Derives, Macros>(options): Bot<Errors, Derives, Macros>

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

Parameters

ParameterType
optionsOmit<BotOptions, "api"> & object

Returns

Bot<Errors, Derives, Macros>

Properties

PropertyModifierTypeDescriptionDefined in
_publicobjectDeprecated use ~ insteadgramio/index.d.ts:876
_.derivespublicDerivesDeprecated @internal. Remap genericgramio/index.d.ts:878
__DerivespublicDerivesDeprecated use ~.derives instead @internal. Remap genericgramio/index.d.ts:881
~publicobject-gramio/index.d.ts:882
~.derivespublicDerivesDeprecated @internal. Remap genericgramio/index.d.ts:884
apireadonlySuppressedAPIMethodsSend API Request to Telegram Bot API Example const response = await bot.api.sendMessage({ chat_id: "@gramio_forum", text: "some text", }); Documentationgramio/index.d.ts:903
infopublicTelegramUserBot data (filled in when calling bot.init/bot.start)gramio/index.d.ts:889
optionsreadonlyBotOptionsOptions provided to instancegramio/index.d.ts:887
updatespublicUpdatesThis instance handle updatesgramio/index.d.ts:909

Methods

callbackQuery()

callbackQuery<Trigger, TOptions>(trigger, handler, options?): this

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

Register handler to callback_query event

Type Parameters

Type ParameterDefault type
Trigger extends string | RegExp | CallbackData<Record<never, never>, Record<never, never>>-
TOptions extends HandlerOptions<CallbackQueryShorthandContext<Bot<Errors, Derives, Macros>, Trigger>, Macros>object

Parameters

ParameterType
triggerTrigger
handler(context) => unknown
options?TOptions

Returns

this

Example

ts
const someData = new CallbackData("example").number("id");

new Bot()
    .command("start", (context) =>
        context.send("some", {
            reply_markup: new InlineKeyboard().text(
                "example",
                someData.pack({
                    id: 1,
                })
            ),
        })
    )
    .callbackQuery(someData, (context) => {
        context.queryData; // is type-safe
    });

chosenInlineResult()

chosenInlineResult<Ctx, TOptions>(trigger, handler, options?): this

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

Register handler to chosen_inline_result update

Type Parameters

Type ParameterDefault type
CtxContextType<Bot<Errors, Derives, Macros>, "chosen_inline_result">
TOptions extends HandlerOptions<Ctx, Macros>object

Parameters

ParameterType
triggerstring | RegExp | (context) => boolean
handler(context) => unknown
options?TOptions

Returns

this


command()

command<TOptions>(command, handler, options?): this

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

Register handler to message and business_message event when entities contains a command

Type Parameters

Type ParameterDefault type
TOptions extends HandlerOptions<ContextType<Bot<Errors, Derives, Macros>, "message">, Macros>object

Parameters

ParameterType
commandMaybeArray<string>
handler(context) => unknown
options?TOptions

Returns

this

Example

ts
new Bot().command("start", async (context) => {
    return context.send(`You message is /start ${context.args}`);
});

decorate()

Call Signature

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

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

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

Bot<Errors, Derives & object, Macros>

Call Signature

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

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

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

Bot<Errors, Derives & object, Macros>


derive()

Call Signature

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

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

Derive some data to handlers

Type Parameters
Type Parameter
Handler extends Derive<Context<Bot<Errors, Derives, Macros>> & Derives["global"]>
Parameters
ParameterType
handlerHandler
Returns

Bot<Errors, Derives & object, Macros>

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

Call Signature

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

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

Derive some data to handlers

Type Parameters
Type Parameter
Update extends UpdateName
Handler extends Derive<InstanceType<ContextsMapping<Bot<Errors, Derives, Macros>>[Update]> & Derives["global"] & Derives[Update]>
Parameters
ParameterType
updateNameMaybeArray<Update>
handlerHandler
Returns

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

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

downloadFile()

Call Signature

downloadFile(attachment): Promise<ArrayBuffer>

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

Download file

Parameters
ParameterType
attachmentstring | Attachment | { file_id: string; }
Returns

Promise<ArrayBuffer>

Example
ts
bot.on("message", async (context) => {
    if (!context.document) return;
    // download to ./file-name
    await context.download(context.document.fileName || "file-name");
    // get ArrayBuffer
    const buffer = await context.download();

    return context.send("Thank you!");
});

Documentation

Call Signature

downloadFile(attachment, path): Promise<string>

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

Download file

Parameters
ParameterType
attachmentstring | Attachment | { file_id: string; }
pathstring
Returns

Promise<string>

Example
ts
bot.on("message", async (context) => {
    if (!context.document) return;
    // download to ./file-name
    await context.download(context.document.fileName || "file-name");
    // get ArrayBuffer
    const buffer = await context.download();

    return context.send("Thank you!");
});

Documentation


error()

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

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

Register custom class-error for type-safe catch in onError hook

Type Parameters

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

Parameters

ParameterType
kindName
errorNewError

Returns

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

Example

ts
export class NoRights extends Error {
    needRole: "admin" | "moderator";

    constructor(role: "admin" | "moderator") {
        super();
        this.needRole = role;
    }
}

const bot = new Bot(process.env.TOKEN!)
    .error("NO_RIGHTS", NoRights)
    .onError(({ context, kind, error }) => {
        if (context.is("message") && kind === "NO_RIGHTS")
            return context.send(
                format`You don't have enough rights! You need to have an «${bold(
                    error.needRole
                )}» role.`
            );
    });

bot.updates.on("message", (context) => {
    if (context.text === "bun") throw new NoRights("admin");
});

extend()

Call Signature

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

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

Extend Plugin logic and types

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

Bot<Errors, Derives & object & UDerives, Macros>

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

Call Signature

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

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

Extend Plugin logic and types

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

Bot<Errors & NewPlugin["_"]["Errors"], Derives & NewPlugin["_"]["Derives"], Macros & NewPlugin["_"]["Macros"]>

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

group()

group(grouped): Bot<Errors, Derives, Macros>

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

Currently not isolated!!!

Parameters

ParameterType
grouped(bot) => AnyBot

Returns

Bot<Errors, Derives, Macros>


hears()

hears<Ctx, Trigger, TOptions>(trigger, handler, options?): this

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

Register handler to message and business_message event

Type Parameters

Type ParameterDefault type
CtxContextType<Bot<Errors, Derives, Macros>, "message">
Trigger extends RegExp | MaybeArray<string> | (context) => booleanRegExp | MaybeArray<string> | (context) => boolean
TOptions extends HandlerOptions<Ctx, Macros>object

Parameters

ParameterType
triggerTrigger
handler(context) => unknown
options?TOptions

Returns

this

Example

ts
new Bot().hears(/regular expression with (.*)/i, async (context) => {
    if (context.args) await context.send(`Params ${context.args[1]}`);
});

init()

init(): Promise<void>

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

Init bot. Call it manually only if you doesn't use Bot.start

Returns

Promise<void>


inlineQuery()

inlineQuery<Ctx>(trigger, handler, options?): this

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

Register handler to inline_query update

Type Parameters

Type ParameterDefault type
CtxContextType<Bot<Errors, Derives, Macros>, "inline_query">

Parameters

ParameterType
triggerstring | RegExp | (context) => boolean
handler(context) => unknown
options?object & { [K in string | number | symbol]?: WithCtx<MacroOptionType<Macros[K]>, Ctx> } & object

Returns

this

Example

ts
new Bot().inlineQuery(
    /regular expression with (.*)/i,
    async (context) => {
        if (context.args) {
            await context.answer(
                [
                    InlineQueryResult.article(
                        "id-1",
                        context.args[1],
                        InputMessageContent.text("some"),
                        {
                            reply_markup: new InlineKeyboard().text(
                                "some",
                                "callback-data"
                            ),
                        }
                    ),
                ],
                {
                    cache_time: 0,
                }
            );
        }
    },
    {
        onResult: (context) => context.editText("Message edited!"),
    }
);

macro()

Call Signature

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

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

Register a single named macro definition

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

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

Example
ts
import { Bot, type MacroDef } from "gramio";

const onlyAdmin: MacroDef = {
  preHandler: (ctx, next) => {
    if (ctx.from?.id !== ADMIN_ID) return;
    return next();
  },
};

const bot = new Bot(process.env.TOKEN!)
  .macro("onlyAdmin", onlyAdmin)
  .command("ban", handler, { onlyAdmin: true });

Call Signature

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

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

Register multiple macro definitions at once

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

Bot<Errors, Derives, Macros & TDefs>


on()

Call Signature

on<Narrowing>(filter, handler): this

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

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<Bot<Errors, Derives, Macros>>[CompatibleUpdates<Bot<Errors, Derives, Macros>, Narrowing>]> & Derives["global"] & Derives[CompatibleUpdates<Bot<Errors, Derives, Macros>, Narrowing>] & Narrowing>
Returns

this

Call Signature

on(filter, handler): this

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

Register handler with a boolean filter (all updates)

Parameters
ParameterType
filter(ctx) => boolean
handlerHandler<Context<Bot<Errors, Derives, Macros>> & Derives["global"]>
Returns

this

Call Signature

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

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

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<Bot<Errors, Derives, Macros>>[T]> & Derives["global"] & Derives[T] & Narrowing>
Returns

this

Call Signature

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

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

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<ContextType<Bot<Errors, Derives, Macros>, T>>
Returns

this

Call Signature

on<T>(updateName, handler): this

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

Register handler to one or many Updates

Type Parameters
Type Parameter
T extends UpdateName
Parameters
ParameterType
updateNameMaybeArray<T>
handlerHandler<ContextType<Bot<Errors, Derives, Macros>, T>>
Returns

this


onApiCall()

Call Signature

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

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

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
import { Bot } from "gramio";

const bot = new Bot(process.env.TOKEN!).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:1132

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

Parameters
ParameterType
handlerOnApiCall
Returns

this

Example
typescript
import { Bot } from "gramio";

const bot = new Bot(process.env.TOKEN!).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:986

Set error handler.

Type Parameters
Type Parameter
T extends UpdateName
Parameters
ParameterType
updateNameMaybeArray<T>
handlerOnError<Errors, ContextType<Bot<Errors, Derives, Macros>, 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:987

Set error handler.

Parameters
ParameterType
handlerOnError<Errors, Context<Bot<Errors, Derives, Macros>> & 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:1107

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:1108

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:1114

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:1115

This hook called when API return an error

Documentation

Parameters
ParameterType
handlerOnResponseError
Returns

this


onStart()

onStart(handler): this

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

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:1079

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:1100

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:1101

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


reaction()

reaction<TOptions>(trigger, handler, options?): this

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

Register handler to reaction (message_reaction update)

Type Parameters

Type ParameterDefault type
TOptions extends HandlerOptions<ContextType<Bot<Errors, Derives, Macros>, "message_reaction">, Macros>object

Parameters

ParameterType
triggerMaybeArray<TelegramReactionTypeEmojiEmoji>
handler(context) => unknown
options?TOptions

Returns

this

Example

ts
new Bot().reaction("👍", async (context) => {
    await context.reply(`Thank you!`);
});

start()

start(__namedParameters?): Promise<TelegramUser>

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

Start receive updates via long-polling or webhook

Parameters

ParameterType
__namedParameters?BotStartOptions

Returns

Promise<TelegramUser>

Example

ts
import { Bot } from "gramio";

const bot = new Bot("") // put you token here
    .command("start", (context) => context.send("Hi!"))
    .onStart(console.log);

bot.start();

startParameter()

startParameter<TOptions>(parameter, handler, options?): this

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

Register handler to start command when start parameter is matched

Type Parameters

Type ParameterDefault type
TOptions extends HandlerOptions<MessageContext<Bot<Errors, Derives, Macros>> & Require<MessageContext<Bot<Errors, Derives, Macros>>, "from"> & Derives["global"] & Derives["message"] & object, Macros>object

Parameters

ParameterType
parameterRegExp | MaybeArray<string>
handlerHandler<MessageContext<Bot<Errors, Derives, Macros>> & Require<MessageContext<Bot<Errors, Derives, Macros>>, "from"> & Derives["global"] & Derives["message"] & object & UnionToIntersection<{ [K in string | number | symbol]: MacroDeriveType<Macros[K]> }[keyof TOptions & keyof Macros]>>
options?TOptions

Returns

this

Example

ts
new Bot().startParameter(/^ref_(.+)$/, (context) => {
    return context.send(`Reference: ${context.rawStartPayload}`);
});

stop()

stop(timeout?): Promise<void>

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

Stops receiving events via long-polling or webhook

Parameters

ParameterType
timeout?number

Returns

Promise<void>


use()

use(handler): this

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

Register handler to any Updates

Parameters

ParameterType
handlerHandler<Context<Bot<Errors, Derives, Macros>> & Derives["global"]>

Returns

this