Bots will conquer the world!

Logo of Facebook Github bot.

Somebody said that the future of communication will depend on the bots (virtual assistant, in other words). This statement, probably, was inspired by the current trends: we have bots in Slack, Facebook launched M (and also bots for Messenger), Skype recently announced the bot’s API, etc. Actually, in my opinion, it’s very interesting concept, and I have a lot of ideas for bots in the messengers. And I am sure that you, my dear reader, has even better and crazier (in the good sense) ideas for that beautiful future of by bots…

Thus, today I want to attract more attention to this question and give you an example of how easy it is to implement a simple working bot in the Telegram messenger with Python (since I am practicing my skills in Python).

The connection between people and bots in the Telegram is managed by HTTP requests. We will use the open-source library pyTelegramBotAPI, which handles all the communication issues and lets developer concentrate on the algorithm itself.

To program your first bot, you have to acquire the token — a unique key to get access to Telegram Bot API. You can create your bot and receive the token from the @BotFather.

Then, we can move further to the code.

First of all, you have to import the mentioned library:

import telebot

Then you can create the instance of the bot:

TOKEN = "123456789:AAAaaAAaAAAaaaaAAaaAA1aaAaaaAaAA-1a"
bot = telebot.TeleBot(TOKEN)

So, from now on, you can interact with the clients via the bot variable.

So, let’s do something easy to bring our bot online. For example, let’s add the message handler. A message handler is a function that is decorated with the message_handler decorator of a TeleBot instance.

@bot.message_handler(func=lambda message: True)
def answer_all(message):
bot.reply_to(message, "You should try image!")

And the last masterpiece to make it all work — we have to add code, which will make our program ask the Telegram server for the messages’ updates:

bot.polling()

And that’s it!

The complete code will look as following:

import telebot

TOKEN = "123456789:AAAaaAAaAAAaaaaAAaaAA1aaAaaaAaAA-1a"
bot = telebot.TeleBot(TOKEN)

@bot.message_handler(func=lambda message: True)
def answer_all(message):
bot.reply_to(message, "You should try image!")

bot.polling()

You can now try and send a message to your bot in the Telegram app. It should be working!

7 lines of code, Karl! And you are up and running! It’s fantastic, isn’t it?!

Now, you can close this tutorial and start teaching your bot on how to conquer the world. Or… you may start wondering why our bot answers with the sentence “You should try image!” -_______- (so, continue reading…)


Cool, you didn’t quit! So, let me clarifai this. Starting from the end of winter 2016, I am involved in an awesome program called Clarifai Champions, mentored by incredible sisters Cassidy and Cami!

Clarifai is an artificial intelligence company that excels in visual recognition, solving real-world problems for businesses and developers alike. The aim of this course is to prepare technology evangelists. But, to be honest, this is a topic for the separate post (and sure I will do that at the end of the program in a few weeks), and now I just want to show you how to integrate the Clarifai API into your application with a few simple lines of code.

First of all, you have to create the developer profile and add a new app in your personal account settings to get the ClientId and ClientSecret. You can easily do that in the https://developer.clarifai.com/.

Then, we have to setup a Python client for the Clarifai API. You can do this from the command line:

pip install git+git://github.com/Clarifai/clarifai-python.git

Then, we have to import that library into our app and create the instance of the client. Important note: Clarifai API tries to retrieve clientId and clientSecret from the environment variables, so, the code will look as follows:

from clarifai.client import ClarifaiApi
import os

os.environ["CLARIFAI_APP_ID"] = "<your_clarifai_app_id>"
os.environ["CLARIFAI_APP_SECRET"] = "<your_clarifai_app_secret>"

clarifai_api = ClarifaiApi() # assumes environment variables are set.

Starting from this point we can use clarifai_api to get tags for the image. The idea is next: every time the user sends an image to our bot, we will be answering with the list of tags provided by Clarifai API. Thus, algorithm is as following:

  • handle a message with the photo
  • retrieve image
  • feed image to Clarifai API and receive the class names
  • reply to the user with the list of tags

So, we have to add the following method:

@bot.message_handler(content_types=["photo"])
def answer_photo(message):
photo = bot.get_file(message.photo[-1].file_id)
photo_url = "https://api.telegram.org/file/bot{0}/{1}".format(TOKEN, photo.file_path)
result = clarifai_api.tag_image_urls(photo_url)
classes = ", ".join(result["results"][0]["result"]["tag"]["classes"])
bot.reply_to(message, classes)

A few more comments:

  • We added filter for the content type in the message handler
  • Telegram provides the image in a few resolutions, so, we take the last one as the biggest one.
  • Clarifai API returns a lot of useful data such as probabilities of the tags and a lot more, but for our simple case we need only tag names.
  • We have to add this method above the method answer_all() because all handlers are tested in the order they are decleared.

Thus, the final source:

import telebot
from clarifai.client import ClarifaiApi
import os

os.environ["CLARIFAI_APP_ID"] = "clarifai_app_id"
os.environ["CLARIFAI_APP_SECRET"] = "clarifai_app_secret"

clarifai_api = ClarifaiApi() # assumes environment variables are set.

TOKEN = "telegram_bot_token"
bot = telebot.TeleBot(TOKEN)


@bot.message_handler(content_types=["photo"])
def answer_photo(message):
photo = bot.get_file(message.photo[-1].file_id)
photo_url = "https://api.telegram.org/file/bot{0}/{1}".format(TOKEN, photo.file_path)
result = clarifai_api.tag_image_urls(photo_url)
classes = ", ".join(result["results"][0]["result"]["tag"]["classes"])
print(classes)
bot.reply_to(message, classes)


@bot.message_handler(func=lambda message: True)
def answer_all(message):
bot.reply_to(message, "You should try image!")


bot.polling()

Final thoughts

Actually, this is a view on the stadium from the top!

You can copy and paste the code above, insert your token and Clarifai credentials, start your app and you will have a working example of the telegram bot! If you managed to have it all done — congratulations! If not — I am open to the questions and will be happy to help you, dear reader! To add more features to your bot, probably, you should dive into the bot API description or official Telegram documentation, and trust me, there are a lot of exciting stuff to work with, such as inline mode, a custom markup for the response buttons, etc.!

I hope this small tutorial will bring you closer to the bot’s development, and, maybe, it will inspire you to develop a helpful bot which thousands of people will use(including me :P)!

And if you find this post useful, feel free to follow me on Medium! I will do my best to produce the good content! Also, I will appreciate the share of this post with your friends.