Algorithmia Blog

Create a Chatbot for Telegram in Python to Summarize Text

This is a guest post by Barend Rijn, a 16-year-old Python enthusiast. Want to contribute your own how-to post? Let us know contact us here.

I heard about Algorithmia when their Colorize It demo was featured on Product Hunt. I’m an aspiring developer, and immediately fell in love with the way they made machine intelligence accessible to me. I had been building chatbots using the python-telegram-bot wrapper for the Telegram Bot API, but then a light went off in my head: a Telegram chatbot that you can use to summarize your text. How cool would that be?

In this tutorial, I’ll walk you through everything you need to create a chatbot with Telegram and Algorithmia that summarizes the text you send it. Here’s a live example of the chatbot we’ll be building on Telegram. Just talk to it @summaris_bot.

Create a Free Algorithmia Account and Install Client

You’ll need a free Algorithmia account for this tutorial. Use the promo code “summarizer” to get an additional 5,000 credits when you sign up.

Next, make sure you have the latest Algorithmia Python client on your machine. Let’s do that really quick:

$ pip install algorithmia

---
Installing collected packages: algorithmia, requests, enum34, six
Successfully installed algorithmia requests enum34 six
Cleaning up...

and to check that installation was successful…

$ pip show algorithmia

---
Name: algorithmia
Version: 1.0.5
Location: ...
Requires: requests, enum34, six

The Algorithmia Python Client should be version 1.0.5.

Install the Python Telegram Bot Framework

You’ll also need the latest version of python-telegram-bot, which is version 5.0.0 at the time of writing. Let’s install that too. If you know you don’t want to use python-telegram-bot, you’re free to use something else, but you have to adapt the code yourself.


$ pip install python-telegram-bot
$ pip show python-telegram-bot

Now, let’s create our chatbot…

Coding the Chatbot

Start by opening a new Python file in your favorite (plain) text editor. I use Sublime Text. I’ll name my file bot.py (how original!).

Step 1: Add Dependencies

Then, write or paste the following lines in:

# Import dependencies
from telegram.ext import Updater
import logging
import Algorithmia
from telegram.ext import CommandHandler
from telegram.ext import MessageHandler, Filters

This will make all dependencies available to use.

Step 2: Add Logging

# Set up basic logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
                    level=logging.INFO)

This will enable logging, so that we’ll be able to debug the bot if needed. It might not seem like much, but logging can help uncover tricky bugs.

Step 3: Add Telegram API token

Now it starts to get interesting. You need an API key to talk to the Telegram Bot API. How do you get one? Talk to @BotFather on Telegram, and if you need help, see how to use BotFather.

# This is the token for the Telegram Bot API.
updater = Updater(token='<token>')
dispatcher = updater.dispatcher

If you have your token, add it in like so:
updater = Updater(token='123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11')

Step 4: Add Algorithmia Token

Now we configure Algorithmia:

# You can find your Algorithmia token by going to My Profile > Credentials
client = Algorithmia.client('API TOKEN HERE')
# The algorithm we'll be using
algo = client.algo('nlp/Summarizer/0.1.3')

So, if your API token is YWxnb3JpdGhtaWEgcm9ja3M (just an example):
client = Algorithmia.client('YWxnb3JpdGhtaWEgcm9ja3M')

Step 5: Hello, Bot!

Let’s get our bot to greet its users. It’s a simple function that gets called whenever someone sends our chatbot /start (which happens automatically when someone starts chatting with your bot). Complicated as it seems, it’s pretty simple:

def start(bot, update):
    # Your bot will send this message when users first talk to it, or when they use the /start command
    bot.sendMessage(chat_id=update.message.chat_id, 
    text="Hi. Send me any English text and I'll summarize it for you.")

So whenever someone starts chatting with our bot, it will say hi! To fully make this work, enable the /start command. If the message contains only text, then we also call the summarize_handler, followed by our dispatcher.

# This enables the '/start' command
start_handler = CommandHandler('start', start)
# Summarize all the messages sent to the bot, but only if they contain text
summarize_handler = MessageHandler([Filters.text], summarize)

# dispatcher.add_handler(summarize_handler)
dispatcher.add_handler(start_handler)

updater.start_polling()

Now, let’s go ahead and try out our chatbot by using: python3 bot.py

Step 6: Add Summary Algorithm

This is cool and all, but our bot doesn’t summarize anything yet. Luckily, Algorithmia and python-telegram-bot combined make this super easy:

def summarize(bot, update):
    try:
        # Get the text the user sent
        text = update.message.text
        # Run it through the summarizer
        summary = algo.pipe(text)
        # Send back the result
        bot.sendMessage(chat_id=update.message.chat_id, 
        text=summary.result)
    except UnicodeEncodeError:
        bot.sendMessage(chat_id=update.message.chat_id, 
        text="Sorry, but I can't summarise your text.")

We’ll finish this bot up by adding our summarizer_handler and add_handler lines, which will summarize our messages, and send them to the chatbot.

# This enables the '/start' command
start_handler = CommandHandler('start', start)
# Summarize all the messages sent to the bot, but only if they contain text
summarize_handler = MessageHandler([Filters.text], summarize)

dispatcher.add_handler(summarize_handler)
dispatcher.add_handler(start_handler)

updater.start_polling()

And that’s it!

Conclusion

Our Telegram chatbot that summarizes text is ready to go. We’re hosting it on Digital Ocean. Get the complete code sample on GitHub, where you can create a chatbot for yourself. Remember to use the promo code “summarizer” to get an additional 5,000 credits when you sign up for Algorithmia.

We could have added additional intelligence to our chatbot by using other microservices to analyze the text for sentiment, automatically generated topic tags, or checked our text for profanity.

Your Python file should like this:

# Import dependencies
from telegram.ext import Updater
import logging
import Algorithmia
from telegram.ext import CommandHandler
from telegram.ext import MessageHandler, Filters

# Set up basic logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
                     level=logging.INFO)

# This is the token for the Telegram Bot API.
# See https://core.telegram.org/bots#3-how-do-i-create-a-bot
# and https://core.telegram.org/bots#6-botfather
updater = Updater(token='')
dispatcher = updater.dispatcher

# You can find your Algorithmia token by going to My Profile > Credentials
client = Algorithmia.client('')
# The algorithm we'll be using
algo = client.algo('nlp/Summarizer/0.1.3')

def start(bot, update):
    # Your bot will send this message when users first talk to it, or when they use the /start command
    bot.sendMessage(chat_id=update.message.chat_id, 
                    text="Hi. Send me any English text and I'll summarize it for you.")

def summarize(bot, update):
    try:
        # Get the text the user sent
        text = update.message.text
        # Run it through the summarizer
        summary = algo.pipe(text)
        # Send back the result
        bot.sendMessage(chat_id=update.message.chat_id, 
                        text=summary.result)
    except UnicodeEncodeError:
        bot.sendMessage(chat_id=update.message.chat_id, 
                        text="Sorry, but I can't summarise your text.")

# This enables the '/start' command
start_handler = CommandHandler('start', start)

# Summarize all the messages sent to the bot, but only if they contain text
summarize_handler = MessageHandler([Filters.text], summarize)

dispatcher.add_handler(summarize_handler)
dispatcher.add_handler(start_handler)

updater.start_polling()