Ro-BOT – Personal Assistant with Telegram & Arduino.

Cover-en

Hello programming folks,

Today I’ll explain 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 Whats app (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 allowing the users to send messages through a secret chat that uses auto destructive messages. It is also possible to send files with any extension (very handy specially when it is necessary to send files such as .pdf, .gif, .rar).

The initial idea for this 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 basically a Telegram account controlled by a software. So how about creating our own bot?

Let’s begin!

 

 

Baby steps first. The first step is 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.

 

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.

 

 

newbot

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

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. 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.glance2(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.notifyOnMessage(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 assistent.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).

 

 

chat

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.

 

 

Untitled-Sketch-2_bb-1024x970

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);
    }
  
}

 

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.glance2(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.notifyOnMessage(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!

Because Telegram supports the developers there are tens of bots available in the internet (with the code available!).
Some of those will be linked below together with some interesting topics

Did you enjoy creating your bot? What ideas would you implement in your bot? Go ahead create your bot and share with us how did it go.

 

Leave a Reply

Your email address will not be published. Required fields are marked *