July 17, 2016 6:16 pm

Bots are third-party applications that run inside Telegram. Users can interact with bots by sending them messages, commands and inline requests. You control your bots using HTTPS requests to Telegram’s bot API.
To name just a few things, you could use bots to:
At the core, Telegram Bots are special accounts that do not require an additional phone number to set up. Users can interact with bots in two ways:
Messages, commands and requests sent by users are passed to the software running on Telegram’s servers. Their intermediary server handles all encryption and communication with the Telegram API for you. You communicate with this server via a simple HTTPS-interface that offers a simplified version of the Telegram API. Telegram calls that interface their Bot API.
A detailed description of the Bot API is available on this page »
There’s a… bot for that. Just talk to BotFather (described below) and follow a few simple steps. Once you’ve created a bot and received your authorization token, head down to the Bot API manual to see what you can teach your bot to do.
You may also like to check out some code examples here »
How are bots different from humans?
BotFather is the one bot to rule them all. It will help you create new bots and change settings for existing ones.
On Telegram, open the @BotFather profile, and start to talk with “him”. You can open the conversation by clicking here. If the screen remains empty, update your Telegram client, or write “/start”
The BotFather will ask you to read a manual, but it’s not necessary!
Use the /newbot command to create a new bot. The BotFather will ask you for a name and username, then generate an authorization token for your new bot.
The name of your bot will be displayed in contact details and elsewhere. Say we call it ‘OrangePi Picaxe’
The Username is a short name, to be used in mentions and telegram.me links. Usernames are 5-32 characters long and are case insensitive, but may only include Latin characters, numbers, and underscores. Your bot’s username must end in ‘bot’, e.g. ‘tetris_bot’ or ‘TetrisBot’. In this tutorial give an appropriate name such as ‘PicaxeBot’.
BotFather will give you an HTTP API token, such as:
87782160:AAGWyE1JSEa8qNqvv4EZzcQQ4kWo7rokMKM
The token is required to authorize the bot and send requests to the Bot API.
If your existing token is compromised or you lost it for some reason, use the /token command to generate a new one.
The remaining commands are pretty self-explanatory:
Please note, that it may take a few minutes for changes to take effect.
So your bot is now ready.
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.
We are going to install Telepot on Orange Pi Lite (OPL) Wifi, assuming that you have OPL duly functioning with latest Armbian Jessie desktop, and with Wifi connected to your router.
First we need to install the sufficient libraries for constructing the Personal Assistant.
![]()
Next:
Once Telepot is installed we are ready to write our first bot code.
The following simple bot does nothing but accepts two commands:
– `/roll` – reply with a random integer between 1 and 6, like rolling a dice.
– `/time` – reply with the current time, like a clock.
Write the code at command prompt:
import time
import random
import datetime
import telepot
def handle(msg):
chat_id = msg['chat']['id']
command = msg['text']
print 'Got command: %s' % command
if command == '/roll':
bot.sendMessage(chat_id, random.randint(1,6))
elif command == '/time':
bot.sendMessage(chat_id, str(datetime.datetime.now()))
bot = telepot.Bot('Token obtained previously')
bot.message_loop(handle)
print 'I am listening ...'
while 1:
time.sleep(10)
Run diceyclock.py at command prompt python diceyclock.py and response will be I am listening…:
![]()
You can now try the two commands /roll and /time on Telegram:
We want the Picaxe18M2 to be able to communicate by serial connection with Orange Pi Lite Wifi
Wrtie and upload the following code in Picaxe 18M2:
main:
setfreq m8
serin C.7, T9600_8, b0
if b0 = "a" then 'looks for "a"
high B.1 'turns on the output
else if b0 = "b" then 'looks for "b" (off)
low B.1 'turns off the output
else if b0 = "c" then 'looks for "c"
high B.2 'turns on the output
else if b0 = "d" then 'looks for "d" (off)
low B.2 'turns off the output
else if b0 = "s" then 'looks for "s" (status)
gosub get_status 'calls up "get_status" subroutine below
endif
goto main
get_status:
let b0 = pinB.1 'checks status of pin B.1
let b1 = pinB.2 'checks status of pin B.2
gosub get_temp 'calls temp subroutine below
gosub get_lumin 'calls lumin subroutine below
serout B.7, T9600_8, (#b0, 32, #b1, 32, #b2, 32, #b3, 13, 10)
return
get_temp:
readtemp 2, b2 'reads the temperature
return
get_lumin:
readadc 0, b3 'reads adc value on In2
return
We will now add connections to HC-05 Bluetooth Module. For this we use Inputs Test Points and Output Test Points with headers (image shows the headers already soldered):

Now connect up HC-05 module to the board as shown:
We have used LogiLink USB Bluetooth V4.0 dongle but it can be any other as most seem to be recognised by Armbian’s Debian Jessie OS for Orange Pi Lite Wifi.
A possible result duly boxed is as follows (I also added a heat-sink on the ARM microcontroller as it tends to heat up):
Armbian’s is already Bluetooth-ready. You can chech the Buletooth dongle has been recongised by following command, and a possible response is shown below:
![]()
We now test the status of Bluetooth:
A possible and likely result will be:
We are now to pair our dongle to HC-06 module on AXE056 board.
The command bluetoothctl will allow us to pair to HC-05
Now run the following sequence of commands:
power on
and next:
scan on
You will see all the Bluetooth devices in neighborhood including HC-05. Copy the MC address of HC-05:
And now the following sequence:
agent on
default-agent
pair <MAC address of HC-05>
A typical response will be:
Note that MAC address has been blurred. Pin code of H-05 is 1234 (this can be changed but we are not going to show here how, you can find information on the Internet how to do it
trust <MAC address of HC-05>
exit
Now create a RFCOMM configuration file in command prompt
# RFCOMM configuration file.
rfcomm0 {
# Automatically bind the device at startup
bind yes;
# Bluetooth address of the HC-05
device XX:XX:XX:XX:XX:XX;
# RFCOMM channel for the connection
channel 1;
# Description of the connection
comment "HC-05";
}
We are now ready to bind this at startup by editing and writing into rc.local with the following command:
Add just before exit 0
rfcomm bind 0 xxxxxxxxxxxx 1
Where xxxxxxxxxxxx is the MAC address of HC-05.
Now reboot the Orange Pi Lite Wifi with command reboot, and afiter rebooting if you check under dev:
You will see RFCOMM0
Write pa.py with command nano pa.py
# pa.py
import telepot, serial, time
ser = serial.Serial('/dev/rfcomm0',
baudrate=9600,
timeout=0
)
degree = unichr(176)
def handle(msg):
chat_id = msg['chat']['id']
command = msg['text']
if command == '/hello':
bot.sendMessage(chat_id, "Local status @Aliatron")
elif command == '/status':
ser.flushInput()
ser.flushOutput()
ser.write(b's')
time.sleep(1)
data = ser.readline()
processed_data = data.split(' ')
data1 = str(processed_data[0])
data2 = str(processed_data[1])
data3 = str(processed_data[2])
data4 = str(processed_data[3])
if data1 == '1':
data10 = "Fan ON"
elif data1 == '0':
data10 = "Fan OFF"
if data2 == '1':
data20 = "Alarm ON"
elif data2 == '0':
data20 = "Alarm OFF"
bot.sendMessage(chat_id, data10 + " ; " + data20 + " ; Temp: " + data3 + degree + "C ; Lumi: " + data4)
elif command == '/fanon':
ser.flushInput()
ser.flushOutput()
ser.write(b'a')
time.sleep(0.25)
bot.sendMessage(chat_id, "Fan: ON")
elif command == '/fanoff':
ser.flushInput()
ser.flushOutput()
ser.write(b'b')
time.sleep(0.25)
bot.sendMessage(chat_id, "Fan: OFF")
elif command == '/alaon':
ser.flushInput()
ser.flushOutput()
ser.write(b'c')
time.sleep(0.25)
bot.sendMessage(chat_id, "Alarm: ON")
elif command == '/alaoff':
ser.flushInput()
ser.flushOutput()
ser.write(b'd')
time.sleep(0.25)
bot.sendMessage(chat_id, "Alarm: OFF")
else:
pass
# Bot API
bot = telepot.Bot('Token obtained previously')
# bot.notifyOnMessage(handle)
bot.message_loop(handle)
print 'I am listening ...'
# Listen to the messages
while 1:
time.sleep(10)
Now run the Personal Assistant with the command python pa.py and response will be I am listening…:
![]()
You can now try the several commands /fanon, /fanoff, /alaon, /alaoff /status on Telegram:
AXE056 board will show LEDs 1 (yellow) and 2 (red) switching ON and OFF according to the commands you will send with Telegram.
The command /status will tell the state of the LEDs, and will give you extra information on local temperature read by DS1820 and luminosity read by LDR on the same AXE056 board.
To run pa.py as a daemon, you can use the following command:
nohup python pa.py &
The response will be similar to:
and then write exit
A special thank you to the Telegram Messaging team for offering us all Telegram services, and most recently the usage of Telegram Bots!
Armbian offers Debian Jessie for Orange Pi Lite Wifi. There was nothing special, and very easy, to get the Debian Jessie OS on Orange Pi Lite. As a thank you, I donated a small amount to the Armbian.
Also a thank you to for inspiration of this project to:
I have added a heatsink and a fan to the Orange Pi Lite Wifi set up. It was heating up before to temperatures as high as 64ºC (of course in plastic box without ventilation).
Now Orange Pi Lite Wifi works at arounf 29ºC.
I know it is a bit of overkill. The following images depict what has been done.

We have connected Telegram to a real world device (a PIC micrcontroller, Picaxe is after all a PIC) allowing us to use it to control, and find status of the pins on the PIC device. We can add lots of others features to this basic Personal Assistant bot such as:
It is not necessary Orange Pi Lite Wifi to do this project. You can do it easily with Raspberry Pi, or Banana Pi.
If I can be any assistance in your project with Telegram inspired on my project, please write here in comments, and I will do my best to reply. Also, if you do anything different with Telegram inspired on my work, please share links here.
Also if there is anything wrong with this please let me know too.
Posted by Tayeb
Categories: Uncategorized
Tags:
Mobile Site | Full Site
Get a free blog at WordPress.com Theme: WordPress Mobile Edition by Alex King.