The easy way to write Telegram bots in Node.js
The easy way to write Telegram bots.
Library features:
npm install telebotOr using yarn package manager:
yarn add telebotImport telebot module and create a new bot object:
…Or just:
const TeleBot = require('telebot');
const bot = new TeleBot(TELEGRAM_BOT_TOKEN);Don't forget to insert your Telegram Bot API token key.
To start polling updates, use bot.start().
bot.on('text', (msg) => msg.reply.text(msg.text));
bot.start();We just created echo bot!
Send text on /start or /hello command:
bot.on(['/start', '/hello'], (msg) => msg.reply.text('Welcome!'));When sticker received, reply back:
bot.on('sticker', (msg) => {
return msg.reply.sticker('http://i.imgur.com/VRYdhuD.png', { asReply: true });
});Sends photo on "show kitty" or "kitty" text message (using RegExp):
bot.on(/(show\s)?kitty*/, (msg) => {
return msg.reply.photo('http://thecatapi.com/api/images/get');
});Command with arguments /say <your message>:
bot.on(/^\/say (.+)$/, (msg, props) => {
const text = props.match[1];
return bot.sendMessage(msg.from.id, text, { replyToMessage: msg.message_id });
});When message was edited:
bot.on('edit', (msg) => {
return msg.reply.text('I saw it! You edited message!', { asReply: true });
});Note: msg.reply is a bot method shortcut, part of shortReply build-in plugin.
Use bot.on(<event>, <function>) to handle all possible TeleBot events.
For example, to catch a command, just add a slash:
bot.on('/hello', (msg) => {
return bot.sendMessage(msg.from.id, `Hello, ${ msg.from.first_name }!`);
});Also, you can catch multiple events:
bot.on(['/start', 'audio', 'sticker'], msg => {
return bot.sendMessage(msg.from.id, 'Bam!');
});keyboard, button, inlineKeyboard, inlineQueryKeyboard, inlineButton, answerList, getMe, sendMessage, deleteMessage, forwardMessage, sendPhoto, sendAudio, sendDocument, sendSticker, sendVideo, sendVideoNote, sendVoice, sendLocation, sendVenue, sendContact, sendChatAction, getUserProfilePhotos, getFile, kickChatMember, unbanChatMember, answerInlineQuery, answerCallbackQuery, answerShippingQuery, answerPreCheckoutQuery, editMessageText, editMessageMedia, editMessageCaption, editMessageReplyMarkup, setWebhook
Read more about Telegram Bot API response types: https://core.telegram.org/bots/api#available-types
You can add modifier to process data before passing it to event.
bot.mod('text', (data) => {
let msg = data.message;
msg.text = ` ${ msg.text }`;
return data;
});This code adds emoji to every text message.
Use usePlugins config option to load plugins from pluginFolder directory:
const bot = new TeleBot({
token: 'TELEGRAM_BOT_TOKEN',
usePlugins: ['askUser', 'commandButtons'],
pluginFolder: '../plugins/',
pluginConfig: {
// Plugin configs
}
});Or use plug(require(<plugin_path>)) to plug an external plugin.
Check out build-in plugin folder!
module.exports = {
id: 'myPlugin', // Unique plugin name
defaultConfig: {
// Default plugin config
key: 'value'
},
plugin(bot, pluginConfig) {
// Plugin code
}
};on(<events>, <function>)Handles events.
event(<event>, <data>)Invokes the event handlers.
mod(<name>, <fn>)Add data modifier.
modRun(<names>, <data>)Run data modifiers.
plug(<plugin function>)Use plugin function.
keyboard([array of arrays], {resize, once, remove, selective})Creates ReplyKeyboardMarkup keyboard replyMarkup object.
button(<location | contact>, <text>)Creates KeyboardButton button.
inlineButton(<text>, {url | callback | game | inline | inlineCurrent | pay})Creates InlineKeyboardButton button object.
inlineKeyboard([array of arrays])Creates inlineKeyboard object for normal bot messages.
answerList(<inline_query_id>, {nextOffset, cacheTime, personal, pmText, pmParameter})Creates answerInlineQuery answer list object.
inlineQueryKeyboard([array of arrays])Creates inlineKeyboard object for answerList articles.
start()Start polling updates.
stop(<message>)Stop polling updates.
receiveUpdates([<update>])Handle Telegram update
TeleBot use standard Telegram Bot API method names.
getMe()A simple method for testing your bot's auth token.
answerQuery(<answerList>)Use this method to send answerList to an inline query.
getFile(<file_id>)Use this method to get basic info about a file and prepare it for downloading.
sendMessage(<chat_id>, <text>, {parseMode, replyToMessage, replyMarkup, notification, webPreview})Use this method to send text messages.
forwardMessage(<chat_id>, <from_chat_id>, <message_id>, {notification})Use this method to forward messages of any kind.
deleteMessage(<chat_id>, <from_message_id>)Use this method to delete a message. A message can only be deleted if it was sent less than 48 hours ago. Any such sent outgoing message may be deleted. Additionally, if the bot is an administrator in a group chat, it can delete any message. If the bot is an administrator of a supergroup or channel, it can delete ordinary messages from any other user, including service messages about people added or removed from the chat. Returns True on success.
sendPhoto(<chat_id>, <file_id | path | url | buffer | stream>, {caption, fileName, serverDownload, replyToMessage, replyMarkup, notification})Use this method to send photos.
sendAudio(<chat_id>, <file_id | path | url | buffer | stream>, {title, performer, duration, caption, fileName, serverDownload, replyToMessage, replyMarkup, notification})Use this method to send audio files, if you want Telegram clients to display the file as a playable voice message.
sendDocument(<chat_id>, <file_id | path | url | buffer | stream>, {caption, fileName, serverDownload, replyToMessage, replyMarkup, notification})Use this method to send general files.
sendAnimation(<chat_id>, <animation>, {caption, fileName, serverDownload, replyToMessage, replyMarkup, notification})Use this method to send animation files (GIF or H.264/MPEG-4 AVC video without sound).
sendSticker(<chat_id>, <file_id | path | url | buffer | stream>, {fileName, serverDownload, replyToMessage, replyMarkup, notification})Use this method to send .webp stickers.
sendVideo(<chat_id>, <file_id | path | url | buffer | stream>, {duration, width, height, caption, fileName, serverDownload, replyToMessage, replyMarkup, notification, supportsStreaming})Use this method to send video files, Telegram clients support mp4 videos (other formats may be sent as Document).
sendVideoNote(<chat_id>, <file_id | path | url | buffer | stream>, {duration, length, fileName, serverDownload, replyToMessage, replyMarkup, notification})Use this method to send video messages.
sendMediaGroup(<chat_id>, <mediaList: InputMedia[]>)Use this method to send a group of photos or videos as an album. (Min. 2)
sendVoice(<chat_id>, <file_id | path | url | buffer | stream>, {duration, caption, fileName, serverDownload, replyToMessage, replyMarkup, notification})Use this method to send audio files, if you want Telegram clients to display the file as a playable voice message.
sendLocation(<chat_id>, [<latitude>, <longitude>], {replyToMessage, replyMarkup, notification})Use this method to send point on the map.
sendLocation(<chat_id>, [<latitude>, <longitude>], {replyToMessage, replyMarkup, notification})Use this method to send point on the map.
editMessageLiveLocation({chatId + messageId | inlineMessageId, latitude, longitude}, {replyMarkup})Use this method to edit live location messages sent by the bot or via the bot (for inline bots). A location can be edited until its live_period expires or editing is explicitly disabled by a call to stopMessageLiveLocation.
stopMessageLiveLocation({chatId + messageId | inlineMessageId}, {replyMarkup})Use this method to stop updating a live location message sent by the bot or via the bot (for inline bots) before live_period expires.
sendVenue(<chat_id>, [<latitude>, <longitude>], <title>, <address>, {foursquareId, foursquareType, replyToMessage, replyMarkup, notification})Use this method to send information about a venue.
getStickerSet(<name>)Use this method to get a sticker set.
uploadStickerFile(<user_id>, <file_id | path | url | buffer | stream>)Use this method to upload a .png file with a sticker for later use in createNewStickerSet and addStickerToSet methods (can be used multiple times
No open issues yet, or sync has not completed.