Create a python Telegram bot, plain, simple and production-ready

posted 6 min read
Beginners' friendly! This content is for anyone who wants to learn

1. Introduction

Most of the people nowadays make use of instant messaging tools, such as WhatsApp, Telegram, Discord or Snapchat, and if you are a user of one of these applications, you are probably already familiar with the concept of bot. If you aren't, let's have a quick look to what it is and how we can use it for our purposes.

The word "bot" is an abbreviation of "robot", and it has been introduced in informatic systems to identify non-human, completely automatic, users that has been employed for all sorts of purposes: correcting grammar mistakes (such as on Wikipedia), liking someone's post (on social media), scraping web content...

In recent years, people started to develop tools that could be used to generate automatic responses in messaging services. This was a solution firstly conceived for customer support, and now that bots entered the realm of chatting apps they are implied for lots of different tasks: moderation, standardized replies, message analysis, authorization... 

Now that you know what a bot is, if you already didn't, it is time to learn how we can build our own bot, and we'll start with one of the most beloved applications to deploy it: Telegram. 

2. Setup

We will take for granted the fact that you already have a Telegram account: in case you don't have, creating one is really simple and you just need to head over to their website (if you are on a laptop) or download their application (if you are on your cell phone).

Now, open Telegram and type into the search bar Botfather: this will guide you to the father of all bots, which will create the bot user we are interested in.

Send to BotFather the /newbot command, and it will prompt you to give your bot a username and then a name that ends with "bot".  For today's tutorial, we will create a simple Neapolitan Pizzeria assistant, so we will simply go for NeapolitanPizzaBot as both the username and the bot name.

Once you are done with the naming, BotFather will send you the real thing that interests us: the API Token, through which we will interact with Telegram, sending messages and retrieving responses. Copy the Token and then open a python file called bot.py in your favorite code editor.

TOKEN = "6789238423:sdhfshgbpsigbspgiJsnsoaH" #this is only an example token

3. Environment preparation

In order to make the "bot.py" script work with Telegram, you will need a lot more than just your token. First of all, you will need to install python-telegram-bot package, and you can simply do it through python package manager, pip:

python3 -m pip install python-telegram-bot

Now that the installation is done, we will be able to do everything we need, so let's dive in and build our Neapolitan Pizzeria Assistant. 

4. Build the bot

We will start by importing the necessary packages:

from telegram.ext import *

Now, we will start simply with defining the message that our bot will send to every user when it is started:

 async def start_command(update, context):
        await update.message.reply_text("Hi, I'm NeapolitanPizzaBot, how may I assist you today?")

Note that this and most of the following functions are asynchronous, which means that they are not executed right away when they are called, but they wait for the application to respond to their queries before execution.

We want our bot to be able to tell customers the price of our three most famous pizzas, which are Margherita, Marinara and Pepperoni, to send them the location of the restaurant and a photo of our complete menu.

In this sense, we will use commands, that, for Telegram bots, are strings of text that start with "/": we will use /price, /location and /menu.

For the /price command, we simply need to reply a text message, and this can be achieved with the reply_text method, as we did for our starting function.

async def price_command(update, context):
        await update.message.reply_text("- Margherita: 8$\n- Marinara: 5$\n- Pepperoni: 9$")
<p>For the /location command, we need to pass an actual location, and to do so we just use the <i>reply_venue</i> method and copy-paste the coordinates from Google Maps, pass the name of the place and the name of the street we are sending.</p>
 async def location_command(update, context):
        await update.message.reply_venue(40.82694507320722, 14.426713826679295, "Italy", "Pizzeria NeapolitanPizzaBot")

 In order to send an image, we must have it saved somewhere on our local machine, in order for the bot to take it and forward it to the user. We will just take a photo of our menu, save it within the same folder as bot.py under the name: "menu.png". Now we use the method reply_photo to send it:

async def menu_command(update, context):
    await update.message.reply_photo("menu.png")

Now we just need to define a function that handles errors and also a function that tells the user if they are using commands or messages that cannot be recognized:

async def unrecognized_command(update, context):
    text = update.message.text
    if (
        text.startswith("/start") == False
        or text.startswith("/menu") == False
        or text.startswith("/price") == False
        or text.startswith("/location") == False
    ):
        await update.message.reply_text(
            f'I cannot understand the message:\n"{text}"\nAs my programmer did not insert it among the command I am set to respond (that are /price, /menu and /location): please check for misspelling/errors or contact the programmer if you feel anything is wrong/missing'
        )
    else:
        pass


async def error_handler(update, context: CallbackContext) -> None:
    await update.message.reply_text("Sorry, something went wrong.")

Now that we are done with defining functions, we can actually write the portion of the code that will make the bot work:

if __name__ == "__main__":
    print("Bot is high and running")
    application = Application.builder().token(TOKEN).build()
    # Commands
    application.add_handler(CommandHandler("start", start_command))
    application.add_handler(CommandHandler("menu", menu_command))
    application.add_handler(CommandHandler("price", price_command))
    application.add_handler(CommandHandler("location", location_command))
    application.add_handler(MessageHandler(filters.COMMAND, unrecognized_command))
    application.add_handler(MessageHandler(filters.TEXT, unrecognized_command))
    application.add_error_handler(error_handler)
    # Run bot
    application.run_polling(1.0)

As you can see, we associated to each command its related function, and then we filtered out all the commands and the texts without commands that cannot be recognized. If something goes wrong, the code is set to handle the error. Last but not least, we launch our application with the run_polling method. 

5. Run the bot

To run the bot, you can simply launch it from your terminal typing:

python3 bot.py

Alternatively, if you want your bot to run independently from your machine, you can explore services such as pythonanywhere

Here is, in the meanwhile, an example chat for our bot

example_chat

6. Conclusion


To sum things up, you have build your first python Telegram bot, that is production-ready and will be really useful for our Neapolitan Pizzeria. In this sense, we also explored how basic python skills can be directly applied to real projects and works. 


In my next posts, I will explain how to fine-grain our Telegram bots and, when we become sufficiently skilled at building them, we will switch to Discord bots. Our ultimate goal will be to create an AI-powered bot, and this will be the last episode of our bot-related post series... Stay tuned!

If you read this far, tweet to the author to show them you care. Tweet a Thanks

More Posts

Learn how to build a user-friendly, conversational Telegram bot with python

Astra Bertelli - Apr 30

Build a Telegram bot with Phi-3 and Qdrant and chat with your PDFs!

Astra Bertelli - May 9

Git and GitHub for Python Developers A Comprehensive Guide

Tejas Vaij - Apr 7

How to read a file and search specific word locations in Python

Brando - Nov 8, 2023

How to create an Income and Expense App in Streamlit

Brando - Nov 19, 2023
chevron_left