Python Telegram Bot

Python Telegram Bot is among one the highest-earning bot. Today, you’ll learn about what this bot is and will make a simple telegram chatbot in python.

Getting Started with Python Telegram Bot

In order to make a Telegram bot, you first need to get familiar with telegram and since you’re going to use python as your development language, you need to have knowledge of at least Python basics and syntax.

Introduction to Telegram

Telegram is a free, cross-platform, cloud-based, powerful desktop or mobile messaging app that does not have any limit on the size of media and chats. You can visit Telegram’s official website to know more about it.

Algorithm

In order to make a Python telegram bot, you’ll have to follow the following algorithm:

  1. Get an API token for your bot from telegram.
  2. Import Python Telegram Bot Library or other necessary libraries in python.
  3. Trigger the bot through the API Token.
  4. Set Specific Command Handlers and define functions.
  5. Start the bot to function

What is API Token?

Generally, API stands for Application Programming Interface. It is an intermediate between software that allows them to talk to each other. Many applications run on the same API but they have different functions, so in order to differentiate between those applications, API provides each and every application with a unique ID called a token. Whenever the API is called it recognizes the application by its API token.

Get the API Token from Telegram

In order to get a token for your Python telegram Bot API token, you need to search for an official telegram bot, i.e., @BotFather on your telegram mobile or desktop app, or web app. Once you find the bot, you need to send the following commands to get your API token:

  1. Click on the start button and start the bot.
  2. Send /newbot command to create a new bot.
  3. Send your bot name, the name you want to give to your bot (here: my telegram chatbot).
  4. Send your bot username, the username you want to give to your bot (here: webmatrices_bot).
Get an API token for your Python Telegram Bot
Get an API token for your Python Telegram Bot

What are Specific Command handlers?

Commands are some specific trigger words that make the bot execute a specific task. For example, if you want your bot to send a greeting message to the user, whenever the user sends the message greet, greet is considered as a specific command. And telebot library has a specific class called message_handler to handle messages with specific commands. Generally, telegram recognizes bot commands starting with /, so all commands to the bot should start with / but it is not necessary to include / in the code.

Diving Into the Code

Importing Packages

The first and foremost thing you need to do is import the required packages. For this task you require only two packages: os and telebot and os is pre-installed in python but you need to install telebot using the following command:

pip install pyTelegramBotAPI

Now you import these packages to your code simply by the following code:

import os
import telebot

Get API Token

After importing all required libraries and packages, you need to get the API token for the bot you created above. As the token is an important part of the Bot, it should be stored confidentially and should not be made public. In order to keep your token save you can save your token as an environment variable in your device and get it using python os library.

Saving Token as Environment Variable

For Windows, you can search “env” in the search bar and open the first application.

Environment Variables Application

After the application is opened, click on Environment Variables and then on New.

Creating Environment Variable

Enter the name for your token (here: bot_token) in Variable Name and your API Token in Variable Value and press Ok. Again press Ok and then Ok again. Now your variable has been saved successfully.

For Linux-based systems, you can go through this to set up the environment variable, and this one for macOS.

Calling Token Variable from Code

Now you can call your token variable from your python code using the os library without exposing it in the code and trigger the bot with the API token.

API_KEY = os.getenv('bot_token')
bot = telebot.TeleBot(API_KEY)

Creating Specific Command Functions

Now as you know what are commands and Command Functions, you’ll create separate functions for each and every commands you want your bot to interact with.

At first, you should create a start command to get your bot started.

@bot.message_handler(commands=['start'])
def send_welcome(message):
	bot.reply_to(message, "Hello! Welcome to Webmatrices Telegram Bot...")

Output:

Start Command

Now, you should create a help command, that should list out all the commands available for your bot, in order to make it easier for the user to use.

@bot.message_handler(commands=['help'])
def send_help(message):
	bot.reply_to(message, "Here are the list of commands you can use to operate this bot:\n 1. /start: to start the bot\n 2. /help: to get the command list of this bot\n 3. /greet: to get greetings from this bot\n 4. /blogs: to get updates on our blogs")

