Building a Telegram Bot using Python

Hey there! In this tutorial, we will be learning to create a simple Telegram Bot in PyCharm using Python.

Telegram Bots are simply Telegram accounts operated by software. Building them is fairly simple and they can be integrated into Telegram groups and channels as well.

Below attached are the basic steps to create a bot that can provide users with the current date and time.

Steps

    1. Open the Telegram app on any device and then search for @BotFather. BotFather is a bot that helps in creating new bots and changing the settings for existing ones.
      Type /newbot. In response to the message received, enter a name for your bot followed by a username. Upon valid entry, you will receive an API Key. Note down the same for future use.

      BotFather

    2. Open PyCharm and create a project titled Telegram_Bot.
      python-telegram-bot
      is a library that provides a pure Python interface for the Telegram bot API and is compatible with Python versions 3.6+. To install the same, open the terminal and type the command:

      $ pip install python-telegram-bot
    3. Create a python file titled Responses.py within the Telegram_Bot project. Within this file, specify the messages to be provided as a response by the bot, to the user’s input messages.
      from datetime import datetime
      import pytz
      
      
      def sample_responses(user_input):
          input_text = str(user_input).lower()
      
          if input_text in ["/start", "hi", "hi!", "hello", "hey"]:
              return "Hey! I'm Alpha. Do you want to know the time or today's date?"
      
          if input_text in ["time", "time?"]:
              return "Do you want to know the time in India, England or United States?"
      
          if input_text == "india":
              time_zone = pytz.timezone('Asia/Kolkata')
              now = datetime.now(time_zone)
              return "Time -  " + now.strftime('%H : %M : %S')
          if input_text == "england":
              time_zone = pytz.timezone('Europe/London')
              now = datetime.now(time_zone)
              return "Time -  " + now.strftime('%H : %M : %S')
          if input_text in ["united states", "us"]:
              time_zone = pytz.timezone('America/New_York')
              now = datetime.now(time_zone)
              return "Time -  " + now.strftime('%H : %M : %S')
      
          if input_text in ["date", "date?"]:
              date = datetime.now()
              return date.strftime('%d - %B - %Y')
      
          if input_text in ["bye", "ttyl", "good bye"]:
              return "It was nice chatting with you. Bye!"
      
          return "Sorry,I didn't understand you"
    4. Create another python file titled main.py within the same project and type the below-specified code.
      Here, the handle_messages method receives the user input and converts it into a string. It then passes this string to the sample_responses method, specified within the Responses.py file, and then displays the corresponding response returned as a reply to the user.
      Refer to telegram.ext documentation for a detailed description of various methods and parameters used.

      from telegram.ext import *
      
      import Responses as R
      
      def handle_messages(update,context):
          text = str(update.message.text)
          response = R.sample_responses(text)
          update.message.reply_text(response)
      
      updater = Updater('1798618640:AAEhpRkF9subG0pbMKoNu1ijT-Xj_eh10AM')
      d = updater.dispatcher
      d.add_handler(MessageHandler(Filters.text, handle_messages))
      updater.start_polling()
      updater.idle()
    5. Within the Telegram app, search for your bot using its name/ username and start your conversation.

Sample Output

The image below showing how the sample output will looks like:

message conversation

Additional Information

In order to modify your bot, begin a conversation with @BotFather by sending the message: /help. By clicking on suitable options in the message received, you can change the bot’s name, add a display photo, specify a description for the bot, delete the bot, etc.
Example:

 

You may also learn,

One response to “Building a Telegram Bot using Python”

  1. Joachim says:

    Great tutorial! How you go about making a Telegram chatbot with the GPT-3 API?

Leave a Reply

Your email address will not be published. Required fields are marked *