Skip to main content
Version: Next

TelegramClient

Usage

Get the TelegramClient instance using the getClient function:

const { getClient } = require('bottender');

const client = getClient('telegram');

// `client` is a `TelegramClient` instance
const webhookInfo = await client.getWebhookInfo();

Or, get the TelegramClient instance from the context:

async function MyAction(context) {
if (context.platform === 'telegram') {
// `context.client` is a `TelegramClient` instance
const webhookInfo = await context.client.getWebhookInfo();
}
}

Error Handling

TelegramClient uses axios as HTTP client. We use axios-error package to wrap API error instances for better formatting error messages. Calling console.log with the error instance returns the formatted message. If you'd like to get the axios request, response, or config, you can still get them via those keys on the error instance.

client.getWebhookInfo().catch((error) => {
console.log(error); // the formatted error message
console.log(error.stack); // stack trace of the error
console.log(error.config); // axios request config
console.log(error.request); // axios HTTP request
console.log(error.response); // axios HTTP response
});

Methods

All methods return a Promise.


Webhook API

getWebhookInfo - Official Docs

Gets current webhook status.

Example:

client.getWebhookInfo().then((info) => {
console.log(info);
// {
// url: 'https://4a16faff.ngrok.io/',
// hasCustomCertificate: false,
// pendingUpdateCount: 0,
// maxConnections: 40,
// }
});

getUpdates - Official Docs

Use this method to receive incoming updates using long polling. An Array of Update objects is returned.

ParamTypeDescription
optionsObjectOptional parameters.

Example:

client
.getUpdates({
limit: 10,
})
.then((updates) => {
console.log(updates);
/*
[
{
updateId: 513400512,
message: {
messageId: 3,
from: {
id: 313534466,
firstName: 'first',
lastName: 'last',
username: 'username',
},
chat: {
id: 313534466,
firstName: 'first',
lastName: 'last',
username: 'username',
type: 'private',
},
date: 1499402829,
text: 'hi',
},
},
...
]
*/
});

setWebhook(url) - Official Docs

Specifies a url and receive incoming updates via an outgoing webhook.

ParamTypeDescription
urlStringHTTPS url to send updates to.

Example:

client.setWebhook('https://4a16faff.ngrok.io/');

deleteWebhook - Official Docs

Removes webhook integration.

Example:

client.deleteWebhook();

Send API - Official Docs

sendMessage(chatId, text [, options]) - Official Docs

Sends text messages.

ParamTypeDescription
chatIdNumber | StringUnique identifier for the target chat or username of the target channel.
textStringText of the message to be sent.
optionsObjectOther optional parameters.

Example:

client.sendMessage(CHAT_ID, 'hi', {
disableWebPagePreview: true,
disableNotification: true,
});

sendPhoto(chatId, photo [, options]) - Official Docs

Sends photos.

ParamTypeDescription
chatIdNumber | StringUnique identifier for the target chat or username of the target channel.
photoStringPass a file id (recommended) or HTTP URL to send photo.
optionsObjectOther optional parameters.

Example:

client.sendPhoto(CHAT_ID, 'https://example.com/image.png', {
caption: 'gooooooodPhoto',
disableNotification: true,
});

sendAudio(chatId, audio [, options]) - Official Docs

Sends audio files.

ParamTypeDescription
chatIdNumber | StringUnique identifier for the target chat or username of the target channel.
audioStringPass a file id (recommended) or HTTP URL to send audio.
optionsObjectOther optional parameters.

Example:

client.sendAudio(CHAT_ID, 'https://example.com/audio.mp3', {
caption: 'gooooooodAudio',
disableNotification: true,
});

sendDocument(chatId, document [, options]) - Official Docs

Sends general files.

ParamTypeDescription
chatIdNumber | StringUnique identifier for the target chat or username of the target channel.
documentStringPass a file id (recommended) or HTTP URL to send document.
optionsObjectOther optional parameters.

Example:

client.sendDocument(CHAT_ID, 'https://example.com/doc.gif', {
caption: 'gooooooodDocument',
disableNotification: true,
});

sendSticker(chatId, sticker [, options]) - Official Docs

Sends .webp stickers.

