Have you ever wondered what comforts a truly programmable app can give to a consumer. Many of us admire Internet of things( IOT) . So today I am going to talk about creating Personal Assistants (PA) for Telegram app, an application similar to whatsApp but fully programmable using it’s Bot API. We can pass messages to multiple devices in a click of eye. Telegram is the app which hackers likes because of it’s customization. Messaging apps should not only provide communication between humans but also should lay channels between humans and programmable machines. There are obvious advantages for programmers who use Telegram App.
- Get Github and Sentry messages directly to your app
- Get favorite tweets from Twitter
- Get updates from multiple information sources like weather or scores
- Control home appliances by sending pre-defined commands
Applications are endless. In this IOT generation you need a platform to program and Telegram API provides you that.
This tutorial will use two main ingredients.
- Telegram app
- Telepot python library
Target
Our goal is to build a PA for us using Bot API provided by Telegram app. We need to install the app
Telegram app on Google playstore
You can also have a Telegram client for your system. Mine is Ubuntu14.04. You can download all clients here.
I presume that you installed the telegram app. Now we need to create a bot for us. Telegram provides us a program called Bot Father using which we can create custom bots. Launch BotFather by visiting this link.
After adding BotFather to your chat list enter into it, you will see few options like this
now type /newbot and hit Enter. It will ask you for a name, give that. Next it will generate an API key, which we are going to use to build our Bot. Store this API key. It also gives a link to your bot. Visit that link to add it as one of your friends. Share it to others if you want to.
Telepot, a python client for Telegram
Telepot is a python client which is the REST wrapper for Telegram API. Using it we can take commands from user and compute something and give back results to the user. Now I am going to build a small bot program which does following things when below commands are given.
- /timeline -> Should fetch the latest tweets on my timeline
- /tweet=message -> Should tweet my message on Twitter
- /chat -> Should launch a virtual chat with machine
- /stopchat -> You are bored and stop chatting
These tasks might be simpler one. But you should be aware that if you know how to unleash the power of message passing between devices you can define your own custom tasks which can have greater value of application. Code for this application is at https://github.com/narenaryan/Mika
Let us build the PA
First we need to install the sufficient libraries for constructing the Virtual Assistant. I name my PA as mika.
$ virtualenv telegram-bot $ source telegram-bot/bin/activate $ pip install telepot tweepy nltk
We are installing telepot for sending and receiving messages from Telegram. NLTK for using it’s virtual chat engines. Tweepy is used for accessing twitter account through consumer keys. For now I am creating a simple bot command which returns “Hello, how are you?” when we say hello to it.
# pa.py import telepot, time def handle(msg): chat_id = msg['chat']['id'] command = msg['text'] print 'Got command: %s' % command if command == '/hello': bot.sendMessage(chat_id, "Hello, how are you?") # Create a bot object with API key bot = telepot.Bot('152871568:AAFRaZ6ibZQ52wEs2sd2XXXXXXXXX') # Attach a function to notifyOnMessage call back bot.notifyOnMessage(handle) # Listen to the messages while 1: time.sleep(10)
Run $ python pa.py
Now enter /hello in the bot channel you created. you will see the following output.
So our bot received our message and replied back to us with the greeting. It is actually the Python code running under the hood managing those tasks. Code is very simple. We need to
- Create Bot object using API key
- Create a function for handling commands and returning information
- Attach the above function to call back handler of Bot. Whenever bot receives a message this function handler executes. We can have any logic in those handlers.
You can see what all inputs you can accept and types of outputs you can send to users from bot here. telepot github link
For now let us Integrate twitter and chat engines of NLTK into our bot. We all know that NLTK comes with few chat engines like Eliza, Iesha,Zen etc. I am here using a chatbot called Iesha. Before I create a file called tweep.py for managing my tweet and timeline fetch tasks.
# tweep.py import tweepy #I prepared this class for simplicity. Fill in details and use it. class Tweet: #My Twitter consumer key consumer_key='3CbMubgpZvXXXXXXXXXX' #My consumer secret consumer_secret='Clua2xLNfvbjj3Zoi4BQU5EXXXXXXXXXXX' #My access token access_token='153952894-cPurjdaQW7bA3B3eXXXXXXXXXXXX' #My access token secret access_token_secret='r6NJ6qjPrYDenqwuHaop1eBnXXXXXXXXXXXXX' def __init__(self): self.auth = tweepy.OAuthHandler(self.consumer_key,self.consumer_secret) self.auth.set_access_token(self.access_token, self.access_token_secret) self.handle = tweepy.API(self.auth) def hitme(self,str): self.handle.update_status(str) print 'tweet posted succesfully'
Now let me finish the show with adding both chatting and Tweeting.
import telepot, time from nltk.chat.iesha import iesha_chatbot from tweep import Tweet # create tweet client tweet_client = Tweet() is_chatting = False def handle(msg): global is_chatting global tweet_client chat_id = msg['chat']['id'] command = msg['text'] print 'Got command: %s' % command if command == '/timeline' and not is_chatting: bot.sendMessage(chat_id, '\n'.join([message.text for message in tweet_client.handle.home_timeline()])) elif command.split('=')[0] == '/tweet' and not is_chatting: try: tweet_client.hitme(command.split('=')[1] + ' #mika') bot.sendMessage(chat_id, 'Your message tweeted successfully') except: bot.sendMessage(chat_id, 'There is some problem tweeting! Try after some time') elif command == '/chat': is_chatting = True bot.sendMessage(chat_id, 'Hi I am Iesha. Who are You?') elif command == '/stopchat': is_chatting = False bot.sendMessage(chat_id, 'Bye Bye. take care!') elif not command.startswith('/') and is_chatting: bot.sendMessage(chat_id, iesha_chatbot.respond(command)) else: pass # Create a bot object with API key bot = telepot.Bot('152871568:AAFRaZ6ibZQ52wEs2sd2Tp4Wcs-IXoWfA-Q') # Attach a function to notifyOnMessage call back bot.notifyOnMessage(handle) # Listen to the messages while 1: time.sleep(10)
So output screens will be like this for /chat and /tweet
For /timeline
Isn’t it funny. We can add lots of features to this basic personal assistant bot like
- Tracking time
- Scheduler and alert
- Notes taking etc
- Opening your garage gate when you push a command to bot
If you observe the code there isn’t much in that. I just used Elisha chat bot from NLTK. Used tweepy methods to fetch timeline and post a tweet. If you want to use code visit my repo.
https://github.com/narenaryan/Mika
Thanks for reading this stuff. Hope it will be helpful for you to build your own IOT.
Hello Naren arya,
Unbelievable! Great post about telegram bots. Actually that exactly what I have been searching for in a very well explained manner.
I started searching for telegram bots this morning and this is the best introduction to telegram bots so far!
Keep up the great work 😀
Rafael Acurcio.
Thanks Rafael 🙂
Inspired, and using some of your code, I am reading temperature and light level with two sensors, and switching ON or OFF a LED on a PIC (Picaxe 18m2 from Revolution Education). I also check the status of the LED whether ON or OFF.
Telegram bot is resident on a Raspberry Pi 2 that sends commands to PIC with recourse to bluetooth.
Thank you Naren Aryan.
As a follow up I’ve written a tutorial on controlling a PIC microcontroller:
https://redacacia.me/2016/07/17/telegram-bot-control-with-orange-pi-lite-wifi-and-axe056-board-with-picaxe-18m2/
Cool sir. Nice job.
Hi …
I’m using django .
whether save my pa.py ??? ( my app or my website or … )
hi
thanks for your wonderful post.
what server you used for your bot?
is it uploaded to google app engine or some thing else?
I deployed that script on my AWS account. You can use anything.
Hey, thank you very much for your insights.
Can you give an example code for the scheduler/alert function you mention?
And how can you save und reply to user specific informations/distinguish between users?
Again, thanks
For those interested like I am, there have been made changes to the method names, see also here:
https://github.com/nickoala/telepot/blob/master/CHANGELOG.md