GramIO API Reference / gramio/dist / Bot
Class: Bot<Errors, Derives, Macros>
Defined in: gramio/index.d.ts:874
Bot instance
Example
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 Parameter | Default type |
|---|---|
Errors extends ErrorDefinitions | object |
Derives extends DeriveDefinitions | DeriveDefinitions |
Macros extends MacroDefinitions | object |
Constructors
Constructor
new Bot<
Errors,Derives,Macros>(token,options?):Bot<Errors,Derives,Macros>
Defined in: gramio/index.d.ts:911
Parameters
| Parameter | Type |
|---|---|
token | string |
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
| Parameter | Type |
|---|---|
options | Omit<BotOptions, "api"> & object |
Returns
Bot<Errors, Derives, Macros>
Properties
| Property | Modifier | Type | Description | Defined in |
|---|---|---|---|---|
_ | public | object | Deprecated use ~ instead | gramio/index.d.ts:876 |
_.derives | public | Derives | Deprecated @internal. Remap generic | gramio/index.d.ts:878 |
__Derives | public | Derives | Deprecated use ~.derives instead @internal. Remap generic | gramio/index.d.ts:881 |
~ | public | object | - | gramio/index.d.ts:882 |
~.derives | public | Derives | Deprecated @internal. Remap generic | gramio/index.d.ts:884 |
api | readonly | SuppressedAPIMethods | Send API Request to Telegram Bot API Example const response = await bot.api.sendMessage({ chat_id: "@gramio_forum", text: "some text", }); Documentation | gramio/index.d.ts:903 |
info | public | TelegramUser | Bot data (filled in when calling bot.init/bot.start) | gramio/index.d.ts:889 |
options | readonly | BotOptions | Options provided to instance | gramio/index.d.ts:887 |
updates | public | Updates | This instance handle updates | gramio/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 Parameter | Default type |
|---|---|
Trigger extends string | RegExp | CallbackData<Record<never, never>, Record<never, never>> | - |
TOptions extends HandlerOptions<CallbackQueryShorthandContext<Bot<Errors, Derives, Macros>, Trigger>, Macros> | object |
Parameters
| Parameter | Type |
|---|---|
trigger | Trigger |
handler | (context) => unknown |
options? | TOptions |
Returns
this
Example
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 Parameter | Default type |
|---|---|
Ctx | ContextType<Bot<Errors, Derives, Macros>, "chosen_inline_result"> |
TOptions extends HandlerOptions<Ctx, Macros> | object |
Parameters
| Parameter | Type |
|---|---|
trigger | string | 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 Parameter | Default type |
|---|---|
TOptions extends HandlerOptions<ContextType<Bot<Errors, Derives, Macros>, "message">, Macros> | object |
Parameters
| Parameter | Type |
|---|---|
command | MaybeArray<string> |
handler | (context) => unknown |
options? | TOptions |
Returns
this
Example
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
| Parameter | Type |
|---|---|
value | Value |
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
| Parameter | Type |
|---|---|
name | Name |
value | Value |
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
| Parameter | Type |
|---|---|
handler | Handler |
Returns
Bot<Errors, Derives & object, Macros>
Example
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
| Parameter | Type |
|---|---|
updateName | MaybeArray<Update> |
handler | Handler |
Returns
Bot<Errors, Derives & { [K in UpdateName]: Awaited<ReturnType<Handler>> }, Macros>
Example
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
| Parameter | Type |
|---|---|
attachment | string | Attachment | { file_id: string; } |
Returns
Promise<ArrayBuffer>
Example
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!");
});Call Signature
downloadFile(
attachment,path):Promise<string>
Defined in: gramio/index.d.ts:940
Download file
Parameters
| Parameter | Type |
|---|---|
attachment | string | Attachment | { file_id: string; } |
path | string |
Returns
Promise<string>
Example
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!");
});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
| Parameter | Type |
|---|---|
kind | Name |
error | NewError |
Returns
Bot<Errors & { [name in string]: InstanceType<NewError> }, Derives, Macros>
Example
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
| Parameter | Type |
|---|---|
composer | EventComposer<any, any, any, any, UExposed, UDerives, any, any> |
Returns
Bot<Errors, Derives & object & UDerives, Macros>
Example
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
| Parameter | Type |
|---|---|
plugin | MaybePromise<NewPlugin> |
Returns
Bot<Errors & NewPlugin["_"]["Errors"], Derives & NewPlugin["_"]["Derives"], Macros & NewPlugin["_"]["Macros"]>
Example
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
| Parameter | Type |
|---|---|
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 Parameter | Default type |
|---|---|
Ctx | ContextType<Bot<Errors, Derives, Macros>, "message"> |
Trigger extends RegExp | MaybeArray<string> | (context) => boolean | RegExp | MaybeArray<string> | (context) => boolean |
TOptions extends HandlerOptions<Ctx, Macros> | object |
Parameters
| Parameter | Type |
|---|---|
trigger | Trigger |
handler | (context) => unknown |
options? | TOptions |
Returns
this
Example
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 Parameter | Default type |
|---|---|
Ctx | ContextType<Bot<Errors, Derives, Macros>, "inline_query"> |
Parameters
| Parameter | Type |
|---|---|
trigger | string | RegExp | (context) => boolean |
handler | (context) => unknown |
options? | object & { [K in string | number | symbol]?: WithCtx<MacroOptionType<Macros[K]>, Ctx> } & object |
Returns
this
Example
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
| Parameter | Type |
|---|---|
name | Name |
definition | TDef |
Returns
Bot<Errors, Derives, Macros & Record<Name, TDef>>
Example
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
| Parameter | Type |
|---|---|
definitions | TDefs |
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
| Parameter | Type |
|---|---|
filter | (ctx) => ctx is Narrowing |
handler | Handler<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
| Parameter | Type |
|---|---|
filter | (ctx) => boolean |
handler | Handler<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
| Parameter | Type |
|---|---|
updateName | MaybeArray<T> |
filter | (ctx) => ctx is Narrowing |
handler | Handler<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
| Parameter | Type |
|---|---|
updateName | MaybeArray<T> |
filter | (ctx) => boolean |
handler | Handler<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
| Parameter | Type |
|---|---|
updateName | MaybeArray<T> |
handler | Handler<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
| Parameter | Type |
|---|---|
methods | MaybeArray<Methods> |
handler | Handler |
Returns
this
Example
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
| Parameter | Type |
|---|---|
handler | OnApiCall |
Returns
this
Example
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
| Parameter | Type |
|---|---|
updateName | MaybeArray<T> |
handler | OnError<Errors, ContextType<Bot<Errors, Derives, Macros>, T>> |
Returns
this
Example
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
| Parameter | Type |
|---|---|
handler | OnError<Errors, Context<Bot<Errors, Derives, Macros>> & Derives["global"]> |
Returns
this
Example
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
Type Parameters
| Type Parameter |
|---|
Methods extends keyof APIMethods |
Handler extends OnResponse<Methods> |
Parameters
| Parameter | Type |
|---|---|
methods | MaybeArray<Methods> |
handler | Handler |
Returns
this
Call Signature
onResponse(
handler):this
Defined in: gramio/index.d.ts:1108
This hook called when API return successful response
Parameters
| Parameter | Type |
|---|---|
handler | OnResponse |
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
Type Parameters
| Type Parameter |
|---|
Methods extends keyof APIMethods |
Handler extends OnResponseError<Methods> |
Parameters
| Parameter | Type |
|---|---|
methods | MaybeArray<Methods> |
handler | Handler |
Returns
this
Call Signature
onResponseError(
handler):this
Defined in: gramio/index.d.ts:1115
This hook called when API return an error
Parameters
| Parameter | Type |
|---|---|
handler | OnResponseError |
Returns
this
onStart()
onStart(
handler):this
Defined in: gramio/index.d.ts:1058
This hook called when the bot is started.
Parameters
| Parameter | Type |
|---|---|
handler | OnStart |
Returns
this
Example
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();onStop()
onStop(
handler):this
Defined in: gramio/index.d.ts:1079
This hook called when the bot stops.
Parameters
| Parameter | Type |
|---|---|
handler | OnStop |
Returns
this
Example
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();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
| Parameter | Type |
|---|---|
methods | MaybeArray<Methods> |
handler | Handler |
Returns
this
Example
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();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
| Parameter | Type |
|---|---|
handler | PreRequest |
Returns
this
Example
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();reaction()
reaction<
TOptions>(trigger,handler,options?):this
Defined in: gramio/index.d.ts:1190
Register handler to reaction (message_reaction update)
Type Parameters
| Type Parameter | Default type |
|---|---|
TOptions extends HandlerOptions<ContextType<Bot<Errors, Derives, Macros>, "message_reaction">, Macros> | object |
Parameters
| Parameter | Type |
|---|---|
trigger | MaybeArray<TelegramReactionTypeEmojiEmoji> |
handler | (context) => unknown |
options? | TOptions |
Returns
this
Example
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
| Parameter | Type |
|---|---|
__namedParameters? | BotStartOptions |
Returns
Promise<TelegramUser>
Example
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 Parameter | Default type |
|---|---|
TOptions extends HandlerOptions<MessageContext<Bot<Errors, Derives, Macros>> & Require<MessageContext<Bot<Errors, Derives, Macros>>, "from"> & Derives["global"] & Derives["message"] & object, Macros> | object |
Parameters
| Parameter | Type |
|---|---|
parameter | RegExp | MaybeArray<string> |
handler | Handler<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
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
| Parameter | Type |
|---|---|
timeout? | number |
Returns
Promise<void>
use()
use(
handler):this
Defined in: gramio/index.d.ts:1144
Register handler to any Updates
Parameters
| Parameter | Type |
|---|---|
handler | Handler<Context<Bot<Errors, Derives, Macros>> & Derives["global"]> |
Returns
this