ParamTypeDescription
chatIdNumber | StringUnique identifier for the target chat or username of the target channel.
stickerStringPass a file id (recommended) or HTTP URL to send sticker.
optionsObjectOther optional parameters.

Example:

client.sendSticker(CHAT_ID, 'CAADAgADQAADyIsGAAE7MpzFPFQX5QI', {
disableNotification: true,
});

sendVideo(chatId, video [, options]) - Official Docs

Sends video files, Telegram clients support mp4 videos (other formats may be sent as Document).

ParamTypeDescription
chatIdNumber | StringUnique identifier for the target chat or username of the target channel.
videoStringPass a file id (recommended) or HTTP URL to send video.
optionsObjectOther optional parameters.

Example:

client.sendVideo(CHAT_ID, 'https://example.com/video.mp4', {
caption: 'gooooooodVideo',
disableNotification: true,
});

sendVoice(chatId, voice [, options]) - Official Docs

Sends audio files.

ParamTypeDescription
chatIdNumber | StringUnique identifier for the target chat or username of the target channel.
voiceStringPass a file id (recommended) or HTTP URL to send voice.
optionsObjectOther optional parameters.

Example:

client.sendVoice(CHAT_ID, 'https://example.com/voice.ogg', {
caption: 'gooooooodVoice',
disableNotification: true,
});

sendVideoNote(chatId, videoNote [, options]) - Official Docs

Sends video messages. As of v.4.0, Telegram clients support rounded square mp4 videos of up to 1 minute long.

ParamTypeDescription
chatIdNumber | StringUnique identifier for the target chat or username of the target channel.
videoNoteStringPass a file id (recommended) or HTTP URL to send video note.
optionsObjectOther optional parameters.

Example:

client.sendVideoNote(CHAT_ID, 'https://example.com/video_note.mp4', {
duration: 40,
disableNotification: true,
});

sendMediaGroup(chatId, media [, options]) - Official Docs

send a group of photos or videos as an album.

ParamTypeDescription
chatIdNumber | StringUnique identifier for the target chat or username of the target channel.
mediaArray<InputMedia>A JSON-serialized array describing photos and videos to be sent, must include 2–10 items
optionsObjectOther optional parameters.

Example:

client.sendMediaGroup(CHAT_ID, [
{ type: 'photo', media: 'BQADBAADApYAAgcZZAfj2-xeidueWwI' },
]);

sendLocation(chatId, location [, options]) - Official Docs

Sends point on the map.

ParamTypeDescription
chatIdNumber | StringUnique identifier for the target chat or username of the target channel.
locationObjectObject contains latitude and longitude.
location.latitudeNumberLatitude of the location.
location.longitudeNumberLongitude of the location.
optionsObjectOther optional parameters.

Example:

client.sendLocation(
CHAT_ID,
{
latitude: 30,
longitude: 45,
},
{
disableNotification: true,
}
);

sendVenue(chatId, venue [, options]) - Official Docs

Sends information about a venue.

ParamTypeDescription
chatIdNumber | StringUnique identifier for the target chat or username of the target channel.
venueObjectObject contains information of the venue.
venue.latitudeNumberLatitude of the venue.
venue.longitudeNumberLongitude of the venue.
venue.titleStringName of the venue.
venue.addressStringAddress of the venue.
optionsObjectOther optional parameters.

Example:

client.sendVenue(
CHAT_ID,
{
latitude: 30,
longitude: 45,
title: 'a_title',
address: 'an_address',
},
{
disableNotification: true,
}
);

sendContact(chatId, contact [, options]) - Official Docs

Sends phone contacts.

ParamTypeDescription
chatIdNumber | StringUnique identifier for the target chat or username of the target channel.
contactObjectObject contains information of the contact.
contact.phoneNumberStringPhone number of the contact.
contact.firstNameStringFirst name of the contact.
optionsObjectOther optional parameters.

Example:

client.sendContact(
CHAT_ID,
{
phoneNumber: '886123456789',
firstName: 'first',
},
{ lastName: 'last' }
);

sendChatAction(chatId, action) - Official Docs

Tells the user that something is happening on the bot's side.

ParamTypeDescription
chatIdNumber | StringUnique identifier for the target chat or username of the target channel.
actionStringType of action to broadcast.

Example:

