---
name: test-telegram-bot-token-nodejs
description: Verify Telegram bot token validity and send test messages using Node.js in restricted environments
version: 1.0.0
---
# Test Telegram Bot Token using Node.js

## When to use
You need to verify that a Telegram bot token is valid and optionally send a test message, but you don't have `curl` or `wget` available (e.g., in a restricted Docker container). Node.js is installed.

## Steps
1. **Ensure the token is available as an environment variable or in a `.env` file.**
   - If using a `.env` file, it should contain: `TELEGRAM_BOT_TOKEN=123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11`
   - You can load it via `process.env` or read the file manually.

2. **Validate the token with `getMe`.**
   ```js
   const https = require('https');
   const fs = require('fs');
   const path = require('path');

   function getToken() {
     return process.env.TELEGRAM_BOT_TOKEN ||
       (() => {
         const envPath = path.resolve('.env');
         if (fs.existsSync(envPath)) {
           const content = fs.readFileSync(envPath, 'utf8');
           const match = content.match(/TELEGRAM_BOT_TOKEN=(.*)/);
           return match ? match[1] : null;
         }
         return null;
       })();
   }

   const token = getToken();
   if (!token) {
     console.error('TELEGRAM_BOT_TOKEN not found in environment or .env');
     process.exit(1);
   }

   https.get(`https://api.telegram.org/bot${token}/getMe`, (res) => {
     let data = '';
     res.on('data', chunk => data += chunk);
     res.on('end', () => {
       console.log('getMe response:', data);
     });
   }).on('error', e => {
     console.error('Error calling getMe:', e.message);
   });
   ```

3. **(Optional) Send a test message to a known chat ID.**
   - Replace `CHAT_ID` with the target chat (e.g., your own user ID or a group where the bot is a member).
   - Use `sendMessage` endpoint with proper URL encoding or POST with JSON body.
   ```js
   const chatId = 5838842946; // example admin ID
   const text = encodeURIComponent('Тестовое сообщение: бот работает!');

   https.get(`https://api.telegram.org/bot${token}/sendMessage?chat_id=${chatId}&text=${text}`, (res) => {
     let data = '';
     res.on('data', chunk => data += chunk);
     res.on('end', () => {
       console.log('sendMessage response:', data);
     });
   }).on('error', e => {
     console.error('Error sending message:', e.message);
   });
   ```

   *Alternative using POST (recommended for longer text):*
   ```js
   const data = JSON.stringify({ chat_id: chatId, text: 'Тестовое сообщение: бот работает!' });
   const options = {
     method: 'POST',
     hostname: 'api.telegram.org',
     path: `/bot${token}/sendMessage`,
     headers: {
       'Content-Type': 'application/json',
       'Content-Length': Buffer.byteLength(data)
     }
   };
   const req = https.request(options, (res) => {
     let data = '';
     res.on('data', chunk => data += chunk);
     res.on('end', () => {
       console.log('sendMessage response:', data);
     });
   });
   req.on('error', e => {
     console.error('Error:', e.message);
   });
   req.write(data);
   req.end();
   ```

## Pitfalls
- **Node.js version:** Some environments may have an older Node.js that lacks native `fetch`; use `https` module as shown.
- **Missing `.env`:** If you rely on `dotenv` package, remember it may not be installed; reading the file manually avoids extra dependencies.
- **URL encoding:** When using GET, always `encodeURIComponent` the text parameter; otherwise spaces and special characters break the request.
- **Chat ID:** The bot must be able to message the chat (private chat started by user, or bot added to group with appropriate privacy settings).
- **Rate limits:** Telegram allows up to 30 messages per second; for simple testing this is not an issue.

## Verification
- Successful `getMe` returns `{ ok: true, result: { id, is_bot: true, first_name, username, ... } }`.
- Successful `sendMessage` returns `{ ok: true, result: { message_id, ... } }`.

## Example output
```bash
$ node test_bot.js
getMe response: {"ok":true,"result":{"id":6754661484,"is_bot":true,"first_name":"Sailingmanager","username":"Sailingmanager_bot",...}}
sendMessage response: {"ok":true,"result":{"message_id":470,...}}
```

## How to adapt
- If you need to check webhook info, call `getWebhookInfo`.
- To set/delete webhook, use `setWebhook` or `deleteWebhook`.
- For long‑running validation, wrap the calls in a function and reuse across scripts.