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

messaging.mddocs/

Messaging and Communication

Core messaging functionality for sending text messages, handling replies, forwarding, and copying messages between chats.

Capabilities

Basic Messaging

Core text messaging functionality with support for formatting, keyboards, and reply handling.

/**
 * Send text message to chat
 * @param {number|string} chatId - Chat identifier
 * @param {string} text - Text message to send (1-4096 characters)
 * @param {object} [options] - Additional options
 * @returns {Promise<Message>}
 */
sendMessage(chatId, text, options): Promise<Message>;

Usage Example:

// Simple text message
await bot.sendMessage(chatId, 'Hello, World!');

// Message with formatting
await bot.sendMessage(chatId, '*Bold text* and _italic text_', {
  parse_mode: 'Markdown'
});

// Message with HTML formatting
await bot.sendMessage(chatId, '<b>Bold</b> and <i>italic</i>', {
  parse_mode: 'HTML'
});

// Message with inline keyboard
await bot.sendMessage(chatId, 'Choose an option:', {
  reply_markup: {
    inline_keyboard: [
      [
        { text: 'Option 1', callback_data: 'opt_1' },
        { text: 'Option 2', callback_data: 'opt_2' }
      ],
      [
        { text: 'Visit Website', url: 'https://example.com' }
      ]
    ]
  }
});

// Message with reply keyboard
await bot.sendMessage(chatId, 'Select from menu:', {
  reply_markup: {
    keyboard: [
      ['🍕 Pizza', '🍔 Burger'],
      ['🥗 Salad', '🍜 Soup'],
      ['❌ Cancel']
    ],
    one_time_keyboard: true,
    resize_keyboard: true
  }
});

// Reply to specific message
await bot.sendMessage(chatId, 'This is a reply', {
  reply_to_message_id: messageId
});

// Silent message (no notification)
await bot.sendMessage(chatId, 'Silent message', {
  disable_notification: true
});

Message Forwarding

Methods for forwarding messages between chats with support for single and batch operations.

/**
 * Forward a message from one chat to another
 * @param {number|string} chatId - Target chat identifier
 * @param {number|string} fromChatId - Source chat identifier
 * @param {number} messageId - Message identifier to forward
 * @param {object} [options] - Additional options
 * @returns {Promise<Message>}
 */
forwardMessage(chatId, fromChatId, messageId, options): Promise<Message>;

/**
 * Forward multiple messages from one chat to another
 * @param {number|string} chatId - Target chat identifier
 * @param {number|string} fromChatId - Source chat identifier
 * @param {number[]} messageIds - Array of message identifiers to forward
 * @param {object} [options] - Additional options
 * @returns {Promise<MessageId[]>}
 */
forwardMessages(chatId, fromChatId, messageIds, options): Promise<MessageId[]>;

Usage Example:

// Forward single message
const forwardedMessage = await bot.forwardMessage(
  targetChatId,     // Where to forward
  sourceChatId,     // Where from
  messageId,        // Which message
  {
    disable_notification: true
  }
);

// Forward multiple messages
const messageIds = [123, 124, 125];
const forwardedMessages = await bot.forwardMessages(
  targetChatId,
  sourceChatId,
  messageIds,
  {
    disable_notification: false,
    protect_content: true
  }
);

console.log(`Forwarded ${forwardedMessages.length} messages`);

Message Copying

Methods for copying message content to other chats while allowing modifications.

/**
 * Copy a message from one chat to another
 * @param {number|string} chatId - Target chat identifier
 * @param {number|string} fromChatId - Source chat identifier
 * @param {number} messageId - Message identifier to copy
 * @param {object} [options] - Additional options and modifications
 * @returns {Promise<MessageId>}
 */
copyMessage(chatId, fromChatId, messageId, options): Promise<MessageId>;

/**
 * Copy multiple messages from one chat to another
 * @param {number|string} chatId - Target chat identifier
 * @param {number|string} fromChatId - Source chat identifier
 * @param {number[]} messageIds - Array of message identifiers to copy
 * @param {object} [options] - Additional options
 * @returns {Promise<MessageId[]>}
 */
copyMessages(chatId, fromChatId, messageIds, options): Promise<MessageId[]>;

Usage Example:

// Copy message with modified caption
const copiedMessage = await bot.copyMessage(
  targetChatId,
  sourceChatId,
  messageId,
  {
    caption: 'Modified caption for copied message',
    parse_mode: 'HTML',
    reply_markup: {
      inline_keyboard: [
        [{ text: 'New Button', callback_data: 'new_action' }]
      ]
    }
  }
);