client.sendChatAction(CHAT_ID, 'typing');

Get API

getMe - Official Docs

Gets bot's information.

Example:

client.getMe().then((result) => {
console.log(result);
// {
// id: 313534466,
// firstName: 'first',
// username: 'a_bot'
// }
});

getUserProfilePhotos(userId [, options]) - Official Docs

Gets a list of profile pictures for a user.

ParamTypeDescription
userIdStringUnique identifier of the target user.
optionsObjectOther optional parameters

Example:

client.getUserProfilePhotos(USER_ID, { limit: 1 }).then((result) => {
console.log(result);
// {
// totalCount: 3,
// photos: [
// [
// {
// fileId:
// 'AgADBAADGTo4Gz8cZAeR-ouu4XBx78EeqRkABHahi76pN-aO0UoDA050',
// fileSize: 14650,
// width: 160,
// height: 160,
// },
// {
// fileId:
// 'AgADBAADGTo4Gz8cZAeR-ouu4XBx78EeqRkABKCfooqTgFUX0EoD5B1C',
// fileSize: 39019,
// width: 320,
// height: 320,
// },
// {
// fileId:
// 'AgADBAADGTo4Gz8cZAeR-ouu4XBx78EeqRkABPL_pC9K3UpI0koD1B1C',
// fileSize: 132470,
// width: 640,
// height: 640,
// },
// ],
// ],
// }
});

getFile(fileId) - Official Docs

Gets basic info about a file and prepare it for downloading.

ParamTypeDescription
fileIdStringFile identifier to get info about.

Example:

client
.getFile('UtAqweADGTo4Gz8cZAeR-ouu4XBx78EeqRkABPL_pM4A1UpI0koD65K2')
.then((file) => {
console.log(file);
// {
// fileId: 'UtAqweADGTo4Gz8cZAeR-ouu4XBx78EeqRkABPL_pM4A1UpI0koD65K2',
// fileSize: 106356,
// filePath: 'photos/1068230105874016297.jpg',
// }
});

getFileLink(fileId)

Gets link of the file.

ParamTypeDescription
fileIdStringFile identifier to get info about.

Example:

client
.getFileLink('UtAqweADGTo4Gz8cZAeR-ouu4XBx78EeqRkABPL_pM4A1UpI0koD65K2')
.then((link) => {
console.log(link);
// 'https://api.telegram.org/file/bot<ACCESS_TOKEN>/photos/1068230105874016297.jpg'
});

getChat(chatId) - Official Docs

Gets up to date information about the chat (current name of the user for one-on-one conversations, current username of a user, group or channel, etc.)

ParamTypeDescription
chatIdNumber | StringUnique identifier for the target chat or username of the target channel.

Example:

client.getChat(CHAT_ID).then((chat) => {
console.log(chat);
// {
// id: 313534466,
// firstName: 'first',
// lastName: 'last',
// username: 'username',
// type: 'private',
// }
});

getChatAdministrators(chatId) - Official Docs

Gets a list of administrators in a chat.

ParamTypeDescription
chatIdNumber | StringUnique identifier for the target chat or username of the target channel.

Example:

client.getChatAdministrators(CHAT_ID).then((admins) => {
console.log(admins);
// [
// {
// user: {
// id: 313534466,
// firstName: 'first',
// lastName: 'last',
// username: 'username',
// languangeCode: 'zh-TW',
// },
// status: 'creator',
// },
// ]
});

getChatMembersCount(chatId) - Official Docs

Gets the number of members in a chat.

ParamTypeDescription
chatIdNumber | StringUnique identifier for the target chat or username of the target channel.

Example:

client.getChatMembersCount(CHAT_ID).then((count) => {
console.log(count); // '6'
});

getChatMember(chatId, userId) - Official Docs

Gets information about a member of a chat.

ParamTypeDescription
chatIdNumber | StringUnique identifier for the target chat or username of the target channel.
userIdNumberUnique identifier of the target user.

Example:

client.getChatMember(CHAT_ID, USER_ID).then((member) => {
console.log(member);
// {
// user: {
// id: 313534466,
// firstName: 'first',
// lastName: 'last',
// username: 'username',
// languangeCode: 'zh-TW',
// },
// status: 'creator',
// }
});

Updating API

