Node Telegram Bot API Development and Deployment Guide

Author

Reads 529

Close-up of hands typing on a digital tablet with messaging app in bed.
Credit: pexels.com, Close-up of hands typing on a digital tablet with messaging app in bed.

Creating a node Telegram bot is a straightforward process that involves setting up a Node.js project, installing the Telegram Bot API library, and defining the bot's functionality.

To start, you'll need to create a new Node.js project using npm init. Then, install the telegram-bot library using npm install telegram-bot.

The bot's functionality is defined in a JavaScript file, where you'll use the library to create a bot instance and define its behavior.

Bot Configuration

To configure your Node Telegram Bot API, you need to initialize it with your Telegram token, which you received from Bot Father. This token is essential for the bot to function properly.

You'll also need to set up a way to save user chat IDs to a database, like MongoDB, to send messages without requiring user input. This can be done using CRUD methods with a framework like Express.

The Telegram Bot API has two main methods: `bot.sendMessage` and `bot.on`. The `bot.on` method allows you to react to specific events, such as the `/start` command, by checking if the received text matches your command and responding with a message.

Commands

Credit: youtube.com, The Best Streamer.bot Commands and Actions for YOUR Stream

Commands are a crucial part of bot configuration, allowing users to interact with your bot in a meaningful way.

To send a user a message describing the use of your bot, you can create a command that responds to the "/start" command. This is a common practice that helps users understand how to use your bot.

You can also create custom commands to perform specific actions, such as sending pictures or audios. For example, you can create a command called "/sendpic" that sends a picture to the user.

Sending audios is just as simple, and you can use the "sendAudio" method to achieve this.

If you want to add a caption to a picture, you can use the "sendPhoto" method with an option to include a caption. This is useful for creating visually appealing messages that include text.

Here are some examples of commands that you can create:

  • /start: sends a message describing the use of your bot
  • /sendpic: sends a picture to the user
  • /sendaudio: sends an audio file to the user

Remember to declare your handlers before starting the bot, otherwise they won't be registered and won't work.

Session

Credit: youtube.com, Bot Sessions allow bot and user to work together giving the bot its own session | Picture-in-Picture

Session is like local storage in web but for telegram bots, allowing you to save params that you need to save and use them in the future.

To set up session, you need to import it from telegraf and make a session middleware, which you can then use in your scenes.

You can use session to store chat IDs, but it's not recommended to store them directly in the code, so you'll need to use a database like MongoDB or a session like node-telegram-bot-api to store them.

To store chat IDs, you need to save them when a user registers, which is typically when they send their first message in a chat. You can access the chat ID using msg.chat.id.

If you're new to MongoDB, you can check out tutorials on YouTube, preferably in English, as they tend to have higher quality content.

Message Handling

To handle messages in your node telegram bot, you need to create a node project and install bot-api. Create a file index.js, or any other name, and inside the file, require node-telegram-bot-api.

You'll also need to assign your token, which you got from BotFather, to the bot. This token is required to authenticate and authorize your bot's actions.

See what others are reading: Onedrive Api Upload File

Parse Mode

Credit: youtube.com, Learn About Parsing - What is it and Why Do You Need It?

Parse Mode is a crucial aspect of sending messages with style in Telegram. You can define it inside your options when sending a message.

The available options for parse mode are HTML and Markdown. You can choose to render your message in either of these formats.

To use HTML, you can define it in your options like so. You can also use Markdown for a more readable format.

In Markdown, you can only use certain tags, as mentioned in the official Telegram API. These tags are supported for now.

You can use HTML or Markdown to add some flair to your messages and make them stand out.

Location and Number

Handling user location and phone numbers in message handling is a breeze with the right methods. You can send users' locations using some enabled methods.

To send a venue, you can use sendVenue. This method allows you to share the location of a specific venue with the user. I've used this feature to send a friend the location of a new restaurant in town.

To send a phone number, you can use sendContact. This method is straightforward and easy to use.

Working With Files

People working remotely in a modern café, using laptops and phones for business tasks.
Credit: pexels.com, People working remotely in a modern café, using laptops and phones for business tasks.

Working with files can be a breeze, especially when you know the supported file sources. You can use existing file_id, file path, URL, buffer, or ReadStream.

When sending a file, you can also provide an optional name for it, which is known as the filename. This can be especially helpful for organizing your files and making them easier to identify.

To send a file, you can choose from one of the following supported file sources:

  • Existing file_id
  • File path
  • Url
  • Buffer
  • ReadStream

Just remember to include the filename if you want to give your file a specific name. This will help keep your files organized and make them easier to manage.

Interacting with Telegram

Interacting with Telegram is a powerful feature of the Node Telegram Bot API. You can use bots to manage groups by receiving users' messages and sending group messages.

Bots can be added to groups, but they need to be set as administrators to access users' messages. This is due to Telegram's privacy policy.

To interact with groups, you can use methods like kickChatMember to remove a member if they say a specific word, such as "idiot". This method receives the id of the chat and the id of the user to remove.

User

Credit: youtube.com, Interacting with Telegram Chatbot using WeatherAPI

Interacting with Telegram can be a breeze once you know the ropes. To get started, you can use the getUser function to retrieve information about a user.

You can also get user profile pictures using the getUserProfilePhotos method. This is especially useful for creating personalized experiences in your bot.

To get a user's profile, you can use the getUser function. This will return a User object that contains all the relevant information about the user.

If you want to get user profile pictures, you can use getUserProfilePhotos. This will return an array of photos that the user has uploaded.

Interacting with Groups and Channels

To interact with groups and channels on Telegram, you can use bots to manage messages and send keyboards to members. Bots can receive users' messages and send group messages if added as an administrator.