Output:

Help Command

After creating start and help commands, now you can create any kind of specific commands of your choice. For example, here you’ve two commands, one is greet which sends the greeting message whenever the user sends a greet command and the other is blogs, which sends the user, details of our blog whenever the user queries for blogs.

@bot.message_handler(commands=['greet'])
def send_greetings(message):
	bot.reply_to(message, "Howdy, how are you doing?")

@bot.message_handler(commands=['blogs'])
def send_blogs(message):
	bot.reply_to(message, "Please check out our blogs at: https://blog.webmatrices.com/\nIf you want blogs on specific topic, you can send the following commands to get blogs on those topics.\n1. /blogs:coding : To get updates on Coding\n2. /blogs:python : To get updates on Python\n3. /blogs:linux : To get updates on Linux\n4. /blogs:google-adsense : To get updates on Google Adsense\n5. /blogs:business : To get updates on Business\n6. /blogs:science : To get updates on Science")

Output:

Blogs Command

Now you can start the bot by using the following code:

bot.infinity_polling()

Complete Code

import os
import telebot

API_KEY = os.getenv('bot_token')
bot = telebot.TeleBot(API_KEY)

@bot.message_handler(commands=['start'])
def send_welcome(message):
	bot.reply_to(message, "Hello! Welcome to Webmatrices Telegram Bot...")

@bot.message_handler(commands=['help'])
def send_help(message):
	bot.reply_to(message, "Here are the list of commands you can use to operate this bot:\n 1. /start: to start the bot\n 2. /help: to get the command list of this bot\n 3. /greet: to get greetings from this bot\n 4. /blogs: to get updates on our blogs")

@bot.message_handler(commands=['greet'])
def send_greetings(message):
	bot.reply_to(message, "Howdy, how are you doing?")

@bot.message_handler(commands=['blogs'])
def send_blogs(message):
	bot.reply_to(message, "Please check out our blogs at: https://blog.webmatrices.com/\nIf you want blogs on specific topic, you can send the following commands to get blogs on those topics.\n1. /blogs:coding : To get updates on Coding\n2. /blogs:python : To get updates on Python\n3. /blogs:linux : To get updates on Linux\n4. /blogs:google-adsense : To get updates on Google Adsense\n5. /blogs:business : To get updates on Business\n6. /blogs:science : To get updates on Science")

@bot.message_handler(commands=['blogs:coding'])
def send_coding_blogs(message):
	bot.reply_to(message, "Check out our Coding Blogs Here: https://blog.webmatrices.com/category/coding/")

@bot.message_handler(commands=['blogs:python'])
def send_python_blogs(message):
	bot.reply_to(message, "Check out our Blogs on Python here: https://blog.webmatrices.com/category/python/")

@bot.message_handler(commands=['blogs:linux'])
def send_linux_blogs(message):
	bot.reply_to(message, "Check out our Blogs on Linux here: https://blog.webmatrices.com/category/linux/")

@bot.message_handler(commands=['blogs:google-adsense'])
def send_adsense_blogs(message):
	bot.reply_to(message, "Check out our Blogs on Google Adsense here: https://blog.webmatrices.com/category/google-adsense/")

@bot.message_handler(commands=['blogs:business'])
def send_business_blogs(message):
	bot.reply_to(message, "Check out our Blogs on Business here: https://blog.webmatrices.com/category/business/")

@bot.message_handler(commands=['blogs:science'])
def send_science_blogs(message):
	bot.reply_to(message, "Check out our Blogs Science here: https://blog.webmatrices.com/category/science/")

bot.infinity_polling()

Conclusion

So, now you’ve learned to create a python telegram bot. Now you can use this script to create your own bot for specific tasks. You can create such chatbots and host on different servers to keep it alive 24×7 and you can sell them to companies to earn from your bot.

  • April 26, 2022