Building a Telegram Bot using Python to Generate Random Quotes
Chatbots are software applications used to conduct online chat conversations and automate customer service via text or text-to-speech. Chatbots can be utilized for things like reminders, booking of appointments, and also on social media platforms. <!--more--> In this tutorial, we will build a simple Telegram bot that sends automated programming quotes to a Telegram group at intervals using Python.
Telegram is a free and open-source, cross-platform, cloud-based instant messaging (IM) software. It provides video calling and file-sharing amongst other features.
Prerequisites
To follow along with this tutorial, you'll need Python 3 installed on your machine and, a little understanding of Python would help the reader to follow along better.
Table of contents
Setting up bot profile
To set up a new bot, we need to register our bot first before using it. That way, we get the token to access the Telegram API. If you don't have a Telegram account, go ahead and create one here.
Click on the search icon in Telegram, then, type @botfather
in the search bar.
BotFather is the official bot created by Telegram to facilitate bot creation.
Creating Bot father in Telegram
Now, click on the start button to start a conversation. You should get the following interface:
Starting conversation with Bot father
Type /start
to get started.
Next, we create the bot by running /newbot
command.
Create new bot
Next, we type in our preferred name and username for the bot.
Choosing bot name
Now, we copy our access token and save it somewhere. Remember to properly secure the access token, as it serves as your bot password.
Coding the bot
We start by creating a new directory and navigate into it.
Next, we create a virtual environment.
A virtual environment allows you to create different spaces on your computer, with a different set of libraries and versions.
By creating a virtual environment, you'll be able to separate the necessary library installation for a project, without having to install them globally.
Now, create a virtual environment env
by running the command below:
python -m venv env
On creation, activate the virtual environment using the following command:
source env/bin/activate
Next, we need to create a Telegram group and add our bot as a member.
Add members to Bot
Next, we need to get the Chat ID, we can do this by sending this command as a message on the Telegram group:
/my_id BOT_NAME
After that, we need to open the URL below in our browser to get our chat id:
https://api.telegram.org/botBOT_TOKEN/getUpdates
BOT_TOKEN = the token we copied earlier
This returns a JSON response, something like a python dictionary that contains our chat id.
JSON containing Chat ID
Now, we create a new python file named bot.py
and add the following lines of code in it:
import requests
import time
# list of quotes
quotes = [
'First, solve the problem. Then, write the code. – John Johnson',
'Experience is the name everyone gives to their mistakes. – Oscar Wilde',
'Code is like humor. When you have to explain it, it’s bad. – Cory House',
'Before software can be reusable it first has to be usable. – Ralph Johnson',
'Optimism is an occupational hazard of programming: feedback is the treatment. - Kent Beck'
]
# loop through the quotes
for quote in quotes:
url = 'https://api.telegram.org/bot1848805395:AAHaacRzz3vDJ8vrQqVZ4vMPTqY1OBOQ12Q/sendMessage?chat_id=CHAT_ID&text="{}"'.format(quote)
requests.get(url)
# sends new quotes every 20seconds
time.sleep(20)
Before testing the bot, we need to install the requests module using the following code:
pip install requests
Now, let's test our bot by running our Python file in the terminal:
python bot.py
Printing a quote every 20 seconds
Hurray, it works!
Let's make our bot more interesting by connecting to an API that feeds us with random programming quotes.
We'll be using this API, and the /random
endpoint to get random quotes.
Next, we need to add the following lines of code at the top of our file
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
import json
Now, let's create a function that sends random quotes, by adding the following lines of code:
telegram_bot_token = "TOKEN"
updater = Updater(token=telegram_bot_token, use_context=True)
dispatcher = updater.dispatcher
def random(update, context):
# fetch data from the api
response = requests.get('http://quotes.stormconsultancy.co.uk/random.json')
data = response.json()
# send message
context.bot.send_message(chat_id=update.effective_chat.id, text=data['quote'])
# linking the /random command with the function random()
quotes_handler = CommandHandler('random', random)
dispatcher.add_handler(quotes_handler)
Now, let's run the file and enter /random
in our Telegram group. Our bot should respond with a random quote.
Bot fetching random quote using an API
Conclusion
To conclude, we have learned about building Telegram bots for groups.
There is still a lot you can achieve with a Telegram bot, like connecting your bot to other APIs and hosting them on a platform like Heroku to make your bot available 24/7.
You can also check the Telegram bot documentation for more info on creating bots.
Here are some API's you could integrate with your Telegram bot:
Happy Coding!
Peer Review Contributions by: Srishilesh P S