Build your first Telegram Bot using Python
If you are learning python and want to get your hands dirty by taking up a real-time project, come grab a seat and let me take you on a ride into the awesome world of python.
Let me start by introducing the things that you are gonna need for a while:
- Creating a bot token using botfather (of course assuming that you are having a telegram account)
- A wrapper of telegram API in python (pyTelegramBotAPI)
- Your enthusiasm (definitely yes)
Yes, that’s all the recipe you need to do your first Telegram bot.
Creating our bot
Step 1: Search @BotFather in telegram and press start.
Step 2: Type in /newbot, then type in your desired name for the bot and username for the bot (make sure to create a unique username, also it must end with `Bot`).
e.g. motivate11Bot or motivate11_bot
Step 3: Congratulations, now you have your own bot in Telegram that can automate your stuff. Copy the API Token and get started to code your bot.
Don’t share or make your API Token publicly visible. It’s just like giving your account password.
Installing package and dependencies
Always ensure to create a virtual environment so that dependencies don’t mess up your whole environment.To create the virtual environment, open the command prompt or if you use anaconda prompt it will be much easier.
For command prompt:
$ python3 -m venv /path/to/new/virtual/environmentFor anaconda prompt:
$ conda create -n pybot python=3.7.2
After creating this virtual environment, switch from base to virtual environment.
For command prompt:
$ source ./venv/bin/activateFor anaconda prompt:
$ conda activate pybot
Now, let us install the packages that does the magic,
$ pip install pyTelegramBotAPI
that pretty much covered everything that is required, there are a lot other Telegram API’s available, but we choose pyTelegramBotAPI because of its simplicity and elegance.
Follow up this directory structure
.
├── bot.py
└── config.json
Create a new file named ‘config.json’ containing the obtained API_KEY as key-value pair in the same directory.
Example:
Now, let’s get our hand into coding by firing up IDE.
#required packages
import telebot
import requests
import os
import json#Config vars
with open(‘config.json’) as f:
token = json.load(f)#initialise bot
bot = telebot.TeleBot(token[‘telegramToken’])
x = bot.get_me()
print(x)#pool~start the bot
bot.polling()
Telebot is part of pyTelegramBotAPI
that handles the interaction with Telegram bot. Run the snippet and Voilaa!!!.
If you get an output like this:
Then, you’ve now successfully connected your Telegram bot with Python.
Let us add more commands that the bot can use to interact with its user. Add the following functions before the `pooling` step. (Link to an example repository given at end of this article)
#handling commands - /start
@bot.message_handler(commands=[‘start’, ‘help’])
def send_welcome(message):
bot.send_message(message.chat.id, “Welcome user”)
Using `@bot.message_handler` decorator, you’ve now triggered a piece of code to run when the mentioned command is called. This welcomes a user or sends a help message when /start or /help command is provided.
For more handlers and API methods, check: https://github.com/eternnoir/pyTelegramBotAPI & https://core.telegram.org/bots/api
Now, let’s connect a simple API to demonstrate how Bots can be used to automate and simplify your daily task .
#handling commands - /motivate
@bot.message_handler(commands=[‘motivate’])
def send_quotes(message):
quote= requests.request(url=’https://api.quotable.io/random',method='get')
bot.reply_to(message, quote.json()[‘content’])
This replies with a random quote from `quotable.io` to the user whenever /motivate is sent.
For clear understanding of code and setup, visit this repo:
So, I’ve demonstrated a way to automate simple tasks using this bot, you can create a bot that provides daily stats of your company or price of products to customers or as a gateway to your Machine Learning models !!
Unleash your ideas into working models. Start up building your own bots.
Learn how to deploy this bot into Heroku in part 2 of this blog:
Learn, Share & Contribute. Happy Learning !!