editMessageText(text [, options]) - Official Docs

Edits text and game messages sent by the bot or via the bot (for inline bots).

ParamTypeDescription
textStringNew text of the message.
optionsObjectOne of chatId, messageId or inlineMessageId is required.
options.chatIdNumber | StringUnique identifier for the target chat or username of the target channel.
options.messageIdNumberIdentifier of the sent message.
options.inlineMessageIdStringIdentifier of the inline message.

Example:

client.editMessageText('new_text', { messageId: MESSAGE_ID });

editMessageCaption(caption [, options]) - Official Docs

Edits captions of messages sent by the bot or via the bot (for inline bots).

ParamTypeDescription
captionStringNew caption of the message.
optionsObjectOne of chatId, messageId or inlineMessageId is required.
options.chatIdNumber | StringUnique identifier for the target chat or username of the target channel.
options.messageIdNumberIdentifier of the sent message.
options.inlineMessageIdStringIdentifier of the inline message.

Example:

client.editMessageCaption('new_caption', { messageId: MESSAGE_ID });

editMessageReplyMarkup(replyMarkup [, options]) - Official Docs

Edits only the reply markup of messages sent by the bot or via the bot (for inline bots).

ParamTypeDescription
replyMarkupObjectNew replyMarkup of the message.
optionsObjectOne of chatId, messageId or inlineMessageId is required.
options.chatIdNumber | StringUnique identifier for the target chat or username of the target channel.
options.messageIdNumberIdentifier of the sent message.
options.inlineMessageIdStringIdentifier of the inline message.

Example:

client.editMessageReplyMarkup(
{
keyboard: [[{ text: 'new_button_1' }, { text: 'new_button_2' }]],
resizeKeyboard: true,
oneTimeKeyboard: true,
},
{ messageId: MESSAGE_ID }
);

deleteMessage(chatId, messageId) - Official Docs

Deletes a message, including service messages.

ParamTypeDescription
chatIdNumber | StringUnique identifier for the target chat or username of the target channel.
messageIdNumberIdentifier of the message to delete.

Example:

client.deleteMessage(CHAT_ID, MESSAGE_ID);

editMessageLiveLocation(location [, options]) - Official Docs

Edit live location messages sent by the bot or via the bot (for inline bots).

ParamTypeDescription
locationObjectObject contains new latitude and longitude.
location.latitudeNumberLatitude of new location.
location.longitudeNumberLongitude of new location.
optionsObjectOne of chatId, messageId or inlineMessageId is required.
options.chatIdNumber | StringUnique identifier for the target chat or username of the target channel.
options.messageIdNumberIdentifier of the sent message.
options.inlineMessageIdStringIdentifier of the inline message.

Example:

client.editMessageLiveLocation(
{
latitude: 30,
longitude: 45,
},
{
messageId: MESSAGE_ID,
}
);

stopMessageLiveLocation(options) - Official Docs

Stop updating a live location message sent by the bot or via the bot (for inline bots) before live_period expires.

ParamTypeDescription
identifierObjectOne of chatId, messageId or inlineMessageId is required.
identifier.chatIdNumber | StringUnique identifier for the target chat or username of the target channel.
identifier.messageIdNumberIdentifier of the sent message.
identifier.inlineMessageIdStringIdentifier of the inline message.

Example:

client.stopMessageLiveLocation({ messageId: MESSAGE_ID });

Group API

kickChatMember(chatId, userId [, options]) - Official Docs

Kicks a user from a group, a supergroup or a channel.

ParamTypeDescription
chatIdNumber | StringUnique identifier for the target chat or username of the target channel.
userIdNumberUnique identifier of the target user.
optionsObjectOther optional parameters.

Example:

client.kickChatMember(CHAT_ID, USER_ID, { untilDate: UNIX_TIME });

unbanChatMember(chatId, userId) - Official Docs

Unbans a previously kicked user in a supergroup or channel.

ParamTypeDescription
chatIdNumber | StringUnique identifier for the target chat or username of the target channel.
userIdNumberUnique identifier of the target user.

Example:

client.unbanChatMember(CHAT_ID, USER_ID);

restrictChatMember(chatId, userId [, options]) - Official Docs

Restricts a user in a supergroup

