Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

telegram-webhook-js

Package Overview
Dependencies
Maintainers
1
Versions
7
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

telegram-webhook-js

This library provides a simplified interface to interact with the Telegram Bot API, enabling you to create, manage, and operate a Telegram bot. It includes methods to send messages, edit messages, handle updates, send various types of media, manage callba

  • 1.0.51
  • latest
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
6
decreased by-93.68%
Maintainers
1
Weekly downloads
 
Created
Source

Telegram Webhook JS

Overview

This library provides a simplified interface to interact with the Telegram Bot API, enabling you to create, manage, and operate a Telegram bot. It includes methods to send messages, edit messages, handle updates, send various types of media, manage callback queries for inline buttons, and handle menu button keyboards.

Installation

To install this library, you need to have Node.js and npm installed. Then, you can add this library to your project:

npm install telegram-webhook-js

Usage

Importing the Library

First, import the TelegramBot class:

import TelegramBot from 'telegram-webhook-js';

Creating a Bot Instance

Create an instance of the TelegramBot class by passing your bot token:

const bot = new TelegramBot('YOUR_BOT_TOKEN_HERE');

Setting a Webhook

To receive updates via webhook, set the webhook URL:

bot.setWebhook('https://your-webhook-url.com');

To delete the webhook:

bot.deleteWebhook();

Getting Updates

To get updates from Telegram servers:

bot.getUpdates().then((updates) => {
    updates.forEach((update) => {
        bot.handleUpdate(update);
    });
});

Sending Messages

Send a text message to a chat:

bot.sendMessage(chatId, 'Hello, world!', {
    parseMode: 'Markdown',
    disableWebPagePreview: true,
    disableNotification: false,
    replyToMessageId: someMessageId,
    replyMarkup: someReplyMarkup,
});

Editing Messages

Edit an existing message:

bot.editMessageText(chatId, messageId, 'Edited message text', {
    parseMode: 'HTML',
    disableWebPagePreview: true,
    replyMarkup: someReplyMarkup,
});

Deleting Messages

Delete a message:

bot.deleteMessage(chatId, messageId);

Sending Media

Send a photo:

bot.sendPhoto(chatId, photoFile, {
    caption: 'Photo caption',
});

Send a document:

bot.sendDocument(chatId, documentFile, {
    caption: 'Document caption',
});

Send a sticker:

bot.sendSticker(chatId, stickerFile);

Sending Inline Keyboard

Send a message with an inline keyboard:

bot.sendInlineKeyboard(chatId, 'Choose an option:', [
    [{ text: 'Button 1', callbackData: 'button1' }],
    [{ text: 'Button 2', callbackData: 'button2' }],
]);

Handling Callback Queries

Register a callback handler:

bot.onCallback('button1', async (callbackQuery) => {
    await bot.sendMessage(callbackQuery.message.chat.id, 'Button 1 clicked!');
    await bot.answerCallbackQuery(callbackQuery.id);
});

bot.onCallback('button2', async (callbackQuery) => {
    await bot.sendMessage(callbackQuery.message.chat.id, 'Button 2 clicked!');
    await bot.answerCallbackQuery(callbackQuery.id, 'Thank you!', true);
});

Handle updates to process incoming callback queries:

bot.getUpdates().then((updates) => {
    updates.forEach((update) => {
        bot.handleUpdate(update);
    });
});

Answering Callback Queries

Answer a callback query:

bot.answerCallbackQuery(callbackQuery, 'Optional message', true);

Sending Menu Button Keyboard

To send a message with a menu button keyboard (custom keyboard):

bot.sendMessage(chatId, 'Choose an option:', {
    replyMarkup: {
        keyboard: [
            [{ text: 'Option 1' }, { text: 'Option 2' }],
            [{ text: 'Option 3' }],
        ],
        resize_keyboard: true,  // Adjusts the size of the keyboard to fit the buttons
        one_time_keyboard: true, // Hides the keyboard after one use
    },
});

Removing Menu Button Keyboard

To remove the menu button keyboard after it has been displayed:

