DEV Community

Cover image for How to Build a Telegram Bot in 5 Simple Steps
Esther
Esther

Posted on • Edited on

How to Build a Telegram Bot in 5 Simple Steps

Building a Telegram bot might seem difficult, but it’s easier than you think! Whether you want to create a fun chatbot, an information service, or something unique, Telegram’s API provides a flexible framework for developers of all skill levels. In this guide, we’ll walk through the process step-by-step, so by the end, you'll have a fully functioning bot ready to interact with users.

Before we get started, a little introduction on how it works. Telegram bots are powered by the telegram API: https://api.telegram.org/bot<YOUR_BOT_TOKEN>. The bot is a script that queries this API using an HTTPS request. While you can choose to interact with the API directly, libraries make it easier. This guide will be based on a Python library. You can find the API documentation here. Also, you can find the scripts here: Nodejs, Python

Now, let's start this exciting journey of bringing your bot idea to life in just five simple steps!

1. Create a New Bot & Generate Bot Token

The first step in building a Telegram bot is to create one via the Telegram platform.

  • Open Telegram and search for BotFather, the official Telegram bot for creating and managing bots.
  • Start a chat with the BotFather and use the command /newbot. It will ask you to choose a name for your bot, provide a unique username.
  • Once you’ve successfully created your bot, BotFather will provide a Bot Token— this will serve as the authentication key for your bot. Make sure to store this token securely because you’ll need it later to communicate with Telegram's API.

2. Install Dependencies

Now that you have your bot ready, it's time to set up your development environment. Before you install dependencies, you will need to create a virtual environment where the installed dependencies will reside:

   python -m venv <YOUR-VIRTUAL_ENVIRONMENT-NAME>
Enter fullscreen mode Exit fullscreen mode

Next, you’ll need the Python telegram library installed:

  • Install python-telegram-bot by running this in your terminal:

     pip install python-telegram-bot
    

This library provides an easy way to interact with the Telegram Bot API.

3. Write the Code

With your environment set up, it’s time to write the code for your bot:

   from telegram import Update
   from telegram.ext import ApplicationBuilder, CommandHandler, ContextTypes

   # Function that handles /start command
   def start(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
       update.message.reply_text('Hello! I am your bot. How can I help you today?')

   def main():
       # Use your bot token here
       application = ApplicationBuilder().token(token).build()

       # Register the /start command
       application.add_handler(CommandHandler("start", start))

       # Run the bot until you send a signal to stop
       application.run_polling()

   if __name__ == '__main__':
       main()
Enter fullscreen mode Exit fullscreen mode
  • Replace "token" with the bot token you got from BotFather.
  • The CommandHandler registers the start command and runs the start function each time the command is called.
  • In this simple example, when a user sends the /start command, the bot replies with a greeting.

4. Test the Bot

Now that the code is ready, it’s time to test your bot.

  • Run your bot script in your terminal:

     python bot.py
    
  • Open Telegram, search for your bot using the unique username you created, and send the /start command.

  • The bot should reply with your predefined message: Hello! I am your bot. How can I help you today?

5. Deploy the Bot Code

Now you have a functional bot 🥳. You can build upon this code to add more commands and features depending on the purpose of your bot. Once you’ve tested the bot and are happy with its functionality, it’s time to deploy it so it can run 24/7. There are a few common hosting options such as Heroku, AWS, Azure has a free app service plan.

Ensure the bot is running continuously and can restart automatically if there are errors.

Some Extra Updates That Can Be Made:

  • Perhaps you'd like to show that the bot is typing just like a regular user, add the command below to the start function:
# Send typing action to user - to show that the bot is typing
    await context.bot.send_chat_action(chat_id=update.effective_chat.id, action=ChatAction.TYPING)
Enter fullscreen mode Exit fullscreen mode
  • In the previous example, we saw how to respond to commands (words that start with a / like /start), to respond to normal text messages, we need a message handler:
from telegram.ext import MessageHandler
application.add_handler(MessageHandler(filters.TEXT & ~filters.COMMAND, handle_message))
Enter fullscreen mode Exit fullscreen mode

Have fun building!

Top comments (0)