Node.js wrapper for the official Telegram Bot API with polling and webhook support, comprehensive message handling, media operations, and bot management features.
—
Pending
Does it follow best practices?
Impact
Pending
No eval scenarios have been run
Pending
The risk profile of this skill
Event-driven message processing with support for text pattern matching, reply handling, and custom event listeners for different message types.
Methods for handling different types of Telegram updates through the EventEmitter interface.
/**
* Add event listener for specified event type
* @param {string} event - Event name (message, callback_query, etc.)
* @param {function} listener - Event handler function
*/
on(event, listener): void;
/**
* Add one-time event listener
* @param {string} event - Event name
* @param {function} listener - Event handler function
*/
once(event, listener): void;
/**
* Remove event listener
* @param {string} event - Event name
* @param {function} listener - Event handler function to remove
*/
removeListener(event, listener): void;Usage Example:
// Listen for all messages
bot.on('message', (msg) => {
console.log('Received message:', msg.text);
console.log('From user:', msg.from.first_name);
console.log('Chat ID:', msg.chat.id);
});
// Listen for specific message types
bot.on('photo', (msg) => {
console.log('Received photo:', msg.photo);
});
bot.on('document', (msg) => {
console.log('Received document:', msg.document.file_name);
});
// Listen for callback queries from inline keyboards
bot.on('callback_query', (callbackQuery) => {
const message = callbackQuery.message;
const data = callbackQuery.data;
console.log('Callback data:', data);
bot.answerCallbackQuery(callbackQuery.id);
});
// Listen for inline queries
bot.on('inline_query', (inlineQuery) => {
console.log('Inline query:', inlineQuery.query);
});Methods for matching text messages against regular expressions and handling command-like interactions.
/**
* Register RegExp to test against incoming text messages
* @param {RegExp} regexp - Regular expression to match
* @param {function} callback - Callback function (msg, match)
*/
onText(regexp, callback): void;
/**
* Remove text listener registered with onText()
* @param {RegExp} regexp - Regular expression to remove
* @returns {object|null} Removed listener object or null
*/
removeTextListener(regexp): object|null;
/**
* Remove all text listeners
*/
clearTextListeners(): void;Usage Example:
// Match commands with parameters
bot.onText(/\/start (.+)/, (msg, match) => {
const chatId = msg.chat.id;
const parameter = match[1];
bot.sendMessage(chatId, `Welcome! Parameter: ${parameter}`);
});
// Match echo command
bot.onText(/\/echo (.+)/, (msg, match) => {
const chatId = msg.chat.id;
const resp = match[1];
bot.sendMessage(chatId, resp);
});
// Match help command
const helpRegex = /\/help/;
bot.onText(helpRegex, (msg) => {
const chatId = msg.chat.id;
bot.sendMessage(chatId, 'Available commands: /start, /echo, /help');
});
// Remove specific text listener
bot.removeTextListener(helpRegex);
// Clear all text listeners
bot.clearTextListeners();Methods for handling replies to specific messages with callback registration and management.
/**
* Register callback for replies to specific message
* @param {number|string} chatId - Chat identifier
* @param {number} messageId - Message identifier
* @param {function} callback - Callback function for replies
* @returns {number} Listener ID for removal
*/
onReplyToMessage(chatId, messageId, callback): number;
/**
* Remove reply listener by ID
* @param {number} replyListenerId - Listener ID returned by onReplyToMessage
* @returns {object|null} Removed listener object or null
*/
removeReplyListener(replyListenerId): object|null;
/**
* Remove all reply listeners
* @returns {array} Array of removed listeners
*/
clearReplyListeners(): array;Usage Example:
// Ask for user input and handle reply
bot.sendMessage(chatId, 'What is your name?')
.then((sentMessage) => {
// Wait for reply to this specific message
const listenerId = bot.onReplyToMessage(chatId, sentMessage.message_id, (replyMsg) => {
const userName = replyMsg.text;
bot.sendMessage(chatId, `Nice to meet you, ${userName}!`);
// Remove the listener after use
bot.removeReplyListener(listenerId);
});
});
// Multiple step conversation
let step = 0;
const conversationSteps = ['name', 'age', 'city'];
bot.sendMessage(chatId, 'What is your name?')
.then((sentMessage) => {
const userData = {};
const listenerId = bot.onReplyToMessage(chatId, sentMessage.message_id, function handleStep(replyMsg) {
const currentStep = conversationSteps[step];
userData[currentStep] = replyMsg.text;
step++;
if (step < conversationSteps.length) {
const nextStep = conversationSteps[step];
bot.sendMessage(chatId, `What is your ${nextStep}?`)
.then((nextMessage) => {
bot.removeReplyListener(listenerId);
bot.onReplyToMessage(chatId, nextMessage.message_id, handleStep);
});
} else {
bot.sendMessage(chatId, `Summary: ${JSON.stringify(userData, null, 2)}`);
bot.removeReplyListener(listenerId);
}
});
});Methods for handling raw updates and retrieving updates manually.
/**
* Process incoming update and emit appropriate events
* @param {object} update - Telegram update object
*/
processUpdate(update): void;
/**
* Get updates using long polling
* @param {object} [options] - Options for getUpdates
* @param {number} [options.offset] - Identifier of first update to return
* @param {number} [options.limit] - Max number of updates (1-100)
* @param {number} [options.timeout] - Timeout for long polling
* @param {string[]} [options.allowed_updates] - Update types to receive
* @returns {Promise<Update[]>}
*/
getUpdates(options): Promise<Update[]>;Usage Example:
// Manually process updates (advanced usage)
const updates = await bot.getUpdates({
offset: lastUpdateId + 1,
limit: 100,
timeout: 30,
allowed_updates: ['message', 'callback_query']
});
updates.forEach(update => {
bot.processUpdate(update);
lastUpdateId = update.update_id;
});
// Custom update processing
bot.processUpdate({
update_id: 12345,
message: {
message_id: 1,
date: Math.floor(Date.now() / 1000),
chat: { id: chatId, type: 'private' },
from: { id: userId, first_name: 'Test' },
text: 'Hello, Bot!'
}
});The bot emits the following events based on Telegram update types:
message - Any messagetext - Text messagephoto - Photo messagevideo - Video messageaudio - Audio messagedocument - Document messagesticker - Sticker messagevoice - Voice messagevideo_note - Video note messageanimation - Animation/GIF messagecontact - Contact messagelocation - Location messagevenue - Venue messagepoll - Poll messagedice - Dice messagegame - Game messageinvoice - Invoice messagenew_chat_members - New members joinedleft_chat_member - Member leftnew_chat_title - Chat title changednew_chat_photo - Chat photo changeddelete_chat_photo - Chat photo deletedgroup_chat_created - Group chat createdsupergroup_chat_created - Supergroup createdchannel_chat_created - Channel createdmessage_auto_delete_timer_changed - Auto-delete timer changedmigrate_to_chat_id - Group migrated to supergroupmigrate_from_chat_id - Supergroup migrated from grouppinned_message - Message pinnedcallback_query - Inline keyboard button pressedinline_query - Inline query receivedchosen_inline_result - Inline result chosenshipping_query - Shipping query for paymentspre_checkout_query - Pre-checkout query for paymentssuccessful_payment - Payment completedpassport_data - Telegram Passport dataweb_app_data - Web App datavideo_chat_started - Video chat startedvideo_chat_ended - Video chat endedvideo_chat_participants_invited - Participants invited to video chatvideo_chat_scheduled - Video chat scheduledchat_member_updated - Chat member status updatedmy_chat_member - Bot's chat member status updatedchat_join_request - Chat join requestmessage_reaction - Message reaction changedinterface Update {
update_id: number;
message?: Message;
edited_message?: Message;
channel_post?: Message;
edited_channel_post?: Message;
inline_query?: InlineQuery;
chosen_inline_result?: ChosenInlineResult;
callback_query?: CallbackQuery;
shipping_query?: ShippingQuery;
pre_checkout_query?: PreCheckoutQuery;
poll?: Poll;
poll_answer?: PollAnswer;
my_chat_member?: ChatMemberUpdated;
chat_member?: ChatMemberUpdated;
chat_join_request?: ChatJoinRequest;
message_reaction?: MessageReactionUpdated;
message_reaction_count?: MessageReactionCountUpdated;
chat_boost?: ChatBoostUpdated;
removed_chat_boost?: ChatBoostRemoved;
business_connection?: BusinessConnection;
business_message?: Message;
edited_business_message?: Message;
deleted_business_messages?: BusinessMessagesDeleted;
}
interface Message {
message_id: number;
message_thread_id?: number;
from?: User;
sender_chat?: Chat;
date: number;
chat: Chat;
forward_origin?: MessageOrigin;
is_topic_message?: boolean;
is_automatic_forward?: boolean;
reply_to_message?: Message;
external_reply?: ExternalReplyInfo;
quote?: TextQuote;
reply_to_story?: Story;
via_bot?: User;
edit_date?: number;
has_protected_content?: boolean;
media_group_id?: string;
author_signature?: string;
text?: string;
entities?: MessageEntity[];
// ... additional message fields
}