Introduction: Personal Assistant With Telegram & Arduino.

Hello folks!
A few months ago I heard about a project that used an instant messenger bot to create a system that would automatically process and organize pizza's orders sent by the costumers via Whats app. I was like...wow! Give that man a cookie!
So I took some time to explore around bots and how to code them. With a little bit of research I discovered that using a Telegram bot would make it easier for me to program my bot since there is a lot of support for the makers that have interest in bots. And Because for this project the Telegram app is used to send commands there is zero android programming

Check out the project working! :D

Step 1: First Things First

This instructable is about how to create and use a personal assistant (bot) using the Telegram app. For those of you that never heard about it, the Telegram app is very similar to WhatsApp (even better… cough cough) however there are a few (and meaningful) differences. Telegram uses an open source code created with a huge focus on security and privacy.

The initial idea for using this bot project was to create a solution that would allow me to talk to my house (How is the temperature in my room?, Turn on the lights; Is the door closed?, DEFCON4 DOUBLE TAKE!!). It isn’t unusual to see projects working with home automation using Arduino, Wi-Fi shields (or Ethernet) but I didn’t want to cross that known path again because what would be easier than having all the power in a simple chat? So I decided to create my bot! All this talk about bots but…. At the end of the day, what is a Telegram bot? A bot is a Telegram account controlled by a software. So how about creating our own bot?

Let’s begin!

Step 2: Installing Telegram

To create a Telegram account. Just install the app in your device (Playstore/iTunes/TelegramDesktop). Easy peasy right? Just sign up using your cellphone number and you would be good to go.

Once your account exists start a conversation with @BotFather (The one bot to rule them all). BotFather is a sort of main bot that allows users to create new bots and to start a conversation with him just follow the link https://telegram.me/botfather or search for botfather in your contacts and start a conversation. Once the conversation is open there will be a button “/start” at the bottom of the chat.

Step 3: Botfather

After starting a conversation with BotFather it will send the available commands to talk interact with BotFather. Because we want to create a bot let’s go ahead and send:

“/newbot” As you can see in the image below, BotFather will require some information about our bot. (1) How the bot will be called and (2) what is the bot username.

If everything worked well, the new bot was born. The bot is mainly ready to send and receive messages from the bot.

Step 4: Installing Tools (LINUX)

Now that the bot is ready to receive some instructions, we have to keep in mind that in order to program the bot some tools will be needed. Here is a list of the commands necessary for the installation of the tools:

$ sudo apt-get install python3
$ sudo apt-get install python3-pip
$ sudo pip3 install telepot
$ sudo pip3 install telepot –upgrade # UPGRADE

The commands above will install the telepot python module for those using Linux.

Step 5: Installing Tools (WINDOWS)

For windows users you can download and install python by accessing the link here.

Once you have installed the python (I recommend the version 3.4) the next step is to install the Telepot package you should open a terminal and insert the following command:

py -m pip install telepot

You should get an output as follows:

Step 6: Python Code

Telepot is a python API to work with Telegram bots. For more details, documentation and some codes about the API check out the GitHub here.

Let’s start with a hello world of the bot’s world. We’ll build a bot that will respond to the “/hello” message.

#!/usr/bin/python
import telepot, time

def handle(msg):
	content_type, chat_type, chat_id = telepot.glance(msg)

	if (content_type == 'text'):
		command = msg['text']
		print ('Got command: %s' % command)

		if  '/hello' in command:
			bot.sendMessage(chat_id, "Hello, do you have any commands for today?")

# Creates a bot using the token provided by BotFather
bot = telepot.Bot('16843XXXX:AAGGq99MLWOknqCx66V5s2XXXXXXXXXXXXX')

# Add the handle function to be called every new received message
bot.message_loop(handle)

# Wait for new messages
while 1:
	time.sleep(20)

Be aware that in your own code you have to change the token in the line 15 by the token provided by botFather. Save the file the name assistant.py.

Run the code though your terminal using

$ python3 assistant.py

Once the code is kicking it is possible to test our bot by sending a message through any device to our bot (you can find him using the username that was provided to botFather earlier).

Step 7: More...more More!

The bot was able to receive messages and reply to an specific message as defined in the code. In the background the python code was handling all the inputs and outputs of the operation. As we can see the code for controlling a bot is pretty straightforward.

Now that the bot is working, how about enhancing some of it’s abilities? Using an Arduino and a relay I decided to test if the bot would be able to control a lamp remotely in my house and here is the result. For this idea the following schematic was used to connect an Arduino to a relay module and a lamp.

The code for the Arduino is very simple:

const int lightPin=6;
unsigned int data;
void setup() {
  Serial.begin(9600);
  pinMode(lightPin,OUTPUT);
  
}

void loop() {
    while(Serial.available()>0){
      data=Serial.read();
        if(data=='Y')digitalWrite(lightPin,HIGH);
        if(data=='N')digitalWrite(lightPin,LOW);
    }
  
}

Step 8: Controlling the Lamp

For this setup the serial port was used to interface the bot code and the Arduino. The code will send the character “Y” to the Arduino for turning on the relay module and “N” to turn off the relay module turning off the light.

Once the Arduino is properly programmed and connected it is time to workout the code for the bot.

#!/usr/bin/python
import telepot, time, serial
ser = serial.Serial('/dev/ttyACM0', 9600)

def handle(msg):

	userName = msg['from']['first_name']+" "+msg['from']['last_name']

	content_type, chat_type, chat_id = telepot.glance(msg)

	if (content_type == 'text'):
		command = msg['text']
		print ('Got command: %s' % command)

		if  '/hello' in command:
			bot.sendMessage(chat_id, "Hello "+userName+", how are you doing today?")

		if '/lamp_on' in command:
			ser.write(b'Y')
			bot.sendMessage(chat_id, "Lamp ON")

		if '/lamp_off' in command:
			ser.write(b'N')
			bot.sendMessage(chat_id, "Lamp OFF")

# Create a bot using the token given by BotFather
bot = telepot.Bot('16843XXXX:AAGGq99MLWOknqCx66V5s2XXXXXXXXXXXXXX')

# Add handle function to be called every received message.
bot.message_loop(handle)

# Wait for new messages
while 1:
	time.sleep(20)

The serial module has to be imported in order to communicate the python code with the Arduino serial port. It is important to note that the line #3 is specific to the port that the Arduino is connected and this line must be modified accordingly to the necessity.

Save the code and it will be ready to be tested!

Step 9: Don't Stop Me Noooowww

For this project, as an example, I could turn on and off a lamp...but it is possible to extend this project "To infinity…and beyond"! My idea to extend this project is to implement a security system controlled by a raspberry pi and I would interface this system by using a Telegram chat. Doing that it is possible to request and send information to my house such as security camera images, temperature, security camera vigilance, and much more.

If you are interested and want to learn more about bots, there are tens of bots available on the internet (with the code available!).
Some of those will be linked below

You can check out a portuguese version of this project at

Full Spectrum Laser Contest 2016

Participated in the
Full Spectrum Laser Contest 2016

Hack Your Day Contest

Participated in the
Hack Your Day Contest