ParamTypeDescription
chatIdNumber | StringUnique identifier for the target chat or username of the target channel.
userIdNumberUnique identifier of the target user.
optionsObjectOther optional parameters.

Example:

client.restrictChatMember(CHAT_ID, USER_ID, { canSendMessages: true });

promoteChatMember(chatId, userId [, options]) - Official Docs

Promotes or demotes a user in a supergroup or a channel.

ParamTypeDescription
chatIdNumber | StringUnique identifier for the target chat or username of the target channel.
userIdNumberUnique identifier of the target user.
optionsObjectOther optional parameters.

Example:

client.promoteChatMember(CHAT_ID, USER_ID, {
canChangeInfo: true,
canInviteUsers: true,
});

exportChatInviteLink(chatId) - Official Docs

Exports an invite link to a supergroup or a channel.

ParamTypeDescription
chatIdNumber | StringUnique identifier for the target chat or username of the target channel.

Example:

client.exportChatInviteLink(CHAT_ID);

setChatPhoto(chatId, photo) - Official Docs

Sets a new profile photo for the chat.

ParamTypeDescription
chatIdNumber | StringUnique identifier for the target chat or username of the target channel.
photoStringPass a file id (recommended) or HTTP URL to send photo.

Example:

client.setChatPhoto(CHAT_ID, 'https://example.com/image.png');

deleteChatPhoto(chatId) - Official Docs

Deletes a chat photo.

ParamTypeDescription
chatIdNumber | StringUnique identifier for the target chat or username of the target channel.

Example:

client.deleteChatPhoto(CHAT_ID);

setChatTitle(chatId, title) - Official Docs

Changes the title of a chat.

ParamTypeDescription
chatIdNumber | StringUnique identifier for the target chat or username of the target channel.
titleStringNew chat title, 1-255 characters.

Example:

client.setChatTitle(CHAT_ID, 'New Title');

setChatDescription(chatId, description) - Official Docs

Changes the description of a supergroup or a channel.

ParamTypeDescription
chatIdNumber | StringUnique identifier for the target chat or username of the target channel.
descriptionStringNew chat description, 0-255 characters.

Example:

client.setChatDescription(CHAT_ID, 'New Description');

setChatStickerSet(chatId, stickerSetName) - Official Docs

Set a new group sticker set for a supergroup.

ParamTypeDescription
chatIdNumber | StringUnique identifier for the target chat or username of the target channel.
stickerSetNameStringName of the sticker set to be set as the group sticker set.

Example:

client.setChatStickerSet(CHAT_ID, 'Sticker Set Name');

deleteChatStickerSet(chatId) - Official Docs

Delete a group sticker set from a supergroup.

ParamTypeDescription
chatIdNumber | StringUnique identifier for the target chat or username of the target channel.

Example:

client.deleteChatStickerSet(CHAT_ID);

pinChatMessage(chatId, messageId [, options]) - Official Docs

Pins a message in a supergroup.

ParamTypeDescription
chatIdNumber | StringUnique identifier for the target chat or username of the target channel.
messageIdNumberIdentifier of a message to pin.
optionsObjectOther optional parameters.

Example:

client.pinChatMessage(CHAT_ID, MESSAGE_ID, { disableNotification: true });

unpinChatMessage(chatId) - Official Docs

Unpins a message in a supergroup chat.

ParamTypeDescription
chatIdNumber | StringUnique identifier for the target chat or username of the target channel.

Example:

client.unpinChatMessage(CHAT_ID);

leaveChat(chatId) - Official Docs

Leaves a group, supergroup or channel.

ParamTypeDescription
chatIdNumber | StringUnique identifier for the target chat or username of the target channel.

Example:

client.leaveChat(CHAT_ID);

Payments API

sendInvoice(chatId, product [, options]) - Official Docs

Sends invoice.

ParamTypeDescription
chatIdNumber | StringUnique identifier for the target chat or username of the target channel.
productObjectObject of the product.
product.titleStringProduct name.
product.descriptionStringProduct description.
product.payloadStringBot defined invoice payload.
product.providerTokenStringPayments provider token.
product.startParameterStringDeep-linking parameter.
product.currencyStringThree-letter ISO 4217 currency code.
product.pricesArray<Object>Breakdown of prices.
optionsObjectAdditional Telegram query options.

Example:

client.sendInvoice(CHAT_ID, {
title: 'product name',
description: 'product description',
payload: 'bot-defined invoice payload',
providerToken: 'PROVIDER_TOKEN',
startParameter: 'pay',
currency: 'USD',
prices: [
{ label: 'product', amount: 11000 },
{ label: 'tax', amount: 11000 },
],
});

answerShippingQuery(shippingQueryId, ok [, options]) - Official Docs

Reply to shipping queries.

ParamTypeDescription
shippingQueryIdStringUnique identifier for the query to be answered.
okBooleanSpecify if delivery of the product is possible.
optionsObjectAdditional Telegram query options.

Example:

client.answerShippingQuery('UNIQUE_ID', true);

answerPreCheckoutQuery(preCheckoutQueryId, ok [, options]) - Official Docs

Respond to such pre-checkout queries.

ParamTypeDescription
preCheckoutQueryIdStringUnique identifier for the query to be answered.
okBooleanSpecify if delivery of the product is possible.
optionsObjectAdditional Telegram query options.

Example:

client.answerPreCheckoutQuery('UNIQUE_ID', true);

Inline mode API

answerInlineQuery(inlineQueryId, results [, options]) - Official Docs

Send answers to an inline query.

ParamTypeDescription
inlineQueryIdStringUnique identifier of the query.
resultsArray<InlineQueryResult>Array of object represents one result of an inline query.
optionsObjectAdditional Telegram query options.

Example:

client.answerInlineQuery(
'INLINE_QUERY_ID',
[
{
type: 'photo',
id: 'UNIQUE_ID',
photoFileId: 'FILE_ID',
title: 'PHOTO_TITLE',
},
{
type: 'audio',
id: 'UNIQUE_ID',
audioFileId: 'FILE_ID',
caption: 'AUDIO_TITLE',
},
],
{
cacheTime: 1000,
}
);

Game API

sendGame(chatId, gameShortName [, options]) - Official Docs

Sends a game.

ParamTypeDescription
chatIdNumber | StringUnique identifier for the target chat or username of the target channel.
gameShortNameStringShort name of the game.
optionsObjectAdditional Telegram query options.

Example:

client.sendGame(CHAT_ID, 'Mario Bros.', {
disableNotification: true,
});

setGameScore(userId, score [, options]) - Official Docs

Sets the score of the specified user in a game.

ParamTypeDescription
userIdNumber | StringUser identifier.
scoreNumberNew score, must be non-negative.
optionsObjectAdditional Telegram query options.

Example:

client.setGameScore(USER_ID, 999);

getGameHighScores(userId [, options]) - Official Docs

Gets data for high score tables.

ParamTypeDescription
userIdNumber | StringUser identifier.
optionsObjectAdditional Telegram query options.

Example:

client.getGameHighScores(USER_ID).then((scores) => {
console.log(scores);
// [
// {
// position: 1,
// user: {
// id: 427770117,
// isBot: false,
// firstName: 'first',
// },
// score: 999,
// },
// ]
});

Others

forwardMessage(chatId, fromChatId, messageId [, options]) - Official Docs

Forwards messages of any kind.

ParamTypeDescription
chatIdNumber | StringUnique identifier for the target chat or username of the target supergroup or channel.
fromChatIdNumber | StringUnique identifier for the chat where the original message was sent.
messageIdNumberMessage identifier in the chat specified in fromChatId.
optionsObjectOther optional parameters.

Example:

client.forwardMessage(CHAT_ID, USER_ID, MESSAGE_ID, {
disableNotification: true,
});

Debug Tips

Log Requests Details

To enable default request debugger, use following DEBUG env variable:

DEBUG=messaging-api-telegram

Test

Send Requests to Your Dummy Server

To avoid sending requests to the real Telegram server, provide the origin option in your bottender.js.config file:

module.exports = {
channels: {
telegram: {
enabled: true,
path: '/webhooks/telegram',
accessToken: process.env.TELEGRAM_ACCESS_TOKEN,
origin:
process.env.NODE_ENV === 'test'
? 'https://mydummytestserver.com'
: undefined,
},
},
};

Warning: Don't do this on the production server.