Telegram Bot on Python 3

Today we will create a simple telegram bot on python that can respond to our messages, interact with us, offering answer options in the form of buttons and process the result we selected by executing commands on the server. Work with Telegram Bot Api we will using the pyTelegramBotAPI (telebot) library written in Python.

  1. Create bot
  2. Install Python and library pyTelegramBotAPI
  3. Write telegram bot on python
  4. Use proxy in telebot
  5. Bot answers to user messanges
  6. Keyboard in telegram bot
  7. InLine keyboard
  8. Complete listing

Create telegram bot

To register a new bot, you need to write the BotFather bot. To do this, type BotFather in the search bar and in the results find it:

Attention! Check bot name, image and a check mark, indicating that he is really the father of all bots.

Click it and write the command /start and the bot in the response message will send a list of all available commands:

We need to creating a new bot, so we select the /newbot command. You can either type the command yourself or select the mouse in the message and it will automatically be sent:


The first step we are offered to give a name to the new bot, it can be arbitrary. We will call it PocketAdmin:

Now you need to specify the bot identifier (username), it must end with _bot and be unique in the system. We will indicate PocketAdminTech_bot:


In the last message, we received a link to our new bot t.me/PocketAdminTech_bot and the token (shaded) needed to interact with the API.

Attention! Be sure to keep the token and keep it secret!

Install Python and library pyTelegramBotAPI

Download Python you can from the official site (how to install the package on Centos 8 can be found in this article) and we will not focus on this issue.

To install the pyTelegramBotAPI package, use pip:

pip install pytelegrambotapi

On this, the preparatory work is completed, we proceed directly to writing our bot.

Write telegram bot on python

Since our bot is created for educational purposes and will not contain a lot of code, I will write it on the server with Centos 8 installed using the nano editor. Create the bot.py file by opening it nano:

nano bot.py

For first we imort library pyTelegramBotAPI:

import telebot

Then declare variable equal to our token, which we received from BotFather for interacting with Telegram Bot Api: :

token = 'your token api'

Declare bot:

bot = telebot.TeleBot(token)

Next, a decorator is set. So far, our bot will process only the start command:

@bot.message_handler(commands=['start'])

and in response write us “Hello!”:

def start_message(message):
    bot.send_message(message.chat.id, 'Hello!')

So that the bot expects a request from the user:

bot.polling()

In final we get the code:

import telebot

token = 'your token api'

bot = telebot.TeleBot(token)

@bot.message_handler(commands=['start'])
def start_message(message):
    bot.send_message(message.chat.id, 'Hello!')

bot.polling()

Run it:

python bot.py

Then open our bot (can be found by name) and write him a command /start:

Congratulations on the first words of our bot PocketAdmin!

Use proxy in telebot

When you run the script, you may receive an error:

requests.exceptions.ConnectionError: ('Connection aborted.', ConnectionResetError(104, 'Connection reset by peer'))

In some countries telegram is blocked. You can use proxies:

from telebot import apihelper
apihelper.proxy = {
    'https':'socks5://login:password@ip:port'}

where login:password@ip:port – data for connecting to the proxy.

If errors occur when using the proxy, such as: Not supported proxy scheme socks5 or Missing dependencies for SOCKS support, then you need to install the modules:

pip install requests[socks] PySocks

Bot answers to user messages

Similar to handlers for commands, the telegram bot api has the ability to process messages from the user. For this, the type text is used. For example, we can program the bot to respond to certain phrases or words of the user:

@bot.message_handler(content_types=['text'])
def send_text(message):
    if message.text.lower() == 'hello':
        bot.send_message(message.chat.id, 'Hello again!')
    elif message.text.lower() == 'bye':
        bot.send_message(message.chat.id, 'Bye!')

The bot will respond to the word “Hello” – “Hello again!”, and to “Bye” – “Bye!”. All code will now look like this:

import telebot

token = 'your token api'

bot = telebot.TeleBot(token)

@bot.message_handler(commands=['start'])
def start_message(message):
    bot.send_message(message.chat.id, 'Hello!')

@bot.message_handler(content_types=['text'])
def send_text(message):
    if message.text.lower() == 'hello':
        bot.send_message(message.chat.id, 'Hello again!')
    elif message.text.lower() == 'bye':
        bot.send_message(message.chat.id, 'Bye!')

bot.polling()

Restart the script and talk to the bot:

This way we can describe various dialogs with the bot.

Keyboard in Telegram Bot on Pyhon

