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
Advanced Telegram features including inline queries, payments, games, sticker management, forum topics, and business features for sophisticated bot implementations.
Methods for handling inline queries and web app interactions.
/**
* Answer inline query with results
* @param {string} inlineQueryId - Inline query identifier
* @param {object[]} results - Array of inline query results
* @param {object} [options] - Answer options
* @returns {Promise<boolean>}
*/
answerInlineQuery(inlineQueryId, results, options): Promise<boolean>;
/**
* Answer Web App query
* @param {string} webAppQueryId - Web App query identifier
* @param {object} result - Inline query result
* @param {object} [options] - Additional options
* @returns {Promise<SentWebAppMessage>}
*/
answerWebAppQuery(webAppQueryId, result, options): Promise<SentWebAppMessage>;Usage Example:
// Handle inline queries
bot.on('inline_query', async (inlineQuery) => {
const query = inlineQuery.query;
const results = [];
// Create article results based on query
if (query.toLowerCase().includes('weather')) {
results.push({
type: 'article',
id: '1',
title: 'Weather Information',
description: 'Get current weather data',
input_message_content: {
message_text: `Weather query: ${query}`,
parse_mode: 'HTML'
},
reply_markup: {
inline_keyboard: [
[{ text: '🌤️ Check Weather', callback_data: 'weather_check' }]
]
}
});
}
// Add photo result
results.push({
type: 'photo',
id: '2',
photo_url: 'https://example.com/photo.jpg',
thumbnail_url: 'https://example.com/thumb.jpg',
caption: `Photo result for: ${query}`
});
// Add GIF result
results.push({
type: 'gif',
id: '3',
gif_url: 'https://example.com/animation.gif',
thumbnail_url: 'https://example.com/gif-thumb.jpg',
title: 'Animated Result'
});
// Answer the inline query
await bot.answerInlineQuery(inlineQuery.id, results, {
cache_time: 300,
is_personal: true,
next_offset: results.length < 10 ? '' : '10'
});
});
// Handle Web App queries
bot.on('web_app_data', async (msg) => {
const webAppData = msg.web_app_data;
console.log('Web App data:', webAppData.data);
// Process the data and respond
await bot.sendMessage(msg.chat.id, `Received Web App data: ${webAppData.data}`);
});
// Answer Web App query (typically called from web app)
await bot.answerWebAppQuery('web_app_query_id', {
type: 'article',
id: 'webapp_result',
title: 'Web App Result',
input_message_content: {
message_text: 'Result from Web App interaction'
}
});Comprehensive payment processing including invoices, shipping, and checkout handling.
/**
* Send invoice for payment
* @param {number|string} chatId - Chat identifier
* @param {string} title - Product title
* @param {string} description - Product description
* @param {string} payload - Bot-defined invoice payload
* @param {string} providerToken - Payment provider token
* @param {string} currency - Three-letter ISO 4217 currency code
* @param {object[]} prices - Price breakdown
* @param {object} [options] - Invoice options
* @returns {Promise<Message>}
*/
sendInvoice(chatId, title, description, payload, providerToken, currency, prices, options): Promise<Message>;
/**
* Create invoice link for payments
* @param {string} title - Product title
* @param {string} description - Product description
* @param {string} payload - Bot-defined invoice payload
* @param {string} providerToken - Payment provider token
* @param {string} currency - Three-letter ISO 4217 currency code
* @param {object[]} prices - Price breakdown
* @param {object} [options] - Invoice options
* @returns {Promise<string>}
*/
createInvoiceLink(title, description, payload, providerToken, currency, prices, options): Promise<string>;
/**
* Answer shipping query with shipping options
* @param {string} shippingQueryId - Shipping query identifier
* @param {boolean} ok - Specify if delivery is possible
* @param {object} [options] - Shipping options
* @returns {Promise<boolean>}
*/
answerShippingQuery(shippingQueryId, ok, options): Promise<boolean>;
/**
* Answer pre-checkout query
* @param {string} preCheckoutQueryId - Pre-checkout query identifier
* @param {boolean} ok - Specify if everything is alright
* @param {object} [options] - Pre-checkout options
* @returns {Promise<boolean>}
*/
answerPreCheckoutQuery(preCheckoutQueryId, ok, options): Promise<boolean>;Usage Example:
// Send invoice
await bot.sendInvoice(
chatId,
'Premium Subscription',
'Monthly premium subscription with advanced features',
'premium_sub_payload_123',
process.env.PAYMENT_PROVIDER_TOKEN,
'USD',
[
{ label: 'Premium Subscription', amount: 999 }, // $9.99
{ label: 'Tax', amount: 100 } // $1.00
],
{
photo_url: 'https://example.com/premium-badge.jpg',
photo_width: 512,
photo_height: 512,
need_name: true,
need_phone_number: false,
need_email: true,
need_shipping_address: false,
send_phone_number_to_provider: false,
send_email_to_provider: true,
is_flexible: false
}
);
// Create invoice link
const invoiceLink = await bot.createInvoiceLink(
'Digital Product',
'Downloadable content package',
'digital_product_payload',
process.env.PAYMENT_PROVIDER_TOKEN,
'USD',
[{ label: 'Digital Product', amount: 1999 }] // $19.99
);
console.log('Invoice link:', invoiceLink);
// Handle shipping queries
bot.on('shipping_query', async (shippingQuery) => {
const shippingAddress = shippingQuery.shipping_address;
// Check if shipping is available to this address
if (shippingAddress.country_code === 'US') {
await bot.answerShippingQuery(shippingQuery.id, true, {
shipping_options: [
{
id: 'standard',
title: 'Standard Shipping',
prices: [{ label: 'Standard', amount: 500 }] // $5.00
},
{
id: 'express',
title: 'Express Shipping',
prices: [{ label: 'Express', amount: 1500 }] // $15.00
}
]
});
} else {
await bot.answerShippingQuery(shippingQuery.id, false, {
error_message: 'Sorry, we do not ship to your country.'
});
}
});
// Handle pre-checkout queries
bot.on('pre_checkout_query', async (preCheckoutQuery) => {
// Verify the payload and order details
const payload = preCheckoutQuery.invoice_payload;
const totalAmount = preCheckoutQuery.total_amount;
console.log(`Pre-checkout: ${payload}, amount: ${totalAmount}`);
// Approve the payment
await bot.answerPreCheckoutQuery(preCheckoutQuery.id, true);
// Or reject with error
// await bot.answerPreCheckoutQuery(preCheckoutQuery.id, false, {
// error_message: 'Payment verification failed.'
// });
});
// Handle successful payments
bot.on('successful_payment', (msg) => {
const payment = msg.successful_payment;
console.log('Payment successful!');
console.log('Currency:', payment.currency);
console.log('Total amount:', payment.total_amount);
console.log('Payload:', payment.invoice_payload);
console.log('Provider payment charge ID:', payment.provider_payment_charge_id);
console.log('Telegram payment charge ID:', payment.telegram_payment_charge_id);
// Send confirmation message
bot.sendMessage(msg.chat.id, '✅ Payment successful! Thank you for your purchase.');
});Methods for implementing Telegram games with score management.
/**
* Send game
* @param {number|string} chatId - Chat identifier
* @param {string} gameShortName - Short name of the game
* @param {object} [options] - Game options
* @returns {Promise<Message>}
*/
sendGame(chatId, gameShortName, options): Promise<Message>;
/**
* Set game score for user
* @param {number} userId - User identifier
* @param {number} score - New score value
* @param {object} options - Score options with chat_id and message_id
* @returns {Promise<Message|boolean>}
*/
setGameScore(userId, score, options): Promise<Message|boolean>;
/**
* Get game high scores
* @param {number} userId - User identifier
* @param {object} options - High score options with chat_id and message_id
* @returns {Promise<GameHighScore[]>}
*/
getGameHighScores(userId, options): Promise<GameHighScore[]>;Usage Example:
// Send game
const gameMessage = await bot.sendGame(chatId, 'my_awesome_game', {
disable_notification: true,
reply_markup: {
inline_keyboard: [
[{ text: '🎮 Play Game', callback_game: {} }]
]
}
});
// Handle game callback
bot.on('callback_query', async (callbackQuery) => {
if (callbackQuery.game_short_name) {
// User wants to play the game
const gameUrl = `https://mybot.example.com/game?user=${callbackQuery.from.id}`;
await bot.answerCallbackQuery(callbackQuery.id, {
url: gameUrl
});
}
});
// Set game score (called from game server)
await bot.setGameScore(userId, 1500, {
chat_id: chatId,
message_id: gameMessageId,
force: false, // Don't decrease score
disable_edit_message: false
});
// Get high scores
const highScores = await bot.getGameHighScores(userId, {
chat_id: chatId,
message_id: gameMessageId
});
console.log('High scores:');
highScores.forEach((score, index) => {
console.log(`${index + 1}. ${score.user.first_name}: ${score.score}`);
});
// Handle game score updates in groups
bot.on('chosen_inline_result', (chosenResult) => {
if (chosenResult.query === 'game_score') {
console.log('User chose game score result:', chosenResult.result_id);
}
});Advanced sticker set creation and management functionality.
/**
* Upload sticker file
* @param {number} userId - User identifier
* @param {string|Buffer|stream.Readable} sticker - Sticker file
* @param {string} stickerFormat - Sticker format (static, animated, video)
* @param {object} [options] - Upload options
* @param {object} [fileOptions] - File options
* @returns {Promise<File>}
*/
uploadStickerFile(userId, sticker, stickerFormat, options, fileOptions): Promise<File>;
/**
* Create new sticker set
* @param {number} userId - User identifier
* @param {string} name - Sticker set name
* @param {string} title - Sticker set title
* @param {object[]} stickers - Initial stickers
* @param {string} stickerFormat - Sticker format
* @param {object} [options] - Creation options
* @returns {Promise<boolean>}
*/
createNewStickerSet(userId, name, title, stickers, stickerFormat, options): Promise<boolean>;
/**
* Add sticker to existing set
* @param {number} userId - User identifier
* @param {string} name - Sticker set name
* @param {object} sticker - Sticker to add
* @param {object} [options] - Add options
* @returns {Promise<boolean>}
*/
addStickerToSet(userId, name, sticker, options): Promise<boolean>;
/**
* Set sticker position in set
* @param {string} sticker - File identifier of sticker
* @param {number} position - New position (0-based)
* @param {object} [options] - Additional options
* @returns {Promise<boolean>}
*/
setStickerPositionInSet(sticker, position, options): Promise<boolean>;
/**
* Delete sticker from set
* @param {string} sticker - File identifier of sticker
* @param {object} [options] - Additional options
* @returns {Promise<boolean>}
*/
deleteStickerFromSet(sticker, options): Promise<boolean>;
/**
* Set sticker set thumbnail
* @param {number} userId - User identifier
* @param {string} name - Sticker set name
* @param {string|Buffer|stream.Readable} thumbnail - Thumbnail file
* @param {object} [options] - Thumbnail options
* @param {object} [fileOptions] - File options
* @returns {Promise<boolean>}
*/
setStickerSetThumbnail(userId, name, thumbnail, options, fileOptions): Promise<boolean>;
/**
* Replace sticker in set
* @param {number} userId - User identifier
* @param {string} name - Sticker set name
* @param {string} oldSticker - File identifier of sticker to replace
* @param {object} sticker - New sticker data
* @param {object} [options] - Additional options
* @returns {Promise<boolean>}
*/
replaceStickerInSet(userId, name, oldSticker, sticker, options): Promise<boolean>;
/**
* Set sticker emoji list
* @param {string} sticker - File identifier of sticker
* @param {string[]} emojiList - List of emoji associated with sticker
* @param {object} [options] - Additional options
* @returns {Promise<boolean>}
*/
setStickerEmojiList(sticker, emojiList, options): Promise<boolean>;
/**
* Set sticker keywords for search
* @param {string} sticker - File identifier of sticker
* @param {string[]} keywords - List of keywords (0-20 items, 1-64 chars each)
* @param {object} [options] - Additional options
* @returns {Promise<boolean>}
*/
setStickerKeywords(sticker, keywords, options): Promise<boolean>;
/**
* Set sticker mask position
* @param {string} sticker - File identifier of sticker
* @param {object} maskPosition - Mask position object
* @param {object} [options] - Additional options
* @returns {Promise<boolean>}
*/
setStickerMaskPosition(sticker, maskPosition, options): Promise<boolean>;
/**
* Set sticker set title
* @param {string} name - Sticker set name
* @param {string} title - New sticker set title (1-64 chars)
* @param {object} [options] - Additional options
* @returns {Promise<boolean>}
*/
setStickerSetTitle(name, title, options): Promise<boolean>;
/**
* Set custom emoji sticker set thumbnail
* @param {string} name - Sticker set name
* @param {string} customEmojiId - Custom emoji identifier for thumbnail
* @param {object} [options] - Additional options
* @returns {Promise<boolean>}
*/
setCustomEmojiStickerSetThumbnail(name, customEmojiId, options): Promise<boolean>;
/**
* Delete sticker set
* @param {string} name - Sticker set name
* @param {object} [options] - Additional options
* @returns {Promise<boolean>}
*/
deleteStickerSet(name, options): Promise<boolean>;Usage Example:
// Create new sticker set
const userId = 12345;
const stickerSetName = `my_stickers_by_${bot.options.username}`;
await bot.createNewStickerSet(
userId,
stickerSetName,
'My Custom Stickers',
[
{
sticker: './sticker1.webp',
emoji_list: ['😀', '😊']
},
{
sticker: './sticker2.webp',
emoji_list: ['😂', '🤣']
}
],
'static',
{
sticker_type: 'regular'
}
);
// Add sticker to existing set
await bot.addStickerToSet(userId, stickerSetName, {
sticker: './new_sticker.webp',
emoji_list: ['🎉', '🎊']
});
// Reorder stickers
await bot.setStickerPositionInSet('CAADAgADAAECAwQFBg', 0); // Move to first position
// Delete sticker
await bot.deleteStickerFromSet('CAADAgADAAECAwQFBg');
// Set thumbnail for sticker set
await bot.setStickerSetThumbnail(userId, stickerSetName, './thumbnail.webp');
// Upload sticker file first, then use in set
const uploadedFile = await bot.uploadStickerFile(userId, './animated_sticker.tgs', 'animated');
console.log('Uploaded file ID:', uploadedFile.file_id);Methods for managing forum topics in supergroups.
/**
* Get forum topic icon stickers
* @param {number|string} chatId - Chat identifier
* @param {object} [options] - Additional options
* @returns {Promise<Sticker[]>}
*/
getForumTopicIconStickers(chatId, options): Promise<Sticker[]>;
/**
* Create forum topic
* @param {number|string} chatId - Chat identifier
* @param {string} name - Topic name
* @param {object} [options] - Topic options
* @returns {Promise<ForumTopic>}
*/
createForumTopic(chatId, name, options): Promise<ForumTopic>;
/**
* Edit forum topic
* @param {number|string} chatId - Chat identifier
* @param {number} messageThreadId - Topic thread identifier
* @param {object} [options] - Edit options
* @returns {Promise<boolean>}
*/
editForumTopic(chatId, messageThreadId, options): Promise<boolean>;
/**
* Close forum topic
* @param {number|string} chatId - Chat identifier
* @param {number} messageThreadId - Topic thread identifier
* @param {object} [options] - Additional options
* @returns {Promise<boolean>}
*/
closeForumTopic(chatId, messageThreadId, options): Promise<boolean>;
/**
* Reopen forum topic
* @param {number|string} chatId - Chat identifier
* @param {number} messageThreadId - Topic thread identifier
* @param {object} [options] - Additional options
* @returns {Promise<boolean>}
*/
reopenForumTopic(chatId, messageThreadId, options): Promise<boolean>;
/**
* Delete forum topic
* @param {number|string} chatId - Chat identifier
* @param {number} messageThreadId - Topic thread identifier
* @param {object} [options] - Additional options
* @returns {Promise<boolean>}
*/
deleteForumTopic(chatId, messageThreadId, options): Promise<boolean>;
/**
* Unpin all forum topic messages
* @param {number|string} chatId - Chat identifier
* @param {number} messageThreadId - Topic thread identifier
* @param {object} [options] - Additional options
* @returns {Promise<boolean>}
*/
unpinAllForumTopicMessages(chatId, messageThreadId, options): Promise<boolean>;
/**
* Edit general forum topic name
* @param {number|string} chatId - Chat identifier
* @param {string} name - New general topic name
* @param {object} [options] - Additional options
* @returns {Promise<boolean>}
*/
editGeneralForumTopic(chatId, name, options): Promise<boolean>;
/**
* Close general forum topic
* @param {number|string} chatId - Chat identifier
* @param {object} [options] - Additional options
* @returns {Promise<boolean>}
*/
closeGeneralForumTopic(chatId, options): Promise<boolean>;
/**
* Reopen general forum topic
* @param {number|string} chatId - Chat identifier
* @param {object} [options] - Additional options
* @returns {Promise<boolean>}
*/
reopenGeneralForumTopic(chatId, options): Promise<boolean>;
/**
* Hide general forum topic
* @param {number|string} chatId - Chat identifier
* @param {object} [options] - Additional options
* @returns {Promise<boolean>}
*/
hideGeneralForumTopic(chatId, options): Promise<boolean>;
/**
* Unhide general forum topic
* @param {number|string} chatId - Chat identifier
* @param {object} [options] - Additional options
* @returns {Promise<boolean>}
*/
unhideGeneralForumTopic(chatId, options): Promise<boolean>;
/**
* Unpin all general forum topic messages
* @param {number|string} chatId - Chat identifier
* @param {object} [options] - Additional options
* @returns {Promise<boolean>}
*/
unpinAllGeneralForumTopicMessages(chatId, options): Promise<boolean>;Usage Example:
// Get available forum icons
const iconStickers = await bot.getForumTopicIconStickers(forumChatId);
console.log(`Available ${iconStickers.length} forum icons`);
// Create new forum topic
const newTopic = await bot.createForumTopic(forumChatId, 'General Discussion', {
icon_color: 0x6FB9F0, // Blue color
icon_custom_emoji_id: iconStickers[0].custom_emoji_id
});
console.log('Created topic:', newTopic.name);
console.log('Thread ID:', newTopic.message_thread_id);
// Edit forum topic
await bot.editForumTopic(forumChatId, newTopic.message_thread_id, {
name: 'Updated Discussion Topic',
icon_custom_emoji_id: iconStickers[1].custom_emoji_id
});
// Send message to forum topic
await bot.sendMessage(forumChatId, 'Hello in the forum topic!', {
message_thread_id: newTopic.message_thread_id
});
// Close topic
await bot.closeForumTopic(forumChatId, newTopic.message_thread_id);
// Reopen topic
await bot.reopenForumTopic(forumChatId, newTopic.message_thread_id);
// Handle forum topic events
bot.on('forum_topic_created', (msg) => {
const topic = msg.forum_topic_created;
console.log(`New forum topic created: ${topic.name}`);
});
bot.on('forum_topic_closed', (msg) => {
console.log('Forum topic was closed');
});Methods for handling business-related functionality.
/**
* Get user's chat boosts
* @param {number|string} chatId - Chat identifier
* @param {number} userId - User identifier
* @param {object} [options] - Additional options
* @returns {Promise<UserChatBoosts>}
*/
getUserChatBoosts(chatId, userId, options): Promise<UserChatBoosts>;
/**
* Get business connection information
* @param {string} businessConnectionId - Business connection identifier
* @param {object} [options] - Additional options
* @returns {Promise<BusinessConnection>}
*/
getBusinessConnection(businessConnectionId, options): Promise<BusinessConnection>;Usage Example:
// Get user's boosts for a chat
const userBoosts = await bot.getUserChatBoosts(chatId, userId);
console.log(`User has ${userBoosts.boosts.length} active boosts`);
userBoosts.boosts.forEach(boost => {
console.log(`Boost expires: ${new Date(boost.expiration_date * 1000)}`);
console.log(`Boost source: ${boost.source.source}`);
});
// Handle business connection updates
bot.on('business_connection', (businessConnection) => {
console.log('Business connection updated:', businessConnection.id);
console.log('User:', businessConnection.user.first_name);
console.log('Can reply:', businessConnection.can_reply);
console.log('Is enabled:', businessConnection.is_enabled);
});
// Handle business messages
bot.on('business_message', (msg) => {
console.log('Business message received:', msg.text);
console.log('Business connection:', msg.business_connection_id);
// Reply to business message
bot.sendMessage(msg.chat.id, 'Thank you for your business message!', {
business_connection_id: msg.business_connection_id
});
});interface InlineQueryResult {
type: string;
id: string;
}
interface InlineQueryResultArticle extends InlineQueryResult {
type: 'article';
title: string;
input_message_content: InputMessageContent;
reply_markup?: InlineKeyboardMarkup;
url?: string;
hide_url?: boolean;
description?: string;
thumbnail_url?: string;
thumbnail_width?: number;
thumbnail_height?: number;
}
interface InlineQueryResultPhoto extends InlineQueryResult {
type: 'photo';
photo_url: string;
thumbnail_url: string;
photo_width?: number;
photo_height?: number;
title?: string;
description?: string;
caption?: string;
parse_mode?: string;
caption_entities?: MessageEntity[];
reply_markup?: InlineKeyboardMarkup;
input_message_content?: InputMessageContent;
}
interface LabeledPrice {
label: string;
amount: number;
}
interface ShippingOption {
id: string;
title: string;
prices: LabeledPrice[];
}
interface SuccessfulPayment {
currency: string;
total_amount: number;
invoice_payload: string;
shipping_option_id?: string;
order_info?: OrderInfo;
telegram_payment_charge_id: string;
provider_payment_charge_id: string;
}
interface GameHighScore {
position: number;
user: User;
score: number;
}
interface ForumTopic {
message_thread_id: number;
name: string;
icon_color: number;
icon_custom_emoji_id?: string;
}
interface UserChatBoosts {
boosts: ChatBoost[];
}
interface ChatBoost {
boost_id: string;
add_date: number;
expiration_date: number;
source: ChatBoostSource;
}
interface BusinessConnection {
id: string;
user: User;
user_chat_id: number;
date: number;
can_reply: boolean;
is_enabled: boolean;
}
interface SentWebAppMessage {
inline_message_id?: string;
}
interface InputMessageContent {
message_text: string;
parse_mode?: string;
entities?: MessageEntity[];
link_preview_options?: LinkPreviewOptions;
}
interface InputSticker {
sticker: string;
emoji_list: string[];
mask_position?: MaskPosition;
keywords?: string[];
}