How to make a simple telegram bot on python

How to make a simple telegram bot on python

It's very simple to make a telegram bot using python. Let's try and make a simple bot - it has only one supported command /cat (to get random cat pictures) apart from the default /start and /help.

Requirements -

  1. Python3 installed
  2. pip3 installed

Install the requirements

pip3 install python-telegram-bot --upgrade
pip3 install requests

Let's start

We will need to make a main.py file, below is a scaffold which we will need for almost any bot -

import logging
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters

logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
                    level=logging.INFO)
logger = logging.getLogger(__name__)

def start(update, context):
    update.message.reply_text('Hi use /cat to get cat pics!')


def help_command(update, context):
    update.message.reply_text('Help: use /cat to get cat pics!')


if __name__ == '__main__':
    TOKEN = "<the bot token>"
    updater = Updater(TOKEN, use_context=True)

    # Get the dispatcher to register handlers
    dp = updater.dispatcher

    # on different commands - answer in Telegram
    dp.add_handler(CommandHandler("start", start))
    dp.add_handler(CommandHandler("help", help_command))

    # Start the Bot
    updater.start_polling()

    # Run the bot until you press Ctrl-C
    updater.idle()

In the above code, we need to add a new handler inside __main__

dp.add_handler(CommandHandler("cat", catpic))

Now, we need to define the catpic handler method

def catpic(update, context):
    import requests
    url = requests.get('https://api.thecatapi.com/v1/images/search').json()[0]["url"]
    update.message.reply_photo(url)
    update.message.reply_text("Here is a nice cat!")

We get a image url from the API and use the reply_photo method to send that image link.

Create a bot on telegram

  1. Goto t.me/botfather, this is a bot by telegram which helps us create and manage our bots.
  2. write /start to see a list of all commands
  3. write /newbot to start creation of a new bot
  4. follow the steps and get the token after the bot is created
  5. in the main.py update the TOKEN variable with the new bot token

Run the bot

python3 main.py

Goto your bot on telegram and try the commands -

  1. /start
  2. /help
  3. /cat

/cat command should give you a nice picture of a cat.