Telegram Bot Api allows you to use your keyboard, or rather, quick buttons that allow the user to send text by pressing them.

Add a keyboard with the “Hello” and “Bye” buttons to the /start command handler:

@bot.message_handler(commands=['start'])
def start_message(message):
    keyboard = telebot.types.ReplyKeyboardMarkup(True)
    keyboard.row('Hello', 'Bye')
    bot.send_message(message.chat.id, 'Hello!', reply_markup=keyboard)

And run the modified script. As soon as we send the /start command to the bot, our keyboard will appear below:

Now to send messages just click on the appropriate button. It is very convenient in the mobile version of the telegram.

InLine keyboard

The most interesting is the InLine keyboard. It allows you to send interactive buttons to the user along with the message, for example, with answer options, and after they are pressed, process the result.

Let’s add a simple question from the bot to the command /test:

@bot.message_handler(commands=['test'])
def start_message(message):
    markup = telebot.types.InlineKeyboardMarkup()
    markup.add(telebot.types.InlineKeyboardButton(text='Three', callback_data=3))
    markup.add(telebot.types.InlineKeyboardButton(text='Four', callback_data=4))
    markup.add(telebot.types.InlineKeyboardButton(text='Five', callback_data=5))
    bot.send_message(message.chat.id, text="How much is 2 plus 2?", reply_markup=markup)

Variable markup declares a new inline keyboard, and markup.add creates a button. The main parameters when creating the button are text and callback_data: the first is responsible for the text on the button, the second is the data that will be transmitted to the bot when the user selects a specific answer option.

Run script and send command /test:

Well, the bot sent us message with answer buttons. But when you click on the button, nothing will happen, because we did not describe the processing of the results. Let’s fix this:

@bot.callback_query_handler(func=lambda call: True)
def query_handler(call):

    bot.answer_callback_query(callback_query_id=call.id, text='Answer accepted!')
    answer = 'You made a mistake'
    if call.data == '4':
        answer = 'You answered correctly!'

    bot.send_message(call.message.chat.id, answer)
    bot.edit_message_reply_markup(call.message.chat.id, call.message.message_id)

bot.answer_callback_quer is a pop-up window that will be shown to the user after clicking the button. And the value that we specified when creating the keyboard in the callback_data parameter will be transferred to call.data. We will answer the bot by choosing one of the answers:

Great, everything works. But it will be better if, after answering, the keyboard remove from the chat. This can be done by adding the following line to the end of the query_handler function:

bot.edit_message_reply_markup(call.message.chat.id, call.message.message_id)

This is a keyboard editing function called without specifying a keyboard object. Now, after the user’s response, the keyboard will be removed by the bot:

Complete listing

We examined only a small part of the capabilities of telegram bot api, however, these are the basic and very useful tools for working with it. At the end, we give a complete listing of the our telegram bot on python:

import telebot

from telebot import apihelper
apihelper.proxy = {
    'https':'socks5://login:password@ip:port'}

token = 'your token api'

bot = telebot.TeleBot(token)

@bot.message_handler(commands=['start'])
def start_message(message):
    keyboard = telebot.types.ReplyKeyboardMarkup(True)
    keyboard.row('Hello', 'Bye')
    bot.send_message(message.chat.id, 'Hello!', reply_markup=keyboard)

@bot.message_handler(commands=['test'])
def start_message(message):
    markup = telebot.types.InlineKeyboardMarkup()
    markup.add(telebot.types.InlineKeyboardButton(text='Three', callback_data=3))
    markup.add(telebot.types.InlineKeyboardButton(text='Four', callback_data=4))
    markup.add(telebot.types.InlineKeyboardButton(text='Five', callback_data=5))
    bot.send_message(message.chat.id, text="How much is 2 plus 2?", reply_markup=markup)

@bot.message_handler(content_types=['text'])
def send_text(message):
    if message.text.lower() == 'hello':
        bot.send_message(message.chat.id, 'Hello again!')
    elif message.text.lower() == 'bye':
        bot.send_message(message.chat.id, 'Bye!')

@bot.callback_query_handler(func=lambda call: True)
def query_handler(call):

    bot.answer_callback_query(callback_query_id=call.id, text='Answer accepted!')
    answer = 'You made a mistake'
    if call.data == '4':
        answer = 'You answered correctly!'

    bot.send_message(call.message.chat.id, answer)
    bot.edit_message_reply_markup(call.message.chat.id, call.message.message_id)

bot.polling()