Introduction: Personal Assistant With Telegram & Arduino.

Picture of 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

Picture of 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

Comments

AugustoF20 (author)2017-11-13

Hi

Is it possible to do with arduino uno and ethershield?

ansari400 (author)2017-10-28

Hi Sir

Hello, at line ser=serial.Serial('/dev/ttyACM0',9600)

How I replace my Arduino uno Port COM12

thanks

SalehS7 (author)2017-08-25

Thanks ❤️

AlexD363 (author)2017-06-18

hi excuse me,i have a problem because i don't have the library for serial communication, so, whats is the name to that library who you use in the example? thanks

jclmdt (author)2017-03-01

I tried running the assistant code with the command '$ python3 assistant.py' in cmd but it return an error " '$' is not recognized as an internal or external command, operable program or batch file".

I already set python in the PATH beforehand.

When i tried to execute the command 'python assistant.py' instead, there is an 'ImportError: No module named 'telepot' '. However, I already install telepot according to the previous step.

Can somebody please help me!!!

superwario (author)jclmdt2017-06-02

Hi @jclmdt
I had the same issue, alternatively, you can open the "assistant.py" file in Python, and then click on Run > Run Module or hit F5

jclmdt (author)jclmdt2017-03-19

any help???

SimonC5 (author)2017-01-11

very cool Project.

Could it be done with an arduino nano?

Thanks

racurcio (author)SimonC52017-01-17

Yes, any arduino will do.

agung.saputra94 (author)2016-04-13

Hi sir

at line ser = serial.Serial('/dev/ttyACM0', 9600)


How i know the number the port that the Arduino is connected ?

what kind Arduino you used to ?

I use arduino yun but i have no idea to find number of port

thanks , great works sir

racurcio (author)agung.saputra942016-04-16

Hello, you can check out the port that the arduino uses by using the arduino software.
Connect the arduino in the computer, open the arduino software and go to "Tools > Port"
There you can see the port that your arduino is connected.
I am using the Arduino Uno

abhijitashru (author)racurcio2016-06-05

AttributeError: 'Bot' object has no attribute 'messgae_loop'

Got this error when executing assistant.py

how to resolve

agung.saputra94 made it! (author)racurcio2016-04-16

Here my error

Got command: /foto

Traceback (most recent call last):

File "/usr/lib/python2.7/site-packages/telepot-6.8-py2.7.egg/telepot/__init__.py", line 338, in handle

callback(update['message'])

File "assistant_edit.py", line 22, in handle

ser.write(b'F')

File "/usr/lib/python2.7/site-packages/serial/serialposix.py", line 547, in write

raise SerialException('write failed: %s' % (v,))

SerialException: write failed: [Errno 5] Input/output error

any idea sir ?

i use port ttyATH0 baud 115200

agung.saputra94 (author)2016-04-16

I have error

Got command: /foto

Traceback (most recent call last):

File "/usr/lib/python2.7/site-packages/telepot-6.8-py2.7.egg/telepot/__init__.py", line 338, in handle

callback(update['message'])

File "assistant_edit.py", line 22, in handle

ser.write(b'P')

File "/usr/lib/python2.7/site-packages/serial/serialposix.py", line 547, in write

raise SerialException('write failed: %s' % (v,))

SerialException: write failed: [Errno 5] Input/output error

SerialException: write failed: [Errno 5] Input/output error

what mean ?

agung.saputra94 (author)2016-04-16

I have error

Got command: /foto

Traceback (most recent call last):

File "/usr/lib/python2.7/site-packages/telepot-6.8-py2.7.egg/telepot/__init__.py", line 338, in handle

callback(update['message'])

File "assistant_edit.py", line 22, in handle

ser.write(b'P')

File "/usr/lib/python2.7/site-packages/serial/serialposix.py", line 547, in write

raise SerialException('write failed: %s' % (v,))

SerialException: write failed: [Errno 5] Input/output error

SerialException: write failed: [Errno 5] Input/output error

what mean ?

Robson Couto (author)2016-04-09

Awesome project!

rifqidp (author)2016-04-08

Could you mix the code with sensor PIR or sensor temperature Sir ?

Robson Couto (author)rifqidp2016-04-09

Hey, you sure can!

I guess you can send a message every time the PIR sensor is triggered or answer with the temperature. Just try it!

rifqidp (author)2016-03-28

awesome !!

DIY Hacks and How Tos (author)2016-03-19

cool project.

Thanks :)

About This Instructable

16,538views

79favorites

License:

More by racurcio:Personal Assistant with Telegram & Arduino.
Add instructable to: