Skip to content

Bot API

Telegram Bot API documentation

Bot API is a high-level HTTP interface to the Telegram API that makes it easy to develop bots. Under the hood, Bot API uses TDLib (which in turn uses MTProto API).

While the Bot API can only be used to work with bot accounts, the MTProto API can be used to work with both bot and user accounts. If you need to work with MTProto, we recommend you the MtCute Logomtcute library.

Calling the Bot API

You can call Telegram Bot API methods via bot.api or via the shorthand methods of contexts (for example, context.send is sendMessage shorthand)

ts
const 
response
= await
bot
.
api
.
sendMessage
({
// //
chat_id
: "@gramio_forum",
text
: "some text",
});
ts
bot
.
on
("message", (
context
) =>
context
.
send
("This message will be sent to the current chat")
);

Suppressing errors

It can be convenient to handle an error on the spot without using try/catch blocks. That's why the suppress argument was created, which you can use in any API method.

ts
const 
response
= await
bot
.
api
.
sendMessage
({
// //
suppress
: true,
chat_id
: "@not_found",
text
: "Suppressed method",
}); if (
response
instanceof
TelegramError
)
console
.
error
("sendMessage returns an error...");
else
console
.
log
("Message has been sent successfully");

Types

GramIO re-exports @gramio/types (Code-generated and Auto-published Telegram Bot API types).

Read more

ts
import type { 
APIMethodParams
,
APIMethodReturn
} from "gramio";
type
SendMessageParams
=
APIMethodParams
<"sendMessage">;
// type
GetMeReturn
=
APIMethodReturn
<"getMe">;
//

For example you can use it in your custom function.

ts
function 
myCustomSend
(
params
:
APIMethodParams
<"sendMessage">) {
params
;
}

Types for suppressed method

ts
import type {
    
SuppressedAPIMethodParams
,
SuppressedAPIMethodReturn
,
} from "gramio"; type
SendMessageParams
=
SuppressedAPIMethodParams
<"sendMessage">;
// type
GetMeReturn
=
SuppressedAPIMethodReturn
<"getMe">;
//

Debugging

In order to debug which requests GramIO sends, you can set the environment variable to DEBUG=gramio:api:*

bash
npx cross-env DEBUG=gramio:api:* node index.js

And you will see something like in the console:

bash
gramio:api:getUpdates options: {"method":"POST","headers":{"Content-Type":"application/json"},"body":"{\"offset\":0,\"suppress\":true}"} +0ms
gramio:api:getUpdates response: {"ok":true,"result":[]} +49ms