### TelegramServer - Create and Start Server Source: https://context7.com/jehy/telegram-test-api/llms.txt This section explains how to create and start an Express-based HTTP server that emulates the Telegram Bot API. It covers initialization with configuration options and starting the server. ```APIDOC ## TelegramServer - Create and Start Server ### Description Creates an Express-based HTTP server emulating the Telegram Bot API. Initialize with configuration options and start the server to begin accepting bot API requests. ### Method Constructor and `start()` method ### Endpoint N/A (Server is initialized and started programmatically) ### Parameters #### Constructor Parameters - **serverConfig** (object) - Optional - Configuration options for the server. - **port** (number) - Optional - Server port (default: 9000). - **host** (string) - Optional - Server host (default: 'localhost'). - **protocol** (string) - Optional - Protocol (default: 'http'). - **storage** (string) - Optional - Message storage type (default: 'RAM'). - **storeTimeout** (number) - Optional - Seconds to store messages (default: 60). #### Methods - **start()** - Asynchronous - Starts the server. - **stop()** - Asynchronous - Stops the server. ### Request Example ```javascript const TelegramServer = require('telegram-test-api'); // Create server with custom configuration const serverConfig = { port: 9000, host: 'localhost', protocol: 'http', storage: 'RAM', storeTimeout: 60 }; const server = new TelegramServer(serverConfig); // Start the server await server.start(); console.log(`Server running at ${server.config.apiURL}`); // Later, stop the server await server.stop(); ``` ### Response #### Success Response (Server Start) - **apiURL** (string) - The URL at which the server is running. #### Response Example ``` Server running at http://localhost:9000 ``` ``` -------------------------------- ### Install Telegram Test API Source: https://github.com/jehy/telegram-test-api/blob/master/README.md This command installs the 'telegram-test-api' package using npm. This package is a dependency for using the Telegram Test API as a built-in module in a Node.js project. ```bash npm install telegram-test-api ``` -------------------------------- ### Start Telegram Test API Server in Node.js Source: https://github.com/jehy/telegram-test-api/blob/master/README.md This JavaScript code snippet shows how to initialize and start the Telegram Test API server within a Node.js application. It requires the 'telegram-test-api' module and configures the server port. The 'server.start()' method is asynchronous and must be awaited. ```javascript const TelegramServer = require('telegram-test-api'); let serverConfig = {port: 9000}; let server = new TelegramServer(serverConfig); await server.start(); ``` -------------------------------- ### Run Telegram Test API as Standalone Service Source: https://context7.com/jehy/telegram-test-api/llms.txt Instructions for running the Telegram Test API as a standalone HTTP service, allowing testing of bots written in any programming language. This involves cloning the repository, installing dependencies, configuring the service, and starting the server. The output indicates the server is running and ready to accept requests. ```bash # Clone and setup git clone https://github.com/jehy/telegram-test-api.git cd telegram-test-api npm install # Copy and edit configuration cp config/config.sample.json config/config.json # Start server with debug output npm start # Output: TelegramServer:server Telegram API server is up on port 9000 in development mode ``` -------------------------------- ### Create and Start Telegram Test Server Source: https://context7.com/jehy/telegram-test-api/llms.txt Initializes and starts the Telegram Test API server. It can be configured with options like port, host, protocol, message storage type, and storage timeout. The server listens for bot API requests and provides a URL for interaction. ```javascript const TelegramServer = require('telegram-test-api'); // Create server with custom configuration const serverConfig = { port: 9000, // Server port (default: 9000) host: 'localhost', // Server host (default: 'localhost') protocol: 'http', // Protocol (default: 'http') storage: 'RAM', // Message storage type (default: 'RAM') storeTimeout: 60 // Seconds to store messages (default: 60) }; const server = new TelegramServer(serverConfig); // Start the server await server.start(); console.log(`Server running at ${server.config.apiURL}`); // Output: Server running at http://localhost:9000 // Later, stop the server await server.stop(); ``` -------------------------------- ### Interact with Standalone Telegram Test API using cURL Source: https://context7.com/jehy/telegram-test-api/llms.txt Demonstrates how to interact with the standalone Telegram Test API service using cURL commands. It shows examples for sending a message as a bot, sending a message as a user (client API), and retrieving updates as a bot. These examples highlight the HTTP endpoints and expected request/response formats for testing bot functionalities. ```bash # Test with curl - Send message as bot curl -X POST http://localhost:9000/botYOUR_TOKEN/sendMessage \ -H "Content-Type: application/json" \ -d '{"chat_id": 1, "text": "Hello from bot!"}' # Response: {"ok":true,"result":{"chat_id":1,"text":"Hello from bot!","message_id":1,"date":1699...}} # Send message as user (client API) curl -X POST http://localhost:9000/sendMessage \ -H "Content-Type: application/json" \ -d '{"botToken":"YOUR_TOKEN","chat":{"id":1},"from":{"id":1},"text":"/start","date":1699000000}' # Response: {"ok":true,"result":null} # Get updates as bot curl -X POST http://localhost:9000/botYOUR_TOKEN/getUpdates # Response: {"ok":true,"result":[{"update_id":1,"message":{"text":"/start",...}}]} ``` -------------------------------- ### Integration with node-telegram-bot-api Source: https://context7.com/jehy/telegram-test-api/llms.txt A comprehensive example demonstrating how to test a bot developed using the node-telegram-bot-api library with the Telegram Test API. It covers setting up the server, defining bot behavior, and simulating user interactions. ```APIDOC ## Testing node-telegram-bot-api Bots ### Description This section provides a complete example of integrating and testing a bot built with `node-telegram-bot-api` using the `telegram-test-api`. ### Setup 1. Initialize `TelegramServer` and start it. 2. Get a `client` instance for your bot token. 3. Create a `TelegramBot` instance, pointing its `baseApiUrl` to the test server. ### Bot Behavior Definition Use standard `node-telegram-bot-api` methods like `bot.onText` and `bot.sendMessage` to define your bot's responses to commands and messages. ### Testing Scenarios #### Simulating User Input Use `client.sendMessage` to send messages or commands to your bot. #### Waiting for Bot Responses Use `server.waitBotMessage()` to create a promise that resolves when the bot sends a message. #### Verifying Bot Responses Use `client.getUpdates()` to retrieve messages sent by the bot and assert their content. ### Example Snippet ```javascript const TelegramServer = require('telegram-test-api'); const TelegramBot = require('node-telegram-bot-api'); async function testBot() { const server = new TelegramServer({ port: 9012 }); await server.start(); const token = 'testBotToken'; const client = server.getClient(token); const bot = new TelegramBot(token, { polling: true, baseApiUrl: server.config.apiURL }); bot.onText(//start/, (msg) => { bot.sendMessage(msg.chat.id, 'Welcome! Choose an option:', { reply_markup: { keyboard: [[{ text: 'Help' }, { text: 'About' }]] } }); }); // ... other bot logic ... const botWaiter = server.waitBotMessage(); await client.sendMessage(client.makeMessage('/start')); await botWaiter; let updates = await client.getUpdates(); console.log('Response to /start:', updates.result[0].message.text); await bot.stopPolling(); await server.stop(); } testBot(); ``` ``` -------------------------------- ### Integrate and Test node-telegram-bot-api with Telegram Test API (JavaScript) Source: https://context7.com/jehy/telegram-test-api/llms.txt This comprehensive example illustrates how to test a bot built with `node-telegram-bot-api` using `telegram-test-api`. It covers setting up the test server, creating a bot instance that points to the test server, defining bot behavior (handling commands and keyboard inputs), and simulating user interactions to verify responses. ```javascript const TelegramServer = require('telegram-test-api'); const TelegramBot = require('node-telegram-bot-api'); async function testBot() { // Setup server const server = new TelegramServer({ port: 9012 }); await server.start(); const token = 'testBotToken'; const client = server.getClient(token); // Create bot pointing to test server const bot = new TelegramBot(token, { polling: true, baseApiUrl: server.config.apiURL }); // Define bot behavior bot.onText(//start/, (msg) => { bot.sendMessage(msg.chat.id, 'Welcome! Choose an option:', { reply_markup: { keyboard: [[{ text: 'Help' }, { text: 'About' }]] } }); }); bot.onText(/Help/, (msg) => { bot.sendMessage(msg.chat.id, 'Here is some help text.'); }); bot.onText(/About/, (msg) => { bot.sendMessage(msg.chat.id, 'Bot version 1.0.0'); }); // Test 1: Send /start command const botWaiter = server.waitBotMessage(); await client.sendMessage(client.makeMessage('/start')); await botWaiter; let updates = await client.getUpdates(); console.log('Response to /start:', updates.result[0].message.text); // Output: Response to /start: Welcome! Choose an option: // Test 2: Press "Help" keyboard button const helpWaiter = server.waitBotMessage(); await client.sendMessage(client.makeMessage('Help')); await helpWaiter; updates = await client.getUpdates(); console.log('Response to Help:', updates.result[0].message.text); // Output: Response to Help: Here is some help text. // Cleanup await bot.stopPolling(); await server.stop(); } testBot(); ``` -------------------------------- ### Interact with Telegram Test API Client Source: https://github.com/jehy/telegram-test-api/blob/master/README.md This JavaScript code demonstrates how to use the built-in client class provided by the Telegram Test API to emulate user interactions. It shows how to get a client instance, create a message, send it, and retrieve updates from the test server. ```javascript let client = server.getClient(token); let message = client.makeMessage('/start'); client.sendMessage(message); client.getUpdates(); ``` -------------------------------- ### Configure Webhook Support with Telegram Test API (JavaScript) Source: https://context7.com/jehy/telegram-test-api/llms.txt This example shows how to configure and test webhook support using `telegram-test-api` and `node-telegram-bot-api`. It demonstrates setting up a webhook URL, sending messages that are routed to the webhook, and then removing the webhook to revert to polling mode. Messages sent via webhook are not stored by the test server. ```javascript const TelegramServer = require('telegram-test-api'); const TelegramBot = require('node-telegram-bot-api'); const server = new TelegramServer({ port: 9010 }); await server.start(); const client = server.getClient('botToken123'); // Configure bot with webhook const webhookPort = 9011; const webhookUrl = `http://localhost:${webhookPort}/bot${'botToken123'}`; const bot = new TelegramBot('botToken123', { polling: false, webHook: { host: 'localhost', port: webhookPort }, baseApiUrl: server.config.apiURL }); // Set webhook on both bot and server await bot.setWebHook(webhookUrl); server.setWebhook({ url: webhookUrl }, 'botToken123'); // Messages now go directly to webhook (not stored) await client.sendMessage(client.makeMessage('Hello via webhook')); console.log(server.storage.userMessages.length); // Output: 0 (messages sent to webhook, not stored) // Remove webhook to return to polling mode server.deleteWebhook('botToken123'); await client.sendMessage(client.makeMessage('Hello via polling')); console.log(server.storage.userMessages.length); // Output: 1 (message stored since no webhook) await bot.closeWebHook(); await server.stop(); ``` -------------------------------- ### Example Bot Logic with Telegram Test API Source: https://github.com/jehy/telegram-test-api/blob/master/README.md This JavaScript code defines a simple bot class that responds to the '/ping' command. It demonstrates how to use the 'onText' method to capture messages and 'sendMessage' to reply, including options for reply markup. This is intended to be used within a Node.js environment with the Telegram Test API. ```javascript class TestBot { constructor(bot) { bot.onText(//ping/, (msg, match)=> { let chatId = msg.from.id; let opts = { reply_to_message_id: msg.message_id, reply_markup: JSON.stringify({ keyboard: [[{text: 'ok 1'}]], }), }; bot.sendMessage(chatId, 'pong', opts); }); } } ``` -------------------------------- ### Configure Standalone Telegram Test API Service Source: https://context7.com/jehy/telegram-test-api/llms.txt Example JSON configuration file for the standalone Telegram Test API service. This file specifies the protocol (http), host (localhost), port (9000), storage type (RAM), and a store timeout value. This configuration is essential for customizing the behavior of the standalone test server. ```json // config/config.json { "protocol": "http", "host": "localhost", "port": 9000, "storage": "RAM", "storeTimeout": 60 } ``` -------------------------------- ### Await Bot Message Edits with Telegram Test API (JavaScript) Source: https://context7.com/jehy/telegram-test-api/llms.txt This snippet demonstrates how to use `server.waitBotEdits()` to asynchronously wait for a bot to edit a message. It requires the `telegram-test-api` and `node-telegram-bot-api` libraries. The example sends a command, triggers an edit via a callback query, and then verifies the edited message content. ```javascript const TelegramServer = require('telegram-test-api'); const TelegramBot = require('node-telegram-bot-api'); const server = new TelegramServer({ port: 9009 }); await server.start(); const client = server.getClient('botToken123'); const bot = new TelegramBot('botToken123', { polling: true, baseApiUrl: server.config.apiURL }); bot.onText(//start/, (msg) => { bot.sendMessage(msg.chat.id, 'Initial text', { reply_markup: { inline_keyboard: [[{ text: 'Edit', callback_data: 'edit' }]] } }); }); bot.on('callback_query', (query) => { if (query.data === 'edit') { bot.editMessageText('Edited text', { chat_id: query.message.chat.id, message_id: query.message.message_id }); } }); // Send start command and get initial message await client.sendCommand(client.makeCommand('/start')); const updates = await client.getUpdates(); const messageId = updates.result[0].messageId; // Send callback to trigger edit const cb = client.makeCallbackQuery('edit', { message: { message_id: messageId } }); await client.sendCallback(cb); // Wait for edit to complete await server.waitBotEdits(); // Verify edit in history const history = await client.getUpdatesHistory(); const editedMsg = history.find(u => u.messageId === messageId); console.log(editedMsg.message.text); // Output: 'Edited text' await bot.stopPolling(); await server.stop(); ``` -------------------------------- ### Get Complete Message History with client.getUpdatesHistory() Source: https://context7.com/jehy/telegram-test-api/llms.txt Retrieves all messages, both user and bot, without marking them as read. This is useful for testing message deletion and edit operations, providing a complete log of interactions. It requires the TelegramServer and a client instance. ```javascript const TelegramServer = require('telegram-test-api'); const server = new TelegramServer({ port: 9006 }); await server.start(); const client = server.getClient('botToken123'); // Send multiple messages await client.sendMessage(client.makeMessage('Message 1')); await client.sendMessage(client.makeMessage('Message 2')); // Get complete history (doesn't mark as read) const history = await client.getUpdatesHistory(); console.log(history.length); // Output: 2 history.forEach((item) => { console.log({ time: item.time, messageId: item.messageId, updateId: item.updateId, text: item.message.text }); }); // Output: // { time: 1699..., messageId: 1, updateId: 1, text: 'Message 1' } // { time: 1699..., messageId: 2, updateId: 2, text: 'Message 2' } await server.stop(); ``` -------------------------------- ### client.makeCommand() and client.sendCommand() - Send Bot Commands Source: https://context7.com/jehy/telegram-test-api/llms.txt This section explains how to create and send command messages (e.g., /start, /help) with proper `bot_command` entity markup using `client.makeCommand()` and `client.sendCommand()`. ```APIDOC ## client.makeCommand() and client.sendCommand() - Send Bot Commands ### Description Creates and sends a command message (e.g., /start, /help) with proper `bot_command` entity markup. ### Method - `makeCommand(commandText)` - `sendCommand(command)` ### Endpoint N/A (Methods are called on a `TelegramClient` instance) ### Parameters #### Parameters for `makeCommand()` - **commandText** (string) - Required - The command text, including the leading '/'. Arguments can follow the command. #### Parameters for `sendCommand()` - **command** (object) - Required - The command object created by `makeCommand()`. ### Request Example ```javascript const TelegramServer = require('telegram-test-api'); const server = new TelegramServer({ port: 9003 }); await server.start(); const client = server.getClient('botToken123'); // Create a command message const command = client.makeCommand('/start'); console.log(command.entities); // Create command with arguments const commandWithArgs = client.makeCommand('/search query text'); // entities will mark only '/search' as the command // Send the command const response = await client.sendCommand(command); console.log(response); await server.stop(); ``` ### Response #### Success Response (Command Send) - **ok** (boolean) - Indicates if the request was successful. - **result** (any) - The result of the API call (often null for command sending). #### Response Example ```json { "ok": true, "result": null } ``` #### Example Output for `command.entities` ```json [ { "offset": 0, "length": 6, "type": "bot_command" } ] ``` ``` -------------------------------- ### Full Telegram Bot Test Sample in JavaScript Source: https://github.com/jehy/telegram-test-api/blob/master/README.md This JavaScript code snippet demonstrates a comprehensive test case for a Telegram bot. It utilizes 'telegram-test-api' to simulate the Telegram environment and 'node-telegram-bot-api' to interact with the bot. The test involves sending a '/start' command, simulating user interaction with a keyboard response, and verifying the bot's greeting message. ```javascript const TelegramServer = require('telegram-test-api'); const TelegramBot = require('node-telegram-bot-api'); describe('Telegram bot test', () => { let serverConfig = {port: 9001}; const token = 'sampleToken'; let server; let client; beforeEach(() => { server = new TelegramServer(serverConfig); return server.start().then(() => { client = server.getClient(token); }); }); afterEach(function () { this.slow(2000); this.timeout(10000); return server.stop(); }); it('should greet Masha and Sasha', async function testFull() { this.slow(400); this.timeout(800); const message = client.makeMessage('/start'); await client.sendMessage(message); const botOptions = {polling: true, baseApiUrl: server.config.apiURL}; const telegramBot = new TelegramBot(token, botOptions); const testBot = new TestBot(telegramBot); // Assuming TestBot is defined elsewhere const updates = await client.getUpdates(); console.log(`Client received messages: ${JSON.stringify(updates.result)}`); if (updates.result.length !== 1) { throw new Error('updates queue should contain one message!'); } let keyboard = JSON.parse(updates.result[0].message.reply_markup).keyboard; const message2 = client.makeMessage(keyboard[0][0].text); await client.sendMessage(message2); const updates2 = await client.getUpdates(); console.log(`Client received messages: ${JSON.stringify(updates2.result)}`); if (updates2.result.length !== 1) { throw new Error('updates queue should contain one message!'); } if (updates2.result[0].message.text !== 'Hello, Masha!') { throw new Error('Wrong greeting message!'); } return true; }); }); ``` -------------------------------- ### server.getClient() - Create Test Client Source: https://context7.com/jehy/telegram-test-api/llms.txt This section details how to create a `TelegramClient` instance using `server.getClient()`. This client simulates user interactions with the bot, allowing for sending messages, commands, and callback queries. ```APIDOC ## server.getClient() - Create Test Client ### Description Creates a `TelegramClient` instance for simulating user interactions with the bot. The client can send messages, commands, and callback queries as if from a real Telegram user. ### Method `getClient(botToken, userOptions)` ### Endpoint N/A (Client is created programmatically via the server instance) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None #### Parameters for `getClient()` - **botToken** (string) - Required - The token for the bot. - **userOptions** (object) - Optional - Custom user and chat options. - **userId** (number) - Optional - Telegram user ID (default: 1). - **chatId** (number) - Optional - Chat ID (default: 1). - **firstName** (string) - Optional - User's first name (default: 'TestName'). - **userName** (string) - Optional - Username (default: 'testUserName'). - **chatTitle** (string) - Optional - Chat title (default: firstName). - **type** (string) - Optional - Chat type: 'private', 'group', 'supergroup', 'channel' (default: 'private'). - **timeout** (number) - Optional - Max wait time for getUpdates in ms (default: 1000). - **interval** (number) - Optional - Polling interval in ms (default: 100). ### Request Example ```javascript const TelegramServer = require('telegram-test-api'); const server = new TelegramServer({ port: 9001 }); await server.start(); // Create client with default options const client = server.getClient('myBotToken'); // Create client with custom user options const customClient = server.getClient('myBotToken', { userId: 12345, chatId: 67890, firstName: 'John', userName: 'johndoe', chatTitle: 'Test Chat', type: 'private', timeout: 2000, interval: 100 }); await server.stop(); ``` ### Response #### Success Response (Client Creation) - **TelegramClient** (object) - An instance of the TelegramClient. #### Response Example (No direct output, but a `client` object is returned) ``` -------------------------------- ### Send Bot Commands with Telegram Client Source: https://context7.com/jehy/telegram-test-api/llms.txt Enables the creation and sending of bot commands (e.g., /start, /help) to the bot. The `makeCommand` function formats the command with the correct `bot_command` entity markup. The `sendCommand` function then transmits this command to the bot for processing. ```javascript const TelegramServer = require('telegram-test-api'); const server = new TelegramServer({ port: 9003 }); await server.start(); const client = server.getClient('botToken123'); // Create a command message const command = client.makeCommand('/start'); console.log(command.entities); // Output: [{ offset: 0, length: 6, type: 'bot_command' }] // Create command with arguments const commandWithArgs = client.makeCommand('/search query text'); // entities will mark only '/search' as the command // Send the command const response = await client.sendCommand(command); console.log(response); // Output: { ok: true, result: null } await server.stop(); ``` -------------------------------- ### Test Telegraf Bot Integration with Telegram Test API Source: https://context7.com/jehy/telegram-test-api/llms.txt Demonstrates how to test a bot built with the Telegraf framework using the Telegram Test API. It covers setting up the test server, creating a Telegraf bot instance pointing to the test server, defining bot behavior, launching the bot, and simulating user interactions like commands and callback queries. Dependencies include 'telegram-test-api' and 'telegraf'. ```javascript const TelegramServer = require('telegram-test-api'); const { Telegraf } = require('telegraf'); async function testTelegrafBot() { // Setup server const server = new TelegramServer({ port: 9013 }); await server.start(); const token = 'telegrafBotToken'; // Create Telegraf bot pointing to test server const bot = new Telegraf(token, { telegram: { apiRoot: server.config.apiURL } }); // Define bot behavior bot.command('start', (ctx) => ctx.reply('Hi from Telegraf!')); bot.on('callback_query', (ctx) => { ctx.answerCbQuery('Callback received'); ctx.reply('You clicked the button'); }); // Launch bot bot.launch(); // Create test client const client = server.getClient(token, { timeout: 5000 }); // Test /start command const command = client.makeCommand('/start'); await client.sendCommand(command); const updates = await client.getUpdates(); console.log('Bot response:', updates.result[0].message.text); // Output: Bot response: Hi from Telegraf! // Test callback query const callback = client.makeCallbackQuery('button_data'); await client.sendCallback(callback); const callbackUpdates = await client.getUpdates(); console.log('Callback response:', callbackUpdates.result[0].message.text); // Output: Callback response: You clicked the button // Cleanup bot.stop(); await server.stop(); } testTelegrafBot(); ``` -------------------------------- ### Simulate Inline Button Callback with client.makeCallbackQuery() and client.sendCallback() Source: https://context7.com/jehy/telegram-test-api/llms.txt Simulates a user pressing an inline keyboard button by creating and sending a callback query. This is useful for testing how your bot handles button interactions. It requires the TelegramServer and a client instance. ```javascript const TelegramServer = require('telegram-test-api'); const server = new TelegramServer({ port: 9004 }); await server.start(); const client = server.getClient('botToken123'); // Create a callback query const callback = client.makeCallbackQuery('button_action_data'); // Create callback with reference to original message const callbackWithMessage = client.makeCallbackQuery('confirm_order', { message: { message_id: 42, chat: { id: 1 } } }); // Send the callback const response = await client.sendCallback(callback); console.log(response); // Output: { ok: true, result: null } await server.stop(); ``` -------------------------------- ### client.makeMessage() and client.sendMessage() - Send User Messages Source: https://context7.com/jehy/telegram-test-api/llms.txt This section covers creating and sending text messages from a simulated user to the bot using `client.makeMessage()` and `client.sendMessage()`. It details how to construct messages with default or custom options. ```APIDOC ## client.makeMessage() and client.sendMessage() - Send User Messages ### Description Creates and sends a text message from a simulated user to the bot. The message includes all required Telegram message fields. ### Method - `makeMessage(text, messageOptions)` - `sendMessage(message)` ### Endpoint N/A (Methods are called on a `TelegramClient` instance) ### Parameters #### Parameters for `makeMessage()` - **text** (string) - Required - The text content of the message. - **messageOptions** (object) - Optional - Additional options for the message. - **chat** (object) - Optional - Chat details. - **id** (number) - Required - Chat ID. - **type** (string) - Required - Chat type: 'private', 'group', 'supergroup', 'channel'. #### Parameters for `sendMessage()` - **message** (object) - Required - The message object created by `makeMessage()`. ### Request Example ```javascript const TelegramServer = require('telegram-test-api'); const server = new TelegramServer({ port: 9002 }); await server.start(); const client = server.getClient('botToken123'); // Create a simple message const message = client.makeMessage('Hello, bot!'); // Create a message with custom options const customMessage = client.makeMessage('/start', { chat: { id: 999, type: 'group' } }); // Send the message const response = await client.sendMessage(message); console.log(response); await server.stop(); ``` ### Response #### Success Response (Message Send) - **ok** (boolean) - Indicates if the request was successful. - **result** (any) - The result of the API call (often null for message sending). #### Response Example ```json { "ok": true, "result": null } ``` ``` -------------------------------- ### Configure Telegram Test API Server Options Source: https://github.com/jehy/telegram-test-api/blob/master/README.md This JavaScript code demonstrates how to configure the Telegram Test API server with various options. It includes settings for port, host, storage type ('RAM' is the only implemented option), and a timeout for storing messages. These options are passed as a configuration object during server initialization. ```javascript const serverConfig = { "port": 9000, "host": "localhost", "storage": "RAM", "storeTimeout": 60 }; let server = new TelegramServer(serverConfig); ``` -------------------------------- ### Running as Standalone Service Source: https://context7.com/jehy/telegram-test-api/llms.txt Instructions on running the Telegram Test API as a standalone HTTP service for testing bots written in any language. ```APIDOC ## Running as Standalone Service Run the server as a standalone HTTP service for testing bots written in any language. ### Description This section details how to set up and run the Telegram Test API as a standalone service. It includes steps for cloning the repository, installing dependencies, configuring the service, and starting it. It also provides examples of interacting with the standalone service using `curl` for sending messages and retrieving updates. ### Method N/A (Setup and Usage) ### Endpoint N/A (Service Configuration and Interaction) ### Parameters N/A ### Request Example ```bash # Clone and setup git clone https://github.com/jehy/telegram-test-api.git cd telegram-test-api npm install # Copy and edit configuration cp config/config.sample.json config/config.json # Start server with debug output npm start ``` ```json // config/config.json { "protocol": "http", "host": "localhost", "port": 9000, "storage": "RAM", "storeTimeout": 60 } ``` #### Sending messages as bot ```bash curl -X POST http://localhost:9000/botYOUR_TOKEN/sendMessage \ -H "Content-Type: application/json" \ -d '{"chat_id": 1, "text": "Hello from bot!"}' ``` #### Sending messages as user (client API) ```bash curl -X POST http://localhost:9000/sendMessage \ -H "Content-Type: application/json" \ -d '{"botToken":"YOUR_TOKEN","chat":{"id":1},"from":{"id":1},"text":"/start","date":1699000000}' ``` #### Getting updates as bot ```bash curl -X POST http://localhost:9000/botYOUR_TOKEN/getUpdates ``` ### Response #### Success Response (200) **Sending message as bot:** ```json {"ok":true,"result":{"chat_id":1,"text":"Hello from bot!","message_id":1,"date":1699...}} ``` **Sending message as user:** ```json {"ok":true,"result":null} ``` **Getting updates as bot:** ```json {"ok":true,"result":[{"update_id":1,"message":{"text":"/start",...}}]} ``` #### Response Example See above. ``` -------------------------------- ### Integration with Telegraf Source: https://context7.com/jehy/telegram-test-api/llms.txt Demonstrates how to test a bot built with the Telegraf framework using the Telegram Test API. ```APIDOC ## Integration with Telegraf Complete example showing how to test a bot built with Telegraf framework. ### Description This section provides a detailed JavaScript example of setting up and testing a Telegraf bot against the Telegram Test API. It covers bot initialization, defining behavior, launching the bot, and simulating user interactions like commands and callback queries. ### Method N/A (Illustrative Example) ### Endpoint N/A (Illustrative Example) ### Parameters N/A ### Request Example ```javascript const TelegramServer = require('telegram-test-api'); const { Telegraf } = require('telegraf'); async function testTelegrafBot() { // Setup server const server = new TelegramServer({ port: 9013 }); await server.start(); const token = 'telegrafBotToken'; // Create Telegraf bot pointing to test server const bot = new Telegraf(token, { telegram: { apiRoot: server.config.apiURL } }); // Define bot behavior bot.command('start', (ctx) => ctx.reply('Hi from Telegraf!')); bot.on('callback_query', (ctx) => { ctx.answerCbQuery('Callback received'); ctx.reply('You clicked the button'); }); // Launch bot bot.launch(); // Create test client const client = server.getClient(token, { timeout: 5000 }); // Test /start command const command = client.makeCommand('/start'); await client.sendCommand(command); const updates = await client.getUpdates(); console.log('Bot response:', updates.result[0].message.text); // Test callback query const callback = client.makeCallbackQuery('button_data'); await client.sendCallback(callback); const callbackUpdates = await client.getUpdates(); console.log('Callback response:', callbackUpdates.result[0].message.text); // Cleanup bot.stop(); await server.stop(); } testTelegrafBot(); ``` ### Response N/A (Illustrative Example) #### Success Response (200) N/A #### Response Example N/A ``` -------------------------------- ### Create Telegram Test Client Source: https://context7.com/jehy/telegram-test-api/llms.txt Generates a TelegramClient instance to simulate user interactions with the bot. The client can be created with default options or custom user details such as user ID, chat ID, name, and chat type. This client is essential for sending messages and commands to the emulated bot. ```javascript const TelegramServer = require('telegram-test-api'); const server = new TelegramServer({ port: 9001 }); await server.start(); // Create client with default options const client = server.getClient('myBotToken'); // Create client with custom user options const customClient = server.getClient('myBotToken', { userId: 12345, // Telegram user ID (default: 1) chatId: 67890, // Chat ID (default: 1) firstName: 'John', // User's first name (default: 'TestName') userName: 'johndoe', // Username (default: 'testUserName') chatTitle: 'Test Chat', // Chat title (default: firstName) type: 'private', // Chat type: 'private', 'group', 'supergroup', 'channel' timeout: 2000, // Max wait time for getUpdates in ms (default: 1000) interval: 100 // Polling interval in ms (default: 100) }); await server.stop(); ``` -------------------------------- ### Configure Bot with Custom Telegram API URL Source: https://github.com/jehy/telegram-test-api/blob/master/README.md This JavaScript code shows how to configure a 'node-telegram-bot-api' instance to use the local Telegram Test API server. By setting the 'baseApiUrl' option to the server's API URL, all bot interactions will be directed to the emulator instead of the actual Telegram servers. ```javascript const TelegramBot = require('node-telegram-bot-api'); let botOptions = {polling: true, baseApiUrl: server.config.apiURL}; telegramBot = new TelegramBot(token, botOptions); ``` -------------------------------- ### Await User Message with server.waitUserMessage() Source: https://context7.com/jehy/telegram-test-api/llms.txt Returns a promise that resolves when a user sends a message, command, or callback query. This is useful for testing scenarios where the bot needs to react to incoming user input. It requires the TelegramServer and a client instance. ```javascript const TelegramServer = require('telegram-test-api'); const server = new TelegramServer({ port: 9008 }); await server.start(); const client = server.getClient('botToken123'); // Start waiting before sending setTimeout(async () => { await client.sendCommand(client.makeCommand('/start')); }, 100); // Wait for user message await server.waitUserMessage(); // Check that message arrived const history = await client.getUpdatesHistory(); console.log(history.length); // Output: 1 await server.stop(); ``` -------------------------------- ### Webhook Support - setWebhook and deleteWebhook Source: https://context7.com/jehy/telegram-test-api/llms.txt Configure webhook mode for your bot. Messages will be sent directly to the specified webhook URL instead of being stored by the test server. This section covers setting and deleting webhooks. ```APIDOC ## Webhook Management ### Description Manages webhook configuration for the test Telegram server, allowing bots to receive updates directly via HTTP POST requests. ### Methods #### POST /server/setWebhook ##### Description Configures a webhook URL for a specific bot token. ##### Endpoint /server/setWebhook ##### Parameters - **body** (object) - Required - Webhook configuration. - **url** (string) - Required - The URL to send updates to. - **certificate** (string) - Optional - Public key file for the HTTPS certificate. - **max_connections** (number) - Optional - Maximum allowed number of simultaneous HTTPS connections. - **allowed_updates** (array) - Optional - List of update types to send. ##### Request Example ```json { "url": "https://your-domain.com/webhook", "max_connections": 40 } ``` #### DELETE /server/deleteWebhook ##### Description Removes the webhook configuration for a specific bot token, returning the bot to polling mode. ##### Endpoint /server/deleteWebhook ##### Parameters - **botToken** (string) - Required - The token of the bot whose webhook should be deleted. ##### Request Example ```json { "botToken": "botToken123" } ``` ### Response #### Success Response (200) - **ok** (boolean) - Indicates the success of the operation. #### Response Example ```json { "ok": true } ``` ``` -------------------------------- ### Retrieve Bot Responses with client.getUpdates() Source: https://context7.com/jehy/telegram-test-api/llms.txt Polls the server for messages sent by the bot, waiting until updates are available or a timeout is reached. This method is essential for verifying bot replies in tests. It requires the TelegramServer, a client instance, and a configured TelegramBot. ```javascript const TelegramServer = require('telegram-test-api'); const TelegramBot = require('node-telegram-bot-api'); const server = new TelegramServer({ port: 9005 }); await server.start(); const client = server.getClient('botToken123'); // Set up a bot that responds to /start const bot = new TelegramBot('botToken123', { polling: true, baseApiUrl: server.config.apiURL }); bot.onText(//start/, (msg) => { bot.sendMessage(msg.chat.id, 'Welcome!', { reply_markup: { keyboard: [[{ text: 'Option A' }, { text: 'Option B' }]] } }); }); // Send command and get bot's response await client.sendMessage(client.makeMessage('/start')); const updates = await client.getUpdates(); console.log(updates); // Output: { // ok: true, // result: [{ // updateId: 2, // messageId: 2, // message: { // text: 'Welcome!', // chat_id: 1, // reply_markup: { keyboard: [[{ text: 'Option A' }, { text: 'Option B' }]] } // } // }] // } await bot.stopPolling(); await server.stop(); ``` -------------------------------- ### Send User Messages with Telegram Client Source: https://context7.com/jehy/telegram-test-api/llms.txt Allows the creation and sending of text messages from a simulated user to the bot using the TelegramClient. The `makeMessage` function constructs the message object, which can include custom options for the chat. The `sendMessage` function then sends this message to the bot. ```javascript const TelegramServer = require('telegram-test-api'); const server = new TelegramServer({ port: 9002 }); await server.start(); const client = server.getClient('botToken123'); // Create a simple message const message = client.makeMessage('Hello, bot!'); // Create a message with custom options const customMessage = client.makeMessage('/start', { chat: { id: 999, type: 'group' } }); // Send the message const response = await client.sendMessage(message); console.log(response); // Output: { ok: true, result: null } await server.stop(); ``` -------------------------------- ### Await Bot Response with server.waitBotMessage() Source: https://context7.com/jehy/telegram-test-api/llms.txt Returns a promise that resolves when the bot sends a message, allowing for synchronization in tests. This is particularly useful for ensuring that a bot's response is received before proceeding with further assertions. It requires the TelegramServer and a configured TelegramBot. ```javascript const TelegramServer = require('telegram-test-api'); const TelegramBot = require('node-telegram-bot-api'); const server = new TelegramServer({ port: 9007 }); await server.start(); const client = server.getClient('botToken123'); const bot = new TelegramBot('botToken123', { polling: true, baseApiUrl: server.config.apiURL }); bot.onText(//hello/, (msg) => { bot.sendMessage(msg.chat.id, 'Hello there!'); }); // Set up waiter before sending message const botResponsePromise = server.waitBotMessage(); // Send user message await client.sendMessage(client.makeMessage('/hello')); // Wait for bot to respond await botResponsePromise; // Now safely check storage console.log(server.storage.botMessages.length); // Output: 1 await bot.stopPolling(); await server.stop(); ``` -------------------------------- ### Stop Telegram Test API Server in Node.js Source: https://github.com/jehy/telegram-test-api/blob/master/README.md This JavaScript code snippet shows how to gracefully stop the Telegram Test API server when used as a built-in module in Node.js. The 'server.stop()' method is asynchronous and should be awaited. ```javascript await server.stop(); ``` -------------------------------- ### server.waitBotEdits() - Await Message Edits Source: https://context7.com/jehy/telegram-test-api/llms.txt This method returns a promise that resolves when the bot edits a message's text or reply markup. It's useful for testing scenarios where bot messages are updated. ```APIDOC ## POST /server/waitBotEdits ### Description Waits for the bot to edit a message's text or reply markup. ### Method POST ### Endpoint /server/waitBotEdits ### Parameters #### Query Parameters - **timeout** (number) - Optional - The maximum time in milliseconds to wait for the edit. ### Request Example ```json { "timeout": 5000 } ``` ### Response #### Success Response (200) - **success** (boolean) - Indicates if the edit was detected within the timeout. #### Response Example ```json { "success": true } ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.