Node.js Telegram Bot API send an image with text

To send an image with text using the Telegram Bot API in Node.js, you can use the node-fetch library to make HTTP requests and the FormData module to handle multipart/form-data requests for uploading images. First, install the required modules:

npm install node-fetch

Here's an example code snippet to send an image with text using the Telegram Bot API:

const fetch = require('node-fetch');
const FormData = require('form-data');

const BOT_TOKEN = 'YOUR_TELEGRAM_BOT_TOKEN';
const CHAT_ID = 'TARGET_CHAT_ID';

async function sendImageWithText() {
  const photoUrl = 'URL_TO_YOUR_IMAGE'; // Replace with the URL of your image

  const form = new FormData();
  form.append('chat_id', CHAT_ID);
  form.append('photo', photoUrl);
  form.append('caption', 'Your text caption goes here');

  try {
    const response = await fetch(`https://api.telegram.org/bot${BOT_TOKEN}/sendPhoto`, {
      method: 'POST',
      body: form,
      headers: form.getHeaders(),
    });

    const responseData = await response.json();
    console.log(responseData);

    if (responseData.ok) {
      console.log('Image sent successfully!');
    } else {
      console.error('Failed to send image:', responseData.description);
    }
  } catch (error) {
    console.error('Error sending image:', error.message);
  }
}

sendImageWithText();

Make sure to replace 'YOUR_TELEGRAM_BOT_TOKEN' and 'TARGET_CHAT_ID' with your actual Telegram bot token and the chat ID where you want to send the image. Also, replace 'URL_TO_YOUR_IMAGE' with the actual URL of the image you want to send.

Note: This example assumes that you have a direct URL to the image. If you have the image as a file on your server, you may need to use a different approach to upload the file. Adjust the code accordingly based on your specific use case.

Komentar

Postingan populer dari blog ini

WhatsApp Web login QR code in an HTML page using whatsapp-web.js

Add these security headers to your website