// Copy multiple messages
const messageIds = [100, 101, 102];
const copiedMessages = await bot.copyMessages(
  targetChatId,
  sourceChatId,
  messageIds,
  {
    disable_notification: true,
    remove_caption: false
  }
);

Message Editing

Methods for editing previously sent messages including text, captions, media, and keyboards.

/**
 * Edit text of a message
 * @param {string} text - New text content
 * @param {object} [options] - Edit options with chat_id and message_id
 * @returns {Promise<Message|boolean>}
 */
editMessageText(text, options): Promise<Message|boolean>;

/**
 * Edit caption of a message
 * @param {string} caption - New caption text
 * @param {object} [options] - Edit options with chat_id and message_id
 * @returns {Promise<Message|boolean>}
 */
editMessageCaption(caption, options): Promise<Message|boolean>;

/**
 * Edit media content of a message
 * @param {object} media - New media object
 * @param {object} [options] - Edit options with chat_id and message_id
 * @returns {Promise<Message|boolean>}
 */
editMessageMedia(media, options): Promise<Message|boolean>;

/**
 * Edit reply markup (inline keyboard) of a message
 * @param {object} replyMarkup - New reply markup
 * @param {object} [options] - Edit options with chat_id and message_id
 * @returns {Promise<Message|boolean>}
 */
editMessageReplyMarkup(replyMarkup, options): Promise<Message|boolean>;

Usage Example:

// Edit text message
await bot.editMessageText('Updated text content', {
  chat_id: chatId,
  message_id: messageId,
  parse_mode: 'HTML'
});

// Edit message caption
await bot.editMessageCaption('New caption with <b>formatting</b>', {
  chat_id: chatId,
  message_id: messageId,
  parse_mode: 'HTML'
});

// Edit inline keyboard
await bot.editMessageReplyMarkup({
  inline_keyboard: [
    [
      { text: 'Updated Button', callback_data: 'updated_action' },
      { text: 'Delete', callback_data: 'delete_message' }
    ]
  ]
}, {
  chat_id: chatId,
  message_id: messageId
});

// Edit media (photo to video)
await bot.editMessageMedia({
  type: 'video',
  media: 'https://example.com/video.mp4',
  caption: 'Updated video with new caption'
}, {
  chat_id: chatId,
  message_id: messageId
});

// Edit inline message (for inline query results)
await bot.editMessageText('Updated inline message', {
  inline_message_id: inlineMessageId
});

Message Deletion

Methods for deleting messages from chats with support for single and batch operations.

/**
 * Delete a message
 * @param {number|string} chatId - Chat identifier
 * @param {number} messageId - Message identifier to delete
 * @param {object} [options] - Additional options
 * @returns {Promise<boolean>}
 */
deleteMessage(chatId, messageId, options): Promise<boolean>;

/**
 * Delete multiple messages
 * @param {number|string} chatId - Chat identifier
 * @param {number[]} messageIds - Array of message identifiers to delete
 * @param {object} [options] - Additional options
 * @returns {Promise<boolean>}
 */
deleteMessages(chatId, messageIds, options): Promise<boolean>;

Usage Example:

// Delete single message
const deleted = await bot.deleteMessage(chatId, messageId);
if (deleted) {
  console.log('Message deleted successfully');
}

// Delete multiple messages
const messageIds = [123, 124, 125, 126];
const allDeleted = await bot.deleteMessages(chatId, messageIds);
if (allDeleted) {
  console.log('All messages deleted successfully');
}

// Delete with error handling
try {
  await bot.deleteMessage(chatId, messageId);
} catch (error) {
  if (error.code === 'ETELEGRAM') {
    console.log('Cannot delete message:', error.message);
  }
}

Callback Query Handling

Method for responding to inline keyboard button presses.

/**
 * Answer callback query from inline keyboard
 * @param {string} callbackQueryId - Callback query identifier
 * @param {object} [options] - Answer options
 * @returns {Promise<boolean>}
 */
answerCallbackQuery(callbackQueryId, options): Promise<boolean>;

Usage Example:

// Handle callback queries
bot.on('callback_query', async (callbackQuery) => {
  const data = callbackQuery.data;
  const messageId = callbackQuery.message.message_id;
  const chatId = callbackQuery.message.chat.id;
  
  // Answer the callback query
  await bot.answerCallbackQuery(callbackQuery.id, {
    text: `You clicked: ${data}`,
    show_alert: false
  });
  
  // Handle different callback data
  switch (data) {
    case 'delete_message':
      await bot.deleteMessage(chatId, messageId);
      break;
      
    case 'edit_message':
      await bot.editMessageText('Message was edited!', {
        chat_id: chatId,
        message_id: messageId
      });
      break;
      
    case 'show_alert':
      await bot.answerCallbackQuery(callbackQuery.id, {
        text: 'This is an alert!',
        show_alert: true
      });
      break;
  }
});

// Send message with callback buttons
await bot.sendMessage(chatId, 'Choose an action:', {
  reply_markup: {
    inline_keyboard: [
      [
        { text: '✏️ Edit', callback_data: 'edit_message' },
        { text: '🗑️ Delete', callback_data: 'delete_message' }
      ],
      [
        { text: '⚠️ Alert', callback_data: 'show_alert' }
      ]
    ]
  }
});

Types

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[];
  animation?: Animation;
  audio?: Audio;
  document?: Document;
  photo?: PhotoSize[];
  sticker?: Sticker;
  story?: Story;
  video?: Video;
  video_note?: VideoNote;
  voice?: Voice;
  caption?: string;
  caption_entities?: MessageEntity[];
  has_media_spoiler?: boolean;
  contact?: Contact;
  dice?: Dice;
  game?: Game;
  poll?: Poll;
  venue?: Venue;
  location?: Location;
  new_chat_members?: User[];
  left_chat_member?: User;
  new_chat_title?: string;
  new_chat_photo?: PhotoSize[];
  delete_chat_photo?: boolean;
  group_chat_created?: boolean;
  supergroup_chat_created?: boolean;
  channel_chat_created?: boolean;
  message_auto_delete_timer_changed?: MessageAutoDeleteTimerChanged;
  migrate_to_chat_id?: number;
  migrate_from_chat_id?: number;
  pinned_message?: MaybeInaccessibleMessage;
  invoice?: Invoice;
  successful_payment?: SuccessfulPayment;
  users_shared?: UsersShared;
  chat_shared?: ChatShared;
  connected_website?: string;
  write_access_allowed?: WriteAccessAllowed;
  passport_data?: PassportData;
  proximity_alert_triggered?: ProximityAlertTriggered;
  boost_added?: ChatBoostAdded;
  forum_topic_created?: ForumTopicCreated;
  forum_topic_edited?: ForumTopicEdited;
  forum_topic_closed?: ForumTopicClosed;
  forum_topic_reopened?: ForumTopicReopened;
  general_forum_topic_hidden?: GeneralForumTopicHidden;
  general_forum_topic_unhidden?: GeneralForumTopicUnhidden;
  giveaway_created?: GiveawayCreated;
  giveaway?: Giveaway;
  giveaway_winners?: GiveawayWinners;
  giveaway_completed?: GiveawayCompleted;
  video_chat_scheduled?: VideoChatScheduled;
  video_chat_started?: VideoChatStarted;
  video_chat_ended?: VideoChatEnded;
  video_chat_participants_invited?: VideoChatParticipantsInvited;
  web_app_data?: WebAppData;
  reply_markup?: InlineKeyboardMarkup;
}

interface MessageId {
  message_id: number;
}

interface InlineKeyboardMarkup {
  inline_keyboard: InlineKeyboardButton[][];
}

interface InlineKeyboardButton {
  text: string;
  url?: string;
  callback_data?: string;
  web_app?: WebApp;
  login_url?: LoginUrl;
  switch_inline_query?: string;
  switch_inline_query_current_chat?: string;
  switch_inline_query_chosen_chat?: SwitchInlineQueryChosenChat;
  callback_game?: CallbackGame;
  pay?: boolean;
}

interface ReplyKeyboardMarkup {
  keyboard: KeyboardButton[][];
  is_persistent?: boolean;
  resize_keyboard?: boolean;
  one_time_keyboard?: boolean;
  input_field_placeholder?: string;
  selective?: boolean;
}

interface KeyboardButton {
  text: string;
  request_users?: KeyboardButtonRequestUsers;
  request_chat?: KeyboardButtonRequestChat;
  request_contact?: boolean;
  request_location?: boolean;
  request_poll?: KeyboardButtonPollType;
  web_app?: WebApp;
}

interface SendMessageOptions {
  business_connection_id?: string;
  message_thread_id?: number;
  parse_mode?: 'HTML' | 'Markdown' | 'MarkdownV2';
  entities?: MessageEntity[];
  link_preview_options?: LinkPreviewOptions;
  disable_notification?: boolean;
  protect_content?: boolean;
  reply_parameters?: ReplyParameters;
  reply_markup?: InlineKeyboardMarkup | ReplyKeyboardMarkup | ReplyKeyboardRemove | ForceReply;
}

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