If you’re a Telegram user, you’re bound to have had a ‘conversation’ with a chatbot at some point. With their amazing customizability, Telegram’s bots offer a variety of advantages---be it for automating tasks or just having a bit of fun with games in your chat group.

While some may find developing a bot to be a daunting task, it really isn’t. With the right planning, you can have a Telegram bot up and running in less than an hour! Here's how to create a simple Telegram bot that outputs cute pictures of internet cats when prompted.

Getting Started

For this tutorial, we are going to use Python 3, the python-telegram-bot and requests library, and TheCatAPI.

Every bot in Telegram has a unique token that helps it communicate with Bot API in order to use the app’s messaging interface. Bot API, one of Telegram's most popular features among developers, allows you to use its messages as an interface.

To get the token, start a conversation with @BotFather which, as the name suggests, is an official bot that lets you create and customize your own bots. You can access the bot using the given link or alternatively search ‘@botfather’ on Telegram.

Once in the chat, create your bot by typing the /newbot command. Continue to set the name and username of your bot (we decided to name ours @pawsomebot). Following this, you will get a token unique to your bot.

Now that we have all the prerequisites, it's time to get to the exciting part!

Installing Libraries

If you’re using Windows, open up command prompt and type the following commands:

        pip install python-telegram-bot
pip install requests

If you’re using macOS or Linux, use the following commands on your terminal instead. Additionally in Linux, make sure you are logged in as a user with sudo privileges.

        pip3 install python-telegram-bot
pip3 install requests

Writing the Program

Create a new folder on your computer and open it in your favorite editor. Create a new file and name it main.py. This file will contain the source code for your bot.

Now, let’s import the libraries we installed earlier along with some of their built-in functions.

            from telegram.ext import Updater, CommandHandler
import requests
import re

    

The flow of the program from here on out is to access TheCatAPI, obtain the URL of a random image, and send that image to the user’s chat.

Let’s start with a function to get the image URL, which can be done using the requests module. In this function, we load the JSON data of a random file provided by TheCatAPI and extract its URL to later use. To look at the format of the JSON object, head over to https://api.thecatapi.com/v1/images/search on your browser. You will notice something like this:

            [{"breeds":[],"id":"a8c","url":"url.jpg","width":800,"height":533}]

    

Notice that the JSON object is an array that holds a dictionary. This dictionary contains the URL with the key 'url'. To extract the URL, we need to reference the first element of the array, and then the relevant key.

            def getUrl():
    #obtain a json object with image details
    #extract image url from the json object
    contents = requests.get('https://api.thecatapi.com/v1/images/search')
    url = contents[0]['url']
    return url
    

Next up, we need to send this image into a user’s chat. For this, we need an image URL as well as the unique ID of the user’s chat. Let’s create a wrapper function to do this. First, we call the getUrl(). function to obtain the URL of a random image---this URL changes every time your program iterates through the function.

This is then followed by obtaining the recipient user’s chat ID, which defines the bot’s target location for messages and parsing the URL through the Bot API’s inbuilt send_photo() function.

            def sendImage(bot, update):
    url = getUrl()
    chat_id = update.message.chat_id
    bot.send_photo(chat_id=chat_id, image=url)

    

To find out more about Bot API’s various inbuilt functions and how they work, feel free to check out Telegram’s official documentation after this tutorial.

Finally, let’s create a function that controls the overall working of the bot. This function---conventionally called main()---is where we send an HTTP request to Bot API using the token we obtained at the beginning of the tutorial and then define what the bot’s user interaction will be like. In a case as simple as ours, this essentially means initiating the bot and calling the sendImage() function when prompted by the user.

            def main():
    updater = Updater("1190888035:AAGeJ9316R95NqJLFefV5vQA-UL4np11V2c")
    #call sendImage() when the user types a command in the telegram chat
    updater.dispatcher.add_handler(CommandHandler('meow',sendImage))
    #start the bot
    updater.start_polling()
    updater.idle()

if __name__ == '__main__':
    main()
    

Your final program should look like this:

            from telegram.ext import Updater, CommandHandler
import requests
import re
def getUrl():
    #obtain a json object with image details
    #extract image url from the json object
    contents = requests.get('https://api.thecatapi.com/v1/images/search')
    url = contents[0]['url']
    return url

def sendImage(bot, update):
    url = getUrl()
    chat_id = update.message.chat_id
    bot.send_photo(chat_id=chat_id, image=url)

def main():
    updater = Updater("1190888035:AAGeJ9316R95NqJLFefV5vQA-UL4np11V2c")
    #call sendImage() when the user types a command in the telegram chat
    updater.dispatcher.add_handler(CommandHandler('meow',sendImage))
    #start the bot
    updater.start_polling()
    updater.idle()

if __name__ == '__main__':
    main()

    

Your Own Telegram Bot

Congratulations! You’ve built your very own stress-relieving bot that sends open-source images of the cutest internet cats upon being prompted. Try running your program and type /meow in your bot's chat to activate it.

While this may be a simple bot with limited functionality, it shows just how powerful Telegram’s bot development ecosystem is. You can add in any number of complex subroutines and features to enhance the functionality of your bot---the sky's the limit. To find out more about awesome Telegram bots that contributors have made over the years, check out our list of useful Telegram bots.

You can also find a variety of open-source licensed programs for Telegram bots on platforms such as GitHub. Most open-source licenses allow you to use, study, download, or modify the source code of a program.

Host Your Telegram Bot Online

Now that you have your bot up and running, try closing main.py on your PC and use the bot on your Telegram messenger app. Does it still respond to the /meow command? No, it doesn't.

As a beginner, you may be confused as to why main.py on your PC needs to be up and running when you have already created a bot running on the internet. The reason for this is that the program uses your PC as a local server to send HTTP requests to the APIs used in this program.

As such, having to run the program every time you want to use the app is neither feasible nor convenient. In order to solve this issue, we need to remove the bot's dependency on your device

One way to do so is to use a low-cost printed circuit board (PCB), such as Raspberry Pi, to set up your own web server and use it to run your program. It has the same benefits as running the program on your PC without the costs of keeping it on all day and night since PCBs tend to have a significantly lower energy footprint.

Alternatively, you can also deploy your program to the cloud. Head over to a web-app hosting platform such as Heroku, AWS, Google Cloud, or Microsoft Azure and choose a subscription that best suits your needs. We recommend choosing a free trial or subscription and upgrading it as you increase the scale or scope of your program.