CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-node-telegram-bot-api

Node.js wrapper for the official Telegram Bot API with polling and webhook support, comprehensive message handling, media operations, and bot management features.

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

message-handling.mddocs/

Message Handling and Events

Event-driven message processing with support for text pattern matching, reply handling, and custom event listeners for different message types.

Capabilities

Event Listeners

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);
});

Text Pattern Matching

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();

Reply Handling

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);
      }
    });
  });

Update Processing

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!'
  }
});

Event Types

The bot emits the following events based on Telegram update types:

Message Events

  • message - Any message
  • text - Text message
  • photo - Photo message
  • video - Video message
  • audio - Audio message
  • document - Document message
  • sticker - Sticker message
  • voice - Voice message
  • video_note - Video note message
  • animation - Animation/GIF message
  • contact - Contact message
  • location - Location message
  • venue - Venue message
  • poll - Poll message
  • dice - Dice message
  • game - Game message
  • invoice - Invoice message

Chat Events

  • new_chat_members - New members joined
  • left_chat_member - Member left
  • new_chat_title - Chat title changed
  • new_chat_photo - Chat photo changed
  • delete_chat_photo - Chat photo deleted
  • group_chat_created - Group chat created
  • supergroup_chat_created - Supergroup created
  • channel_chat_created - Channel created
  • message_auto_delete_timer_changed - Auto-delete timer changed
  • migrate_to_chat_id - Group migrated to supergroup
  • migrate_from_chat_id - Supergroup migrated from group
  • pinned_message - Message pinned

Interaction Events

  • callback_query - Inline keyboard button pressed
  • inline_query - Inline query received
  • chosen_inline_result - Inline result chosen
  • shipping_query - Shipping query for payments
  • pre_checkout_query - Pre-checkout query for payments
  • successful_payment - Payment completed

Other Events

  • passport_data - Telegram Passport data
  • web_app_data - Web App data
  • video_chat_started - Video chat started
  • video_chat_ended - Video chat ended
  • video_chat_participants_invited - Participants invited to video chat
  • video_chat_scheduled - Video chat scheduled
  • chat_member_updated - Chat member status updated
  • my_chat_member - Bot's chat member status updated
  • chat_join_request - Chat join request
  • message_reaction - Message reaction changed

Types

interface 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
}

docs

advanced-features.md

bot-settings.md

bot-setup.md

chat-management.md

index.md

interactive-features.md

media-files.md

message-handling.md

messaging.md

tile.json