bot.sendMessage(chatId, 'Keyboard removed', {
    replyMarkup: {
        remove_keyboard: true,
    },
});

Extracting an Image from Updates

To retrieve an image from an update, you can use the following method in your TelegramBot class:

async getImageFromUpdate(update) {
	if (update.message && update.message.photo) {
		// Extract the highest resolution photo
		const photoArray = update.message.photo;
		const fileId = photoArray[photoArray.length - 1].file_id;

		// Get file path
		const fileInfo = await this.getFile(fileId);
		const filePath = fileInfo.file_path;

		// Construct the download URL
		const fileUrl = `https://api.telegram.org/file/bot${this.token}/${filePath}`;
		
		return fileUrl;  // Return the URL to download the image
	} else {
		console.error('No photo found in update.');
		return null;
	}
}

async getFile(fileId) {
	try {
		const response = await fetch(`${this.apiUrl}getFile?file_id=${fileId}`);
		const data = await response.json();
		return data.result;
	} catch (error) {
		console.error('Error getting file:', error);
	}
}

You can use this method to handle image updates in your bot:

const updates = await bot.getUpdates();
for (const update of updates) {
	const imageUrl = await bot.getImageFromUpdate(update);
	if (imageUrl) {
		console.log('Image URL:', imageUrl);
		// You can now download the image or process it further
	}
}

API Reference

TelegramBot

constructor(token)
  • token (string): The bot token provided by the BotFather.
getUpdates(offset = 0)

Fetches updates from the Telegram servers.

  • offset (number, optional): Identifier of the first update to be returned. Defaults to 0.
setWebhook(url)

Sets a webhook URL to receive updates.

  • url (string): The URL to set for receiving updates.
deleteWebhook()

Deletes the webhook.

sendMessage(chatId, text, options = {})

Sends a text message.

  • chatId (number): The chat ID to send the message to.
  • text (string): The message text.
  • options (object, optional): Additional options for the message.
editMessageText(chatId, messageId, text, options = {})

Edits an existing message.

  • chatId (number): The chat ID containing the message.
  • messageId (number): The ID of the message to edit.
  • text (string): The new text for the message.
  • options (object, optional): Additional options for the message.
deleteMessage(chatId, messageId)

Deletes a message.

  • chatId (number): The chat ID containing the message.
  • messageId (number): The ID of the message to delete.
sendPhoto(chatId, photo, options = {})

Sends a photo.

  • chatId (number): The chat ID to send the photo to.
  • photo (File or string): The photo to send.
  • options (object, optional): Additional options for the message.
sendDocument(chatId, document, options = {})

Sends a document.

  • chatId (number): The chat ID to send the document to.
  • document (File or string): The document to send.
  • options (object, optional): Additional options for the message.
sendSticker(chatId, sticker, options = {})

Sends a sticker.

  • chatId (number): The chat ID to send the sticker to.
  • sticker (File or string): The sticker to send.
  • options (object, optional): Additional options for the message.
sendInlineKeyboard(chatId, text, buttons, options = {})

Sends a message with an inline keyboard.

  • chatId (number): The chat ID to send the message to.
  • text (string): The message text.
  • buttons (array): Array of button rows, where each row is an array of button objects.
  • options (object, optional): Additional options for the message.
handleUpdate(update)

Handles an update from the Telegram servers.

  • update (object): The update object.
handleCallbackQuery(callbackQuery, answer = true)

Handles a callback query.

  • callbackQuery (object): The callback query object.
  • answer (boolean, optional): Whether to answer the callback query. Defaults to true.
answerCallbackQuery(callbackQuery, text = undefined, show_alert = false)

Answers a callback query.

  • callbackQuery (object): The callback query object.
  • text (string, optional): Text of the notification. Defaults to undefined.
  • show_alert (boolean, optional): Whether to show an alert. Defaults to false.
onCallback(callbackData, handler)

Registers a callback handler.

  • callbackData (string): The callback data to handle.
  • handler (function): The handler function to execute when the callback data is received.

Keywords

FAQs

Package last updated on 07 Nov 2024

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc