### Configuration Guide Source: https://github.com/borodin/typescript-telegram-bot-api/blob/main/_autodocs/DOCUMENTATION_SUMMARY.txt Details on constructor options, initialization, update filtering, polling, rate limiting, proxy support, and environment-specific setups. ```APIDOC ## configuration.md ### Description This guide covers the configuration options for the Telegram Bot API, including constructor parameters, initialization examples, update type filtering, polling settings, rate limiting, and proxy support. ### Key Topics - Constructor options and defaults - Initialization examples - Update type filtering - Polling configuration - Rate limiting and auto-retry - Proxy support (HTTP/HTTPS/SOCKS5) - Environment-specific setups - Best practices - Type definitions for configuration ``` -------------------------------- ### Basic Webhook Setup with Express and ngrok Source: https://github.com/borodin/typescript-telegram-bot-api/blob/main/README.md This example demonstrates a basic Telegram bot that responds with a reaction to any incoming message using Webhooks. It uses Express for the server and ngrok for tunneling. For production, use a server with a public IP and SSL. ```typescript import 'dotenv/config'; import * as ngrok from 'ngrok'; import express from "express"; import {TelegramBot} from "./src"; import {Update} from "./src/types"; const port = 3001; const bot = new TelegramBot({ botToken: process.env.TEST_TELEGRAM_TOKEN as string, }); bot.on('message', async (message) => { await bot.setMessageReaction({ chat_id: message.chat.id, message_id: message.message_id, reaction: [{ type: 'emoji', emoji: '👍' }] }); }); const app = express(); app.use(express.json()); app.post('/', async (req, res) => { try { await bot.processUpdate(req.body as Update); res.sendStatus(200); } catch (e) { res.sendStatus(500); } }); (async () => { app.listen(port, async () => { const url = await ngrok.connect({ proto: 'http', addr: port, }); await bot.setWebhook({url}); console.log('Set Webhook to', url); }) })(); process.on('SIGINT', async () => { await bot.deleteWebhook(); await ngrok.disconnect(); console.log('Webhook deleted'); }); ``` -------------------------------- ### Basic Bot Setup and Polling Source: https://github.com/borodin/typescript-telegram-bot-api/blob/main/_autodocs/README.md Illustrates how to initialize a Telegram bot using token-based authentication and start receiving updates via polling. Includes basic message handling and graceful shutdown. ```typescript import { TelegramBot } from 'typescript-telegram-bot-api'; const bot = new TelegramBot({ botToken: process.env.BOT_TOKEN, pollingTimeout: 30, }); // Start receiving updates await bot.startPolling(); // Listen for messages bot.on('message', async (message) => { console.log(`${message.from?.first_name}: ${message.text}`); // Send a reply await bot.sendMessage({ chat_id: message.chat.id, text: 'Hello! You sent: ' + message.text, }); }); // Stop gracefully process.on('SIGINT', async () => { await bot.stopPolling(); process.exit(0); }); ``` -------------------------------- ### Basic Telegram Bot Setup Source: https://github.com/borodin/typescript-telegram-bot-api/blob/main/_autodocs/configuration.md Initializes a Telegram bot with a bot token and starts polling for updates. Includes a basic message handler to log incoming messages. ```typescript import { TelegramBot } from 'typescript-telegram-bot-api'; const bot = new TelegramBot({ botToken: process.env.BOT_TOKEN, }); // Start listening for updates await bot.startPolling(); bot.on('message', (msg) => { console.log(`${msg.from?.first_name}: ${msg.text}`); }); ``` -------------------------------- ### Install typescript-telegram-bot-api Source: https://github.com/borodin/typescript-telegram-bot-api/blob/main/README.md Install the library using npm. This is the first step to using the Telegram Bot API wrapper. ```bash npm install typescript-telegram-bot-api ``` -------------------------------- ### Send Video Example Source: https://github.com/borodin/typescript-telegram-bot-api/blob/main/_autodocs/api_methods.md Send a video file with specified dimensions and duration. ```typescript await bot.sendVideo({ chat_id: 123, video: 'https://example.com/video.mp4', width: 1920, height: 1080, duration: 60, }); ``` -------------------------------- ### Send Video Note Example Source: https://github.com/borodin/typescript-telegram-bot-api/blob/main/_autodocs/api_methods.md Send a video note with specified length and duration. ```typescript await bot.sendVideoNote({ chat_id: 123, video_note: buffer, length: 512, duration: 45, }); ``` -------------------------------- ### Get My Commands Source: https://github.com/borodin/typescript-telegram-bot-api/blob/main/_autodocs/QUICK_REFERENCE.md Returns the list of commands supported by the bot. ```APIDOC ## Get My Commands ### Description Returns the list of commands supported by the bot. ### Method `bot.getMyCommands` ### Parameters #### Request Body - **scope** (BotCommandScope) - Optional - An object, describing the scope of bot commands, for example, the scope of commands for the given chat type. Defaults to BotCommandScopeDefault. - **language_code** (string) - Optional - A localization language code. For example, 'en', 'ru', 'de'. See https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes. Default is 'en'. ``` -------------------------------- ### Send Audio Example Source: https://github.com/borodin/typescript-telegram-bot-api/blob/main/_autodocs/api_methods.md Send an audio file with optional title and performer information. ```typescript await bot.sendAudio({ chat_id: 123, audio: 'https://example.com/audio.mp3', title: 'Song Name', performer: 'Artist Name', }); ``` -------------------------------- ### Send Document Example Source: https://github.com/borodin/typescript-telegram-bot-api/blob/main/_autodocs/api_methods.md Send a general file using a readable stream. ```typescript await bot.sendDocument({ chat_id: 123, document: createReadStream('document.pdf'), }); ``` -------------------------------- ### Send Live Photo Example Source: https://github.com/borodin/typescript-telegram-bot-api/blob/main/_autodocs/api_methods.md Send a live photo, providing both the animated video and the static photo, with an optional caption. ```typescript await bot.sendLivePhoto({ chat_id: 123, live_photo: videoBuffer, photo: photoBuffer, caption: 'Live photo', }); ``` -------------------------------- ### Quick Reference Source: https://github.com/borodin/typescript-telegram-bot-api/blob/main/_autodocs/DOCUMENTATION_SUMMARY.txt A fast lookup guide with code snippets for common operations, event types, file handling patterns, and type references. ```APIDOC ## QUICK_REFERENCE.md ### Description This file serves as a quick reference guide, offering fast lookup for common operations through code snippets. It also lists all major features, event types, file handling patterns, and provides a type reference. ### Content - Code snippets for common operations - All major features at a glance - Event types listed - File handling patterns - Type reference - Performance tips ``` -------------------------------- ### Send Paid Media Example Source: https://github.com/borodin/typescript-telegram-bot-api/blob/main/_autodocs/api_methods.md Send paid media to a channel, specifying the cost in Stars and the media content. ```typescript await bot.sendPaidMedia({ chat_id: -1001234567890, // Channel star_count: 99, media: [ { type: 'photo', media: 'photo_file_id' }, { type: 'video', media: 'video_file_id' }, ], caption: 'Premium content', }); ``` -------------------------------- ### Development Bot Setup with Test Server Source: https://github.com/borodin/typescript-telegram-bot-api/blob/main/_autodocs/configuration.md Initializes a bot specifically for development using the test server. Requires a test bot token and sets a polling timeout of 30 seconds. ```typescript const devBot = new TelegramBot({ botToken: 'YOUR_TEST_TOKEN', testEnvironment: true, pollingTimeout: 30, }); devBot.startPolling(); ``` -------------------------------- ### Get File Info Source: https://github.com/borodin/typescript-telegram-bot-api/blob/main/_autodocs/TELEGRAM_BOT_API_REFERENCE.md Retrieve information about a file and prepare it for download. The download URL is constructed using the returned file_path. ```typescript const file = await bot.getFile({ file_id: 'file_id_string' }); // Download from: https://api.telegram.org/file/bot{token}/{file.file_path} ``` -------------------------------- ### Send Photo Examples Source: https://github.com/borodin/typescript-telegram-bot-api/blob/main/_autodocs/api_methods.md Demonstrates sending photos using different input types: file ID, URL, Buffer, and Stream. Also shows how to specify custom filename and content type. ```typescript await bot.sendPhoto({ chat_id: 123, photo: 'AgAC...' }); ``` ```typescript await bot.sendPhoto({ chat_id: 123, photo: 'https://example.com/photo.jpg' }); ``` ```typescript import fs from 'fs'; const buffer = fs.readFileSync('photo.jpg'); await bot.sendPhoto({ chat_id: 123, photo: buffer }); ``` ```typescript import { createReadStream } from 'fs'; await bot.sendPhoto({ chat_id: 123, photo: createReadStream('photo.jpg') }); ``` ```typescript await bot.sendPhoto({ chat_id: 123, photo: new FileOptions(buffer, { filename: 'pic.jpg', contentType: 'image/jpeg' }), }); ``` -------------------------------- ### Bot Setup with Webhooks Source: https://github.com/borodin/typescript-telegram-bot-api/blob/main/_autodocs/README.md Demonstrates setting up a Telegram bot to receive updates via webhooks using Express.js. This involves configuring the bot, setting up an Express server to handle incoming requests, and processing updates. ```typescript import express from 'express'; import { TelegramBot } from 'typescript-telegram-bot-api'; const app = express(); const bot = new TelegramBot({ botToken: process.env.BOT_TOKEN }); app.use(express.json()); app.post('/webhook', async (req, res) => { try { await bot.processUpdate(req.body); res.sendStatus(200); } catch (error) { res.sendStatus(500); } }); bot.on('message', async (msg) => { await bot.sendMessage({ chat_id: msg.chat.id, text: 'Webhook received your message!', }); }); app.listen(3000, async () => { await bot.setWebhook({ url: 'https://example.com/webhook' }); console.log('Bot ready on https://example.com/webhook'); }); ``` -------------------------------- ### Get User Profile Audios Source: https://github.com/borodin/typescript-telegram-bot-api/blob/main/_autodocs/QUICK_REFERENCE.md Gets a list of profile audios for a specified user. Requires the user ID. ```APIDOC ## Get User Profile Audios ### Description Gets a list of profile audios for a specified user. Requires the user ID. ### Method `bot.getUserProfileAudios` ### Parameters #### Request Body - **user_id** (number) - Required - Unique identifier of the target user ``` -------------------------------- ### TelegramBot.startPolling Source: https://github.com/borodin/typescript-telegram-bot-api/blob/main/_autodocs/TELEGRAM_BOT_API_REFERENCE.md Starts the long polling mechanism to receive updates from Telegram. Once started, it automatically emits update events that can be listened to. ```APIDOC ## Method startPolling ### Description Starts the long polling mechanism to receive updates from Telegram. Once started, it automatically emits update events that can be listened to. ### Method `startPolling(): Promise` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript await bot.startPolling(); bot.on('message', (msg) => console.log(msg.text)); ``` ### Response - **Promise** - A promise that resolves when polling has started. ``` -------------------------------- ### Get Bot Info Source: https://github.com/borodin/typescript-telegram-bot-api/blob/main/_autodocs/QUICK_REFERENCE.md Returns basic information about the bot. No parameters required. ```APIDOC ## Get Bot Info ### Description Returns basic information about the bot. No parameters required. ### Method `bot.getMe` ``` -------------------------------- ### Get Sticker Set Source: https://github.com/borodin/typescript-telegram-bot-api/blob/main/_autodocs/QUICK_REFERENCE.md Gets a sticker set. Requires the name of the sticker set. ```APIDOC ## Get Sticker Set ### Description Gets a sticker set. Requires the name of the sticker set. ### Method `bot.getStickerSet` ### Parameters #### Request Body - **name** (string) - Required - Name of the sticker set ``` -------------------------------- ### API Methods Reference Source: https://github.com/borodin/typescript-telegram-bot-api/blob/main/_autodocs/DOCUMENTATION_SUMMARY.txt A complete reference for over 180 API methods, organized by category, including parameters, return types, and examples. ```APIDOC ## api_methods.md ### Description This file provides a complete method reference for the Telegram Bot API, organized by category. It documents over 180 methods, detailing parameters, return types, and code examples for each. ### Categories - Polling & Updates - Webhooks - Message Sending (all types) - Message Editing & Deletion - Location, Venue, Contact - Polls & Dice - User Profile Management - Chat Operations - Member Management - Invite Links - Forum Topics - Reactions - Inline Queries - Commands - Stickers - Payments - And 10+ more categories ``` -------------------------------- ### Send Animation Example Source: https://github.com/borodin/typescript-telegram-bot-api/blob/main/_autodocs/api_methods.md Send a GIF or video animation with an optional caption. ```typescript await bot.sendAnimation({ chat_id: 123, animation: 'https://example.com/animation.gif', caption: 'Funny animation', }); ``` -------------------------------- ### Get Bot Commands Source: https://github.com/borodin/typescript-telegram-bot-api/blob/main/_autodocs/QUICK_REFERENCE.md Use this to retrieve the current list of bot commands. ```typescript const commands = await bot.getMyCommands(); ``` -------------------------------- ### Get Bot Info Source: https://github.com/borodin/typescript-telegram-bot-api/blob/main/_autodocs/QUICK_REFERENCE.md Use this to retrieve information about the bot. Returns a User object. ```typescript const me = await bot.getMe(); ``` -------------------------------- ### Requesting Contact or Location via Keyboard Source: https://github.com/borodin/typescript-telegram-bot-api/blob/main/_autodocs/README.md Demonstrates how to use a reply keyboard to prompt the user to share their contact information or location. Includes an example of listening for the 'contact' message type to process shared contacts. ```typescript await bot.sendMessage({ chat_id: 123, text: 'Share your contact:', reply_markup: { keyboard: [[{ text: 'Share Contact', request_contact: true }]], resize_keyboard: true, one_time_keyboard: true, }, }); bot.on('message:contact', (msg) => { console.log(`Contact: ${msg.contact?.phone_number}`); }); ``` -------------------------------- ### startPolling(): Promise Source: https://github.com/borodin/typescript-telegram-bot-api/blob/main/_autodocs/api_methods.md Starts long polling to receive updates from Telegram. This method is non-blocking and runs in the background. It should be called once at startup and runs continuously until stopPolling() is invoked. ```APIDOC ## startPolling() ### Description Start long polling to receive updates. Non-blocking - call and let it run in background. ### Method `startPolling` ### Parameters None ### Return `Promise` ### Example ```typescript await bot.startPolling(); // Bot will now emit events for incoming updates ``` ``` -------------------------------- ### Set and Handle Webhooks Source: https://github.com/borodin/typescript-telegram-bot-api/blob/main/_autodocs/QUICK_REFERENCE.md Configure a webhook to receive updates from Telegram at a specified URL. This example also shows how to process incoming updates using an Express.js server. ```typescript // Set webhook await bot.setWebhook({ url: 'https://example.com/webhook', secret_token: 'my-secret', }); // Handle incoming updates app.post('/webhook', express.json(), (req, res) => { bot.processUpdate(req.body); res.sendStatus(200); }); // Remove webhook await bot.deleteWebhook(); ``` -------------------------------- ### Production Bot Setup with Retries and Timeout Source: https://github.com/borodin/typescript-telegram-bot-api/blob/main/_autodocs/configuration.md Configures a bot for production with automatic request retries enabled and a retry limit of 60 seconds. Sets a balanced polling timeout suitable for production environments. ```typescript const prodBot = new TelegramBot({ botToken: process.env.BOT_TOKEN, autoRetry: true, autoRetryLimit: 60, // Retry if API wants us to wait < 60s pollingTimeout: 50, // Balanced timeout for production }); ``` -------------------------------- ### Send Voice Example Source: https://github.com/borodin/typescript-telegram-bot-api/blob/main/_autodocs/api_methods.md Send a voice message using a readable stream, specifying the duration. ```typescript await bot.sendVoice({ chat_id: 123, voice: createReadStream('voice.ogg'), duration: 30, }); ``` -------------------------------- ### Get Bot Description Source: https://github.com/borodin/typescript-telegram-bot-api/blob/main/_autodocs/api_methods.md Retrieves the full description of the bot. This can be requested for a specific language. ```typescript const desc = await bot.getMyDescription(); console.log(desc.description); ``` -------------------------------- ### Recommended Production Polling Configuration Source: https://github.com/borodin/typescript-telegram-bot-api/blob/main/_autodocs/configuration.md Sets up a bot for production with a 50-second polling timeout, enabled auto-retry for rate limits with a 30-second limit, and specifies essential allowed update types. Starts polling after configuration. ```typescript const bot = new TelegramBot({ botToken: process.env.BOT_TOKEN, pollingTimeout: 50, autoRetry: true, autoRetryLimit: 30, allowedUpdates: [ 'message', 'callback_query', 'inline_query', ], }); await bot.startPolling(); ``` -------------------------------- ### Get User Profile Audios Source: https://github.com/borodin/typescript-telegram-bot-api/blob/main/_autodocs/QUICK_REFERENCE.md Use this to retrieve profile audios for a given user. Requires user_id. ```typescript const audios = await bot.getUserProfileAudios({ user_id: 123 }); ``` -------------------------------- ### Basic Telegram Bot Usage Source: https://github.com/borodin/typescript-telegram-bot-api/blob/main/README.md Initialize a Telegram bot with your token, start polling for updates, and handle incoming messages. This snippet shows how to set up a basic bot and listen for different message types. ```typescript import { TelegramBot } from 'typescript-telegram-bot-api'; const bot = new TelegramBot({ botToken: 'YOUR_BOT_TOKEN' }); bot.startPolling(); bot.on('message', (message) => { console.log('Received message:', message.text); }); bot.on('message:sticker', (message) => { console.log('Received sticker:', message.sticker.emoji); }); bot.getMe() .then(console.log) .catch(console.error); ``` -------------------------------- ### Sending Photos with Various Sources Source: https://github.com/borodin/typescript-telegram-bot-api/blob/main/_autodocs/README.md Demonstrates multiple methods for sending photo files, including using a file ID, URL, Node.js Buffer, Node.js Stream, and a browser File object. Includes an example of sending with custom filename and content type. ```typescript // From file_id (fastest) await bot.sendPhoto({ chat_id: 123, photo: 'AgACAgIAAxk...' }); // From URL await bot.sendPhoto({ chat_id: 123, photo: 'https://example.com/photo.jpg' }); // From Buffer (Node.js) const buffer = fs.readFileSync('photo.jpg'); await bot.sendPhoto({ chat_id: 123, photo: buffer }); // From Stream (Node.js) await bot.sendPhoto({ chat_id: 123, photo: fs.createReadStream('photo.jpg') }); // With custom filename await bot.sendPhoto({ chat_id: 123, photo: new FileOptions(buffer, { filename: 'custom.jpg', contentType: 'image/jpeg', }), }); // From File (Browser) await bot.sendPhoto({ chat_id: 123, photo: inputElement.files[0] }); ``` -------------------------------- ### Handle Telegram Files Source: https://github.com/borodin/typescript-telegram-bot-api/blob/main/_autodocs/QUICK_REFERENCE.md Demonstrates various methods for handling files with the Telegram Bot API, including getting file information, sending files by ID, URL, Buffer, or Stream, and sending files with custom options. ```typescript // Get file info const file = await bot.getFile({ file_id: 'file_id' }); // Download from: https://api.telegram.org/file/bot{token}/{file.file_path} // Send from file_id await bot.sendPhoto({ chat_id: 123, photo: 'file_id' }); // Send from URL await bot.sendPhoto({ chat_id: 123, photo: 'https://example.com/photo.jpg' }); // Send from Buffer const buffer = fs.readFileSync('photo.jpg'); await bot.sendPhoto({ chat_id: 123, photo: buffer }); // Send from Stream (Node.js) await bot.sendPhoto({ chat_id: 123, photo: fs.createReadStream('photo.jpg'), }); // Send with custom filename await bot.sendPhoto({ chat_id: 123, photo: new FileOptions(buffer, { filename: 'custom.jpg', contentType: 'image/jpeg', }), }); ``` -------------------------------- ### Sending Messages with Inline Keyboard Source: https://github.com/borodin/typescript-telegram-bot-api/blob/main/_autodocs/README.md Shows how to send a message with an inline keyboard attached, allowing users to interact with buttons that trigger callback queries. Includes an example of handling these callbacks to respond to user actions. ```typescript await bot.sendMessage({ chat_id: 123, text: 'Choose an action:', reply_markup: { inline_keyboard: [ [ { text: 'Yes', callback_data: 'action:yes' }, { text: 'No', callback_data: 'action:no' }, ], ], }, }); bot.on('callback_query', async (query) => { if (query.data === 'action:yes') { await bot.answerCallbackQuery({ callback_query_id: query.id, text: 'You chose YES!', show_alert: true, }); } }); ``` -------------------------------- ### API Methods Reference Source: https://github.com/borodin/typescript-telegram-bot-api/blob/main/_autodocs/README.md A complete list of all async methods on the TelegramBot class, organized by category. Each method includes its signature, parameter details, return type, code examples, and source file location. ```APIDOC ## API Methods Reference This document provides a comprehensive list of all async methods available on the `TelegramBot` class, categorized for easy access. ### Categories: - **Polling & Updates**: `startPolling`, `stopPolling`, `getUpdates`, `processUpdate` - **Webhooks**: `setWebhook`, `deleteWebhook`, `getWebhookInfo` - **Bot Info**: `getMe`, `logOut`, `close` - **Sending Messages**: `sendMessage`, `sendPhoto`, `sendAudio`, `sendDocument`, `sendVideo`, `sendAnimation`, `sendVoice`, `sendVideoNote`, `sendMediaGroup` - **Message Forwarding**: `forwardMessage`, `forwardMessages`, `copyMessage`, `copyMessages` - **Location Messages**: `sendLocation`, `sendVenue`, `sendContact` - **Polls & Dice**: `sendPoll`, `stopPoll`, `sendDice` - **Message Editing**: `editMessageText`, `editMessageCaption`, `editMessageMedia`, `editMessageLiveLocation`, `editMessageReplyMarkup`, `deleteMessage`, `deleteMessages` - **User Methods**: `getUserProfilePhotos`, `setMyProfilePhoto`, `removeMyProfilePhoto`, `setUserEmojiStatus` - **File Handling**: `getFile` - **Chat Management**: `banChatMember`, `unbanChatMember`, `restrictChatMember`, `promoteChatMember`, `setChatAdministratorCustomTitle`, `setChatPermissions` - **Chat Info**: `getChat`, `getChatAdministrators`, `getChatMemberCount`, `getChatMember`, `leaveChat` - **Chat Profile**: `setChatPhoto`, `deleteChatPhoto`, `setChatTitle`, `setChatDescription` - **Message Pinning**: `pinChatMessage`, `unpinChatMessage`, `unpinAllChatMessages` - **Invite Links**: `exportChatInviteLink`, `createChatInviteLink`, `editChatInviteLink`, `revokeChatInviteLink` - **Forum Topics**: `createForumTopic`, `editForumTopic`, `closeForumTopic`, `reopenForumTopic`, `deleteForumTopic` - **General Forum**: `editGeneralForumTopic`, `closeGeneralForumTopic`, `reopenGeneralForumTopic`, `hideGeneralForumTopic` - **Reactions**: `setMessageReaction`, `deleteMessageReaction`, `deleteAllMessageReactions` - **Inline Queries**: `answerInlineQuery` - **Commands**: `setMyCommands`, `getMyCommands`, `deleteMyCommands` - **Bot Profile**: `setMyName`, `getMyName`, `setMyDescription`, `getMyDescription`, `setMyShortDescription` - **Stickers**: `sendSticker`, `getStickerSet`, `getCustomEmojiStickers`, `uploadStickerFile`, `createNewStickerSet`, `addStickerToSet`, `setStickerPositionInSet`, `deleteStickerFromSet`, `setStickerEmojiList`, `setStickerKeywords`, `setStickerMaskPosition`, `setStickerSetTitle`, `setStickerSetThumbnail`, `deleteStickerSet` - **Payments**: `answerShippingQuery`, `answerPreCheckoutQuery` - **Callback Queries**: `answerCallbackQuery` - **Telegram Stars**: `getMyStarBalance`, `getStarTransactions`, `refundStarPayment` - **Chat Action**: `sendChatAction` - **Message Drafts**: `sendMessageDraft` - **Rich Messages**: `sendRichMessage`, `sendRichMessageDraft` - **Gifts**: `getAvailableGifts`, `sendGift` - **User Verification**: `verifyUser`, `verifyChat`, `removeUserVerification`, `removeChatVerification` Each method includes: - Full method signature with parameter types - Parameter table with defaults and descriptions - Return type explanation - Code examples - Source file location **Use for:** Looking up specific methods and understanding their parameters. ``` -------------------------------- ### Error Handling Guide Source: https://github.com/borodin/typescript-telegram-bot-api/blob/main/_autodocs/DOCUMENTATION_SUMMARY.txt Documentation for the TelegramError class, error codes, specific error scenarios, auto-retry configuration, and recovery strategies. ```APIDOC ## errors.md ### Description This document details the `TelegramError` class, all associated error codes (e.g., 400, 401, 403, 404, 429, 500+), specific error scenarios with examples, auto-retry configuration, and recommended error handling patterns and recovery strategies. ### Key Information - `TelegramError` class documentation - All error codes and their meanings - Specific error scenarios with examples - Auto-retry configuration - Error handling patterns - Recovery strategies ``` -------------------------------- ### Listen to All Telegram Update Types Source: https://github.com/borodin/typescript-telegram-bot-api/blob/main/_autodocs/QUICK_REFERENCE.md Register event listeners for all available Telegram update types. This example shows how to listen for messages, queries, chat events, and more. ```typescript // Message events bot.on('message', (msg) => {}); bot.on('edited_message', (msg) => {}); bot.on('channel_post', (msg) => {}); // Message sub-events (when message has specific content) bot.on('message:text', (msg) => {}); bot.on('message:photo', (msg) => {}); bot.on('message:audio', (msg) => {}); bot.on('message:document', (msg) => {}); bot.on('message:video', (msg) => {}); bot.on('message:location', (msg) => {}); bot.on('message:contact', (msg) => {}); bot.on('message:poll', (msg) => {}); // Query events bot.on('callback_query', (query) => {}); bot.on('inline_query', (query) => {}); bot.on('chosen_inline_result', (result) => {}); // Payment events bot.on('shipping_query', (query) => {}); bot.on('pre_checkout_query', (query) => {}); // Chat events bot.on('my_chat_member', (update) => {}); bot.on('chat_member', (update) => {}); bot.on('chat_join_request', (request) => {}); bot.on('chat_boost', (boost) => {}); // Other bot.on('poll', (poll) => {}); bot.on('poll_answer', (answer) => {}); bot.on('message_reaction', (reaction) => {}); ``` -------------------------------- ### Get User Profile Photos Source: https://github.com/borodin/typescript-telegram-bot-api/blob/main/_autodocs/api_methods.md Retrieve a user's profile pictures. You can specify an `offset` to start from and a `limit` to control the number of photos fetched (1-100). ```typescript const photos = await bot.getUserProfilePhotos({ user_id: 123456, limit: 10, }); ``` -------------------------------- ### Environment Variables for Testing Source: https://github.com/borodin/typescript-telegram-bot-api/blob/main/tests/README.md Create a .env file in the root directory and populate it with these variables for testing purposes. ```bash TEST_TELEGRAM_TOKEN=your_bot_token TEST_USER_ID=your_user_id TEST_GROUP_ID=your_group_id TEST_GROUP_MEMBER_ID=your_group_member_id TEST_CHANNEL_ID=your_channel_id ``` -------------------------------- ### Get User Profile Photos Source: https://github.com/borodin/typescript-telegram-bot-api/blob/main/_autodocs/QUICK_REFERENCE.md Gets a list of profile photos for a specified user. Requires the user ID. ```APIDOC ## Get User Profile Photos ### Description Gets a list of profile photos for a specified user. Requires the user ID. ### Method `bot.getUserProfilePhotos` ### Parameters #### Request Body - **user_id** (number) - Required - Unique identifier of the target user - **offset** (number) - Optional - Sequential number of the first photo to be returned. By default, photos are returned in reverse chronological order. - **limit** (number) - Optional - Limits the number of photos to be retrieved. Values between 1-100. Defaults to 100. ``` -------------------------------- ### Start Long Polling Source: https://github.com/borodin/typescript-telegram-bot-api/blob/main/_autodocs/api_methods.md Starts long polling to receive updates. This method is non-blocking and runs in the background. Call it once at startup; it runs continuously until stopPolling() is called. ```typescript await bot.startPolling(); // Bot will now emit events for incoming updates ``` -------------------------------- ### Running Tests and Linting Source: https://github.com/borodin/typescript-telegram-bot-api/blob/main/tests/README.md Execute these npm commands to run tests, linting, and format checks. ```bash npm test ``` ```bash npm run lint ``` ```bash npm run format:check ``` -------------------------------- ### Get Bot Name Source: https://github.com/borodin/typescript-telegram-bot-api/blob/main/_autodocs/api_methods.md Retrieves the current name of the bot. The name can be language-specific. ```typescript const name = await bot.getMyName(); console.log(name.name); ``` -------------------------------- ### Initialize TelegramBot with Options Source: https://github.com/borodin/typescript-telegram-bot-api/blob/main/_autodocs/TELEGRAM_BOT_API_REFERENCE.md Instantiate the TelegramBot class with your bot token and optional configuration. Supports proxy agents for network requests. ```typescript import { TelegramBot } from 'typescript-telegram-bot-api'; const bot = new TelegramBot({ botToken: 'YOUR_BOT_TOKEN', autoRetry: true, pollingTimeout: 50, }); // With proxy import { HttpsProxyAgent } from 'https-proxy-agent'; const botWithProxy = new TelegramBot({ botToken: 'YOUR_BOT_TOKEN', agent: new HttpsProxyAgent('http://user:pass@proxy:8080'), }); ``` -------------------------------- ### Initialize Telegram Bot Source: https://github.com/borodin/typescript-telegram-bot-api/blob/main/_autodocs/QUICK_REFERENCE.md Import the TelegramBot class and initialize a new bot instance with your bot token. Ensure you replace 'YOUR_TOKEN' with your actual bot token. ```typescript import { TelegramBot } from 'typescript-telegram-bot-api'; const bot = new TelegramBot({ botToken: 'YOUR_TOKEN' }); ``` -------------------------------- ### Accessing Bot Configuration Properties Source: https://github.com/borodin/typescript-telegram-bot-api/blob/main/_autodocs/configuration.md Demonstrates how to read configuration properties after initializing the bot. Properties like botToken, pollingTimeout, and autoRetry are accessible directly. ```typescript const bot = new TelegramBot({ botToken: 'YOUR_TOKEN', pollingTimeout: 30, autoRetry: true, }); // Read properties console.log(bot.botToken); // 'YOUR_TOKEN' console.log(bot.pollingTimeout); // 30 console.log(bot.autoRetry); // true console.log(bot.testEnvironment); // false console.log(bot.baseURL); // 'https://api.telegram.org' console.log(bot.allowedUpdates); // [] console.log(bot.autoRetryLimit); // 0 ``` -------------------------------- ### Get Bot Information Source: https://github.com/borodin/typescript-telegram-bot-api/blob/main/_autodocs/TELEGRAM_BOT_API_REFERENCE.md Fetch basic information about the bot, such as its username and first name. ```typescript const me = await bot.getMe(); console.log(`@${me.username} - ${me.first_name}`); ``` -------------------------------- ### getFile Source: https://github.com/borodin/typescript-telegram-bot-api/blob/main/_autodocs/TELEGRAM_BOT_API_REFERENCE.md Retrieves information about a file and prepares it for download. The download URL can be constructed using the returned `file_path`. ```APIDOC ## GET /getFile ### Description Get file info and prepare for download. ### Method GET ### Endpoint /getFile ### Parameters #### Query Parameters - **file_id** (string) - Required - Identifier for the file to get info about. ### Request Example ```json { "file_id": "file_id_string" } ``` ### Response #### Success Response (200) - **file_path** (string) - The file path to be appended to `https://api.telegram.org/file/bot{token}/` ``` -------------------------------- ### Configure Telegram Bot Instance Source: https://github.com/borodin/typescript-telegram-bot-api/blob/main/_autodocs/QUICK_REFERENCE.md Initialize a new Telegram Bot instance with various configuration options. This includes setting the bot token, environment, API URL, retry behavior, polling timeout, allowed update types, and proxy agent. ```typescript const bot = new TelegramBot({ botToken: 'YOUR_TOKEN', testEnvironment: false, // Use test server baseURL: 'https://api.telegram.org', // Custom API URL autoRetry: true, // Auto-retry on rate limit autoRetryLimit: 30, // Max 30s wait for retry pollingTimeout: 50, // Long polling timeout allowedUpdates: [ 'message', 'callback_query', ], agent: proxyAgent, // HTTP/HTTPS proxy (Node.js) }); ``` -------------------------------- ### Set My Commands Source: https://github.com/borodin/typescript-telegram-bot-api/blob/main/_autodocs/QUICK_REFERENCE.md Sets the list of commands supported by the bot. Requires an array of BotCommand objects. ```APIDOC ## Set My Commands ### Description Sets the list of commands supported by the bot. Requires an array of BotCommand objects. ### Method `bot.setMyCommands` ### Parameters #### Request Body - **commands** (BotCommand[]) - Required - An array of BotCommand objects that describe the commands supported by the bot. - **scope** (BotCommandScope) - Optional - An object, describing the scope of bot commands, for example, the scope of commands for the given chat type. Defaults to BotCommandScopeDefault. - **language_code** (string) - Optional - A localization language code. For example, 'en', 'ru', 'de'. See https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes. Default is 'en'. ``` -------------------------------- ### Get Chat Information Source: https://github.com/borodin/typescript-telegram-bot-api/blob/main/_autodocs/TELEGRAM_BOT_API_REFERENCE.md Retrieve information about a chat, including its title, description, and member count. ```typescript const chat = await bot.getChat({ chat_id: 123 }); console.log(chat.title, chat.description, chat.member_count); ``` -------------------------------- ### Get Sticker Set Source: https://github.com/borodin/typescript-telegram-bot-api/blob/main/_autodocs/QUICK_REFERENCE.md Use this to retrieve information about a sticker set. Requires the set name. ```typescript const set = await bot.getStickerSet({ name: 'set_name' }); ``` -------------------------------- ### getMe Source: https://github.com/borodin/typescript-telegram-bot-api/blob/main/_autodocs/TELEGRAM_BOT_API_REFERENCE.md Fetches basic information about the bot, such as its username and first name. ```APIDOC ## getMe ### Description Get basic bot information. This method returns details about the bot user account. ### Method GET ### Endpoint /getMe ### Response #### Success Response (200) - **User** - An object containing bot information. - **id** (number) - Unique identifier for this bot. - **is_bot** (boolean) - True, if the user is a bot. - **first_name** (string) - Name of the bot. - **username** (string) - Username of the bot. - **can_join_groups** (boolean) - True, if the bot can be invited to groups. - **can_read_all_group_messages** (boolean) - True, if the bot can read all messages in groups. - **supports_inline_queries** (boolean) - True, if the bot supports inline queries. ### Request Example ```typescript const me = await bot.getMe(); console.log(`@${me.username} - ${me.first_name}`); ``` ``` -------------------------------- ### Get Short Bot Description Source: https://github.com/borodin/typescript-telegram-bot-api/blob/main/_autodocs/api_methods.md Retrieves the short description of the bot. This is useful for displaying in limited-space contexts. ```typescript const short = await bot.getMyShortDescription(); ``` -------------------------------- ### Export Chat Invite Link Source: https://github.com/borodin/typescript-telegram-bot-api/blob/main/_autodocs/QUICK_REFERENCE.md Use this to get the primary invite link for a chat. Requires chat_id. ```typescript const link = await bot.exportChatInviteLink({ chat_id: 123 }); ``` -------------------------------- ### Handle Shipping and Pre-Checkout Queries Source: https://github.com/borodin/typescript-telegram-bot-api/blob/main/_autodocs/QUICK_REFERENCE.md Listen for and respond to shipping and pre-checkout queries from users during the payment process. Ensure your bot is configured to handle these events. ```typescript // Answer shipping query bot.on('shipping_query', async (query) => { await bot.answerShippingQuery({ shipping_query_id: query.id, ok: true, shipping_options: [ { id: 'standard', title: 'Standard', price: [{ label: 'Shipping', amount: 1000 }], }, ], }); }); // Answer pre-checkout query bot.on('pre_checkout_query', async (query) => { await bot.answerPreCheckoutQuery({ pre_checkout_query_id: query.id, ok: true, }); }); ``` -------------------------------- ### Telegram Bot Initialization with Environment Variables Source: https://github.com/borodin/typescript-telegram-bot-api/blob/main/_autodocs/configuration.md Configures a Telegram bot using environment variables for the bot token, test environment, polling timeout, and retry settings. Ensures proper parsing for numeric values. ```typescript const bot = new TelegramBot({ botToken: process.env.TELEGRAM_BOT_TOKEN!, testEnvironment: process.env.NODE_ENV === 'development', pollingTimeout: parseInt(process.env.POLLING_TIMEOUT || '50'), autoRetry: true, autoRetryLimit: 30, // Only wait up to 30 seconds }); ``` -------------------------------- ### Get Chat Administrators Source: https://github.com/borodin/typescript-telegram-bot-api/blob/main/_autodocs/api_methods.md Fetches a list of administrators for a given chat. This is useful for moderation or displaying admin roles. ```typescript const admins = await bot.getChatAdministrators({ chat_id: 123 }); ``` -------------------------------- ### Get User Profile Photos Source: https://github.com/borodin/typescript-telegram-bot-api/blob/main/_autodocs/QUICK_REFERENCE.md Use this to retrieve a list of profile photos for a given user. Requires user_id. ```typescript const photos = await bot.getUserProfilePhotos({ user_id: 123 }); ``` -------------------------------- ### FileOptions Class Source: https://github.com/borodin/typescript-telegram-bot-api/blob/main/_autodocs/TELEGRAM_BOT_API_REFERENCE.md Wraps files for sending with custom parameters like filename and MIME type. Use this when you need to provide additional metadata for uploaded files. ```typescript export class FileOptions { constructor( public file: ReadStream | Buffer | File, public options?: FormData.AppendOptions | string ) } ``` ```typescript import fs from 'fs'; // With custom filename and MIME type await bot.sendDocument({ chat_id: 123, document: new FileOptions( fs.readFileSync('document.pdf'), { filename: 'custom.pdf', contentType: 'application/pdf' } ), }); ``` -------------------------------- ### Get Available Gifts Source: https://github.com/borodin/typescript-telegram-bot-api/blob/main/_autodocs/api_methods.md Retrieve a list of available gifts that can be sent to users. Includes sticker information and star cost. ```typescript const gifts = await bot.getAvailableGifts(); gifts.gifts.forEach(gift => { console.log(`${gift.sticker.emoji} - ${gift.star_count} stars`); }); ``` -------------------------------- ### Get Bot Information Source: https://github.com/borodin/typescript-telegram-bot-api/blob/main/_autodocs/api_methods.md Fetches basic information about the bot, such as its username, first name, ID, and whether it can join groups. ```typescript const me = await bot.getMe(); console.log(`@${me.username} - ${me.first_name}`); console.log(`ID: ${me.id}`); console.log(`Can join groups: ${me.can_join_groups}`); ``` -------------------------------- ### Get Star Transactions Source: https://github.com/borodin/typescript-telegram-bot-api/blob/main/_autodocs/TELEGRAM_BOT_API_REFERENCE.md Retrieve a list of Telegram Star transactions. Use this to track payments made with Telegram Stars. ```typescript const transactions = await bot.getStarTransactions({ offset: 0, limit: 100, }); ``` -------------------------------- ### Create New Sticker Set Source: https://github.com/borodin/typescript-telegram-bot-api/blob/main/_autodocs/QUICK_REFERENCE.md Creates a new sticker set. Requires user ID, name, title, and an array of stickers. ```APIDOC ## Create New Sticker Set ### Description Creates a new sticker set. Requires user ID, name, title, and an array of stickers. ### Method `bot.createNewStickerSet` ### Parameters #### Request Body - **user_id** (number) - Required - User identifier of the sticker set owner - **name** (string) - Required - Short name of the sticker set. Should be empty, in which case the name will be built automatically from the user's name and the title. Can contain only 'a-z', '0-9' and '_'. - **title** (string) - Required - Sticker set title, 1-64 characters - **stickers** (InputSticker[]) - Required - A JSON-serialized list of 1-100 stickers to be added to the set. Each object in the list must contain a 'sticker' (InputFile or file_id), 'format' ('static' or 'animated'), and 'emoji_list' (array of strings). ``` -------------------------------- ### setMyShortDescription Source: https://github.com/borodin/typescript-telegram-bot-api/blob/main/_autodocs/api_methods.md Sets the short description of the bot. The short description can be between 0 and 120 characters long. Supports language codes. ```APIDOC ## setMyShortDescription ### Description Sets the short description of the bot. The short description can be between 0 and 120 characters long. Supports language codes. ### Method Not specified (assumed to be a method call in a TypeScript SDK) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - `short_description` (string) - Optional - `language_code` (string) - Optional ### Request Example ```typescript await bot.setMyShortDescription({ short_description: 'Short bot description', }); ``` ### Response #### Success Response (200) - `true` (boolean) - Indicates success #### Response Example ```json true ``` ``` -------------------------------- ### Get Bot Star Balance Source: https://github.com/borodin/typescript-telegram-bot-api/blob/main/_autodocs/api_methods.md Retrieve the bot's current Telegram Stars balance. This is useful for tracking in-app currency. ```typescript const balance = await bot.getMyStarBalance(); console.log(`Stars: ${balance}`); ``` -------------------------------- ### Run Tests Locally Source: https://github.com/borodin/typescript-telegram-bot-api/blob/main/README.md Execute npm test to run the test suite. Alternatively, build a Docker image and run tests within a container. ```bash npm test ``` ```bash docker build -t typescript-bot-api . docker run --rm --env-file .env typescript-bot-api run test ``` -------------------------------- ### Get Chat Member Count Source: https://github.com/borodin/typescript-telegram-bot-api/blob/main/_autodocs/api_methods.md Retrieves the total number of members in a chat. Use this to display the current size of a group or channel. ```typescript const count = await bot.getChatMemberCount({ chat_id: 123 }); console.log(`Members: ${count}`); ``` -------------------------------- ### getMyShortDescription Source: https://github.com/borodin/typescript-telegram-bot-api/blob/main/_autodocs/api_methods.md Retrieves the current short description of the bot. Can be filtered by language code. ```APIDOC ## getMyShortDescription ### Description Retrieves the current short description of the bot. Can be filtered by language code. ### Method Not specified (assumed to be a method call in a TypeScript SDK) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - `language_code` (string) - Optional ### Request Example ```typescript const short = await bot.getMyShortDescription(); ``` ### Response #### Success Response (200) - `BotShortDescription` - An object containing the bot's short description. #### Response Example ```json { "short_description": "Short bot description" } ``` ``` -------------------------------- ### getWebhookInfo(): Promise Source: https://github.com/borodin/typescript-telegram-bot-api/blob/main/_autodocs/api_methods.md Retrieves the current status and configuration of the bot's webhook. ```APIDOC ## getWebhookInfo() ### Description Get webhook status. ### Method `getWebhookInfo` ### Parameters None ### Return `Promise` ### Example ```typescript const info = await bot.getWebhookInfo(); if (info.url) { console.log(`Webhook URL: ${info.url}`); console.log(`Pending updates: ${info.pending_update_count}`); } else { console.log('No webhook set'); } ``` ``` -------------------------------- ### Get Webhook Info Source: https://github.com/borodin/typescript-telegram-bot-api/blob/main/_autodocs/TELEGRAM_BOT_API_REFERENCE.md Retrieve the current status of the bot's webhook integration, including the URL and pending update count. ```typescript const info = await bot.getWebhookInfo(); if (info.url) { console.log(`Webhook: ${info.url}, pending: ${info.pending_update_count}`); } else { console.log('No webhook set (using polling)'); } ``` -------------------------------- ### BotCommand Source: https://github.com/borodin/typescript-telegram-bot-api/blob/main/_autodocs/types.md Represents a bot command that can be sent to the user. Includes the command string and its description. ```APIDOC ## BotCommand ### Description Represents a bot command that can be sent to the user. Includes the command string and its description. ### Type Definition ```typescript type BotCommand = { command: string; description: string; } ``` ``` -------------------------------- ### setWebhook(options) Source: https://github.com/borodin/typescript-telegram-bot-api/blob/main/_autodocs/api_methods.md Configures the bot to receive updates via a webhook. You can specify the HTTPS URL, certificate, and other connection options. ```APIDOC ## setWebhook(options) ### Description Set webhook URL for incoming updates. ### Method `setWebhook` ### Parameters #### Request Body - **url** (string) - Required - HTTPS URL (empty string removes webhook) - **certificate** (InputFile) - Optional - SSL certificate for self-signed - **ip_address** (string) - Optional - Fixed IP instead of DNS - **max_connections** (number) - Optional - Max concurrent connections (1-100, default 40) - **allowed_updates** (UpdateType[]) - Optional - Update types - **drop_pending_updates** (boolean) - Optional - Drop pending updates - **secret_token** (string) - Optional - Secret for webhook requests (1-256 chars) ### Return `Promise` ### Example ```typescript await bot.setWebhook({ url: 'https://example.com/webhook', secret_token: 'my-secret', max_connections: 100, }); ``` ``` -------------------------------- ### Get Custom Emoji Stickers Source: https://github.com/borodin/typescript-telegram-bot-api/blob/main/_autodocs/api_methods.md Fetches sticker objects based on their custom emoji IDs. This is useful for bots that use custom emojis. ```typescript const stickers = await bot.getCustomEmojiStickers({ custom_emoji_ids: ['emoji_id1', 'emoji_id2'], }); ``` -------------------------------- ### Get Specific Chat Member Source: https://github.com/borodin/typescript-telegram-bot-api/blob/main/_autodocs/api_methods.md Fetches information about a particular member within a chat. Allows checking a user's status or details. ```typescript const member = await bot.getChatMember({ chat_id: 123, user_id: 456 }); if (member.status === 'member') { console.log('Regular member'); } ``` -------------------------------- ### Send Photo with Different Sources Source: https://github.com/borodin/typescript-telegram-bot-api/blob/main/README.md Demonstrates sending a photo using various sources: file_id, URL, stream, buffer, FileOptions, and a browser File object. Use FileOptions for custom filenames or content types. ```typescript import { TelegramBot, FileOptions } from 'typescript-telegram-bot-api'; import { createReadStream } from 'fs'; import { readFile } from 'fs/promises'; await bot.sendPhoto({ chat_id: chat_id, photo: 'AgACAgIAAxkDAAIF62Zq43...AgADcwADNQQ', caption: 'file_id', }); // or await bot.sendPhoto({ chat_id: chat_id, photo: 'https://unsplash.it/640/480', caption: 'url', }); // or await bot.sendPhoto({ chat_id: chat_id, photo: createReadStream('photo.jpg'), caption: 'stream', }); // or await bot.sendPhoto({ chat_id: chat_id, photo: await readFile('photo.jpg'), caption: 'buffer', }); // or await bot.sendPhoto({ chat_id: chat_id, photo: new FileOptions( await readFile('photo.jpg'), { filename: 'custom_file_name.jpg', contentType: 'image/jpeg', } ), caption: 'FileOptions', }); // or in browser await bot.sendPhoto({ chat_id: chat_id, photo: input.files[0], // or new File(…) caption: 'file', }); ``` -------------------------------- ### Start and Stop Polling Source: https://github.com/borodin/typescript-telegram-bot-api/blob/main/_autodocs/QUICK_REFERENCE.md Initiate long polling to receive updates from Telegram and stop it when necessary. You can listen for various events like 'message' or 'callback_query'. ```typescript // Start receiving updates await bot.startPolling(); // Listen for events bot.on('message', (msg) => { /* ... */ }); bot.on('callback_query', (query) => { /* ... */ }); // Stop polling await bot.stopPolling(); ``` -------------------------------- ### Validate Bot Token on Startup Source: https://github.com/borodin/typescript-telegram-bot-api/blob/main/_autodocs/configuration.md Validates the bot token by attempting to fetch bot information upon startup. Exits the process if authentication fails. ```typescript const bot = new TelegramBot({ botToken: process.env.BOT_TOKEN || '', }); try { const me = await bot.getMe(); console.log(`Bot authenticated: @${me.username}`); } catch (error) { console.error('Failed to authenticate bot - check BOT_TOKEN'); process.exit(1); } ```