Creating a Python Telegram Bot

Python Telegram Bot

While visiting any modern webpage these days, most likely we will see an automated chatbot that pops up on the screen with some kind of information about the website and its services. We can type into the chat application to make our queries and get replies as if we are talking to a real person from the other side.

These bots that we interact with are generally powered by some AI applications that try to mimic human-like behaviour. The replies that we receive from them are customized as per the services provided by the website. They are usually designed to provide first-hand information to the person making inquiries and try to resolve the most common issues of a person.

They are deployed on some cloud services which makes them available at all times. They are a thing in almost every company that we know of.

Some well-known e-commerce companies use them to resolve customer issues using an automated bot. Other examples include booking appointments with medical professionals or getting information about some online courses that a person is interested in. If an automated bot is unable to resolve our issues, it gets us connected to a person in the customer services of that company.

Creating a Bot using Python for Telegram Messenger

Bots can also be implemented on chat messaging services. In this article, we will code up a bot using Python on the Telegram Messenger application. We will use some of the basic commands and see our bot in action. So, let’s get started.

STEP – 1: Installing the Telegram application to our smartphone and workstation

First, we need to download the telegram app to our smartphones from the Google Play Store or the Apple Store. The app needs to be authenticated using our contact number. After setting up the application on our phones, we need to download the telegram app to our workstation and connect the phone’s application to it by providing access rights to our desktop application to use the same credentials.

Also read: Python PIP – Package Manager

STEP – 2: Installing the Telegram module for Python

Now, go to the terminal of a code editor and install the telegram module using Python with pip or conda install. Below is the code for both types of installations.

# using pip
pip install python-telegram-bot
# using conda 
conda install -c conda-forge python-telegram-bot

Also read: Python Anaconda Tutorial – Getting Started With Anaconda

STEP – 3: Setting up our Telegram Desktop Application and Spinning up a new Bot

Next, we need to start up our desktop application and configure it so that our custom code could be accessed it. Our code gets access to the telegram application using an API key. Before connecting our application to our code, we need to set up the basic bot functionality through the desktop application itself and obtain the unique API key for connection.

After opening the application on our desktop, search for BotFather in the application search tab. This pops up a new screen containing the basic settings to fire up a new bot for our application.

1 BotFather Search
BotFather Search

STEP – 4: Setting Up Basic Functionality

Next, we need to click the START button provided at the bottom of the BotFather page taking us to another screen containing pre-defined commands for the new bot like starting up a new bot using /newbot command, naming our bot, setting the description, setting the profile picture, and so on.

2 BotFather Settings
BotFather Settings

STEP – 5: Setting Up Basic Functionality and API Key Generation

Next, we need to provide our bot with a name/alias and a unique username. Note that the username for the bot should end with “bot” as directed by telegram. We can also provide descriptions and other information for our bot. Later, we will also set up our custom commands like /about, /help, and a few more which would provide a custom reply when used.

As we finish setting up our bot, an API KEY is generated specific to our bot that will connect it to our Python Code file. Now, copy the API KEY and paste it to a Python file to access it importing it as a module.

Note: The API key provides full access to control our bot. Make sure to put this key as an environment variable. If uploading any code to GitHub, do not forget to include the env vars file to your gitignore file.

3 Basics
Basics

STEP – 6: Code Implementation: Imports

Now, we have a basic application setup with the API key, we start by importing the telegram.ext module for Python as well our API Key stored in a python file named “secret.py”.

We will import everything from telegram.ext module using “*”. To see our bot server code running in our terminal, we can also include a print statement at the start of the code.

from telegram.ext import *
import secret

print("Server is running.... ")

STEP – 7: Setting Up Custom Command Functions

Next, we code up multiple functions to take care of the custom commands for our bot. They are fixed replies from our code, which can be invoked using /about, /help, etc. These functions will be later used by a handler function provided by telegram.ext module and a dispatcher function that comes later in the code, which would invoke these functions and provide responses accordingly.

def start_function(update, context):
    update.message.reply_text("Hello there! I'm AskPython Bot.")


def help_function(update, context):
    update.message.reply_text(
        """
    Available commands:

    /start : Starts up the bot
    /help : Help topics
    /about : About text
    /askpython : Go to AskPython Offical Website
    /custom : Other custom commands 

    """
    )


def about_function(update, context):
    update.message.reply_text("I am a bot and also a Python Genie.")


def ask_python_function(update, context):
    update.message.reply_text("AskPython Website: https://www.askpython.com/")


def custom_function(update, context):
    update.message.reply_text("Some other custom reply")

Explanation:

In the above code, we define the custom-built functions that help us invoke commands such as /start, /help, /about, /askpython, and /custom. Once we define the function, we need to pass 2 arguments to it namely update and context.

  1. Update: This argument is used as soon as the function is called and a text reply as defined is provided by it.
  2. Context: This argument although not being used directly in our function, is used internally by the code, and not including it as an argument would make the program throw errors. It is seen to be used later in the code while we use the dispatcher for the message.

STEP – 8: Functions for Incoming Text and Error Handling

Next, we are defining two more functions. The first named message_handler_function, would reply to the incoming text input message from our bot. This function can be powered by some AI application to process the incoming text and provide a suitable reply as per the text processing algorithm incorporated within that application. For this article, we will just provide a placeholder to output the same text that’s being entered into our bot.

