Sending Telegram Messages/Photos in NodeJS using Fetch

Hossein MarganiHossein Margani
2 min read

This blog post provides a basic guide on how to send Telegram messages and photos from a Node.js application using the node-fetch library. We'll focus on a simple, straightforward approach, perfect for beginners getting started with Telegram bot development.

First, you'll need to install the node-fetch library: npm install node-fetch. Then, you will need a Telegram Bot token, which you can obtain from BotFather on Telegram. This token will be used to authenticate your bot's requests to the Telegram API.

Here's an example of sending a simple text message:

const fetch = require('node-fetch');

async function sendMessage(chatId, text, botToken) {
    const response = await fetch(`https://api.telegram.org/bot${botToken}/sendMessage`, {
        method: 'POST',
        headers: {
        'Content-Type': 'application/json'
        },
        body: JSON.stringify({ chat_id: chatId, text: text })
    });
    const data = await response.json();
    console.log(data);
}

// Example usage:
const chatId = '-123456789'; // Replace with your chat ID
const botToken = 'YOUR_BOT_TOKEN'; // Replace with your bot token
const message = 'Hello from Node.js!';
sendMessage(chatId, message, botToken);

Sending photos requires a slightly different approach. You'll need to send a multipart/form-data request containing the photo's data:

// ... other code ...
async function sendPhoto(chatId, photoPath, botToken) {
    const formData = new FormData();
    formData.append('chat_id', chatId);
    formData.append('photo', fs.createReadStream(photoPath));
    const response = await fetch(`https://api.telegram.org/bot${botToken}/sendPhoto`, {
        method: 'POST',
        body: formData
    });
// ... handling the response ...
}

This functionality can be used in various applications, such as creating chatbots for customer service, automated alerts, or personal task management systems.

For more advanced features and detailed information about the Telegram Bot API, refer to the official Telegram Bot API documentation. You may also want to consider using libraries built on top of the fetch API for more robust error handling and other advanced features.

0
Subscribe to my newsletter

Read articles from Hossein Margani directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Hossein Margani
Hossein Margani