npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

telegram-webhook-js

v1.0.4

Published

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

Downloads

219

Readme

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.