Note that, this function would be invoked in a different way than the rest of the functions.

The second function would be a simple error handler function, which would get invoked if our application encounters any errors.

Code:

def message_handler_function(update, context):
    update.message.reply_text(f"Custom reply to message: '{update.message.text}'")

def error_handler_function(update, context):
    print(f"Update: {update} caused error: {context.error}")

STEP – 9: Connection through the API and Handling previously defined function

Next, We need to connect our application with the API key that we imported earlier in the code and also add handlers for all the functions that we defined previously in the code. The explanation follows after the code block.

Code:

# Connecting our app with the Telegram API Key and using the context
updater = Updater(secret.API_KEY, use_context=True)
my_dispatcher = updater.dispatcher

# Adding CommandHandler from telegram.ext to handle defined functions/commands
my_dispatcher.add_handler(CommandHandler("start", start_function))
my_dispatcher.add_handler(CommandHandler("help", help_function))
my_dispatcher.add_handler(CommandHandler("about", about_function))
my_dispatcher.add_handler(CommandHandler("askpython", ask_python_function))
my_dispatcher.add_handler(CommandHandler("custom", custom_function))

# Handing Incoming Messages
my_dispatcher.add_handler(MessageHandler(Filters.text, message_handler_function))

# Error Handling if any
my_dispatcher.add_error_handler(error_handler_function)

Explanation: In this part of the code, we are implementing functions with certain arguments that were previously defined in the code. Below is a brief overview.

  1. Updater: This function comes from telegram.ext module is taking in two args. The first one is the API Key that we are accessing through our “secret.py” file with the variable name API_KEY, and the second arg is directing the application to use context. This updater function is then chained with the dispatcher method and stored in the my_dispatcher variable which at the end provides methods to be used by the following handlers.
  2. CommandHandler: This function is responsible for handling the custom commands that we defined using the first set of functions.
  3. MessageHandler: This one is handling the function for the dynamic replies to an entered text with args Filters.txt and message_handler_function. Filters.txt is provided by the telegram.ext module.
  4. add_error_handler: This method as the name suggests catches any errors if encountered while running the code.

STEP – 10: Finishing up and running our bot

This step marks the final code lines to start our bot. It used polling(1.0) which means to spin up the bot through telegram server and check for messages every 1 second. Then there is the idle() function which keeps the bot idle if any input is not provided in the application.

Both these methods are invoked using the updater function which indeed provides the API Key and the context to our bot

# Starting the bot using polling() function and check for messages every sec
updater.start_polling(1.0)
updater.idle()

The Complete Code

from telegram.ext import *
import secret

print("Server is running.... ")

def start_function(update, context):
    update.message.reply_text("Hello there! I'm AskPython Bot.")

def help_function(update, context):
    update.message.reply_text(
        """
    Available commands:

    /start : Starts up the bot
    /help : Help topics
    /about : About text
    /askpython : Go to AskPython Offical Website
    /custom : Other custom commands 

    """
    )

def about_function(update, context):
    update.message.reply_text("I am a bot and also a Python Genie.")

def ask_python_function(update, context):
    update.message.reply_text("AskPython Website: https://www.askpython.com/")

def custom_function(update, context):
    update.message.reply_text("Some other custom reply")

def message_handler_function(update, context):
    update.message.reply_text(f"Custom reply to message: '{update.message.text}'")

def error_handler_function(update, context):
    print(f"Update: {update} caused error: {context.error}")

# Connecting our app with the Telegram API Key and using the context
updater = Updater(secret.API_KEY, use_context=True)
my_dispatcher = updater.dispatcher

# Adding CommandHandler from telegram.ext to handle defined functions/commands
my_dispatcher.add_handler(CommandHandler("start", start_function))
my_dispatcher.add_handler(CommandHandler("help", help_function))
my_dispatcher.add_handler(CommandHandler("about", about_function))
my_dispatcher.add_handler(CommandHandler("askpython", ask_python_function))
my_dispatcher.add_handler(CommandHandler("custom", custom_function))

# Handing Incoming Messages
my_dispatcher.add_handler(MessageHandler(Filters.text, message_handler_function))

# Error Handling if any
my_dispatcher.add_error_handler(error_handler_function)

# Starting the bot using polling() function and check for messages every sec
updater.start_polling(1.0)
updater.idle()

Testing The Python Telegram Bot

Now we are all set and ready to test our telegram bot.

  • Running the code, starting up the telegram desktop application, and searching up our bot using the username we provided. In our case, its @AskPython_01_bot
4 Search Our Bot With Username
Search Our Bot With Username
  • As soon as we click on our bot, it responds with the text that we fed in our start command function
Start Bot
start Bot
  • Let’s enter our /help command and see the response
Help Command
help Command
  • Using the /about command
About Command
about Command
  • Using /askpython command
Askpython Command
Askpython Command
  • Now, let’s try to enter something and see our bot response
Text Reply
Text Reply

Summary

In this article, we went through the basic steps to set up a telegram bot using Python. It’s not a very sophisticated bot like we see all around the internet using some great AI tools to make it sound like a human. But it showcases the ease of getting such a bot up and running with a small chunk of Python code. Using bots provides some great features and use cases to the ever-expanding tech field.

Reference

Python Telegram Bot Documentation