You can create a bot that sends a message to group members, such as "Have a nice day Username" when a member says something containing the "Bye" keyword. This is done by setting the bot as an administrator of the group.

Credit: youtube.com, ~ How to Create Engaging Polls in Telegram? Boost Your Group Interaction!

To access users' messages, the bot must be added as an administrator of the group, as Telegram's privacy policy restricts bots from accessing users' messages otherwise. This is a necessary step to enable the bot to receive and respond to users' messages.

You can also use bots to remove members from a group if they say a specific word, such as "idiot". This is achieved by using the kickChatMember method, which requires the id of the chat and the user to be removed.

Adding a bot as an administrator is a crucial step to enable it to access users' messages and perform actions such as removing members from a group.

Error Handling and Deployment

Error handling is crucial when building a node Telegram bot API. Middleware can throw an error or time out, triggering bot.handleError to be called.

If middleware throws an error, the bot will either rethrow it, causing the update source to close, or swallow it, leaving the process in an invalid state. Swallowing unknown errors is not recommended in production.

In production, you can use systemd or pm2 to restart your bot if it exits for any reason.

Error Handling

Credit: youtube.com, Make.com Error Handling Quick Reference Guide - How to Handle Errors

Error handling is crucial in any application, and Telegraf is no exception. Middleware can throw errors or time out, triggering the bot's handleError function.

If middleware throws an error, Telegraf calls bot.handleError. This function rethrows the error by default.

You can prevent the process from terminating by overwriting bot.handleError with bot.catch. However, be aware that swallowing unknown errors might leave the process in an invalid state.

Systemd or pm2 can restart your bot if it exits for any reason, including errors. This is a convenient feature for production environments.

Add Deployment Information

To deploy your Node.js app on Heroku, you need to add some essential configuration information. Heroku requires you to specify the Node and npm versions in the package.json file. Add an engines object with node and npm keys and their respective versions.

Heroku looks for specific scripts in the package.json file, including a build script that outlines the steps to build your project, and a start script that it uses to boot your app. You can configure these scripts to meet your project's needs.

For your interest: Nextjs File Upload Api

Credit: youtube.com, When Should Error Handling Be Tested During Development? | Learn To Troubleshoot News

Heroku also looks for a Procfile in the root of your project, which configures the deployment steps. You can read about how it works and how to configure it on the Procfile documentation. Add a Procfile with the following content to specify that your application is a worker dyno and how to start it.

Here are the scripts Heroku looks for in the package.json file:

  • build script: lets you specify the steps to build your project
  • start script: Heroku uses it to boot your app

You can read more about these steps and how to configure your Procfile on the Deploying Node.js Apps on Heroku documentation.

Advanced Topics

In the Node Telegram Bot API, you can use the polling strategy to handle incoming updates, which involves making a GET request to the Bot API's webhook endpoint at a specified interval to check for new updates.

The polling strategy is a good option for small-scale bots, but it can be inefficient for large-scale bots, as it requires making multiple requests to the server.

Credit: youtube.com, NodeJS : Node Telegram bot api, make chain conversation between user

To handle incoming updates, you can also use the webhook strategy, which involves setting up a webhook endpoint on your server to receive updates from the Bot API.

You can use the `getUpdates` method to retrieve a list of all updates that the Bot API has stored for your bot.

The Bot API will store updates for up to 24 hours, and you can use the `deleteWebhook` method to remove the webhook endpoint and switch back to the polling strategy.

To send messages to a user, you can use the `sendMessage` method, which takes a `chat_id` parameter to specify the user to send the message to.

You can also use the `sendPhoto` method to send a photo to a user, which takes a `chat_id` parameter and a `photo` parameter to specify the photo to send.

The Bot API supports sending files of various types, including photos, videos, audio files, and documents.

You can use the `getFile` method to retrieve the file path of a file that you've sent to a user.

A unique perspective: Aws Upload File to S3 Api Gateway

Tools and Frameworks

Credit: youtube.com, Creating a telegram bot using Node JS

Telegraf is a well-documented and widely-used library for developing bots using Node.js, making it easier to interact with APIs than sending HTTP requests.

You can find Telegraf and other libraries for Node.js and other languages on the Telegram page.

To install Telegraf as a dependency, use the command.

Telegraf has similar methods to node-telegram-bot-api, including initializing with new Telegraf(token) and reacting to the /start command with bot.start.

The ctx object in Telegraf has many methods, including ctx.reply for sending response messages, and ctx.replyWithHTML, ctx.replyWithAudio, and ctx.replyWithPhoto for sending messages with HTML, audio, or photos.

The bot.on function is the same as in node-telegram-bot-api, and all its parameters can be seen in the previous link.

The bot.hears function reacts to user's messages, and to launch the bot, use bot.launch().

Development Environment

I'm using a Linux Mint 20.2 computer to write this bot, paired with Visual Studio Code 1.61.2.

The project relies on a specific set of dependencies, which can be installed later. Here are the dependencies we'll be using:

  • Node.js: 17.0.1
  • npm: 8.1.0
  • typescript: 4.4.4
  • telegraf: 4.4.2
  • @types/node: 16.11.2
  • eslint: 8.1.0

Willie Walsh

Junior Assigning Editor

Willie Walsh is an accomplished Assigning Editor with a keen eye for detail and a passion for delivering high-quality content. With a strong background in research and editing, Willie has honed their skills in identifying and assigning relevant topics to writers. Willie's expertise spans a wide range of categories, including technology, productivity, and education.

Love What You Read? Stay Updated!

Join our community for insights, tips, and more.