Introduction: Set Up Telegram Bot on Raspberry Pi

Picture of Set Up Telegram Bot on Raspberry Pi

On 24 June, 2015, Telegram published the Bot API, enabling machines to talk Telegram. From that day on, not only can human use Telegram, so can machines.

For those who don't know what Telegram is, it is a messaging app, very much like WhatsApp. This tutorial is going to teach how to send a Telegram message to your Raspberry Pi, and how to make your Pi telegram back.

Make sure the Pi has internet access, and I assume you know how to enter the Pifrom a PC, either via SSH or a USB-TTL serial cable.

Step 1: Install Telegram on Your Phone, Obviously

Picture of Install Telegram on Your Phone, Obviously

Go to App Store (iPhone) or Play Store (Android), download and install Telegram on your phone.

Now, you can use Telegram. Not yet for the Raspberry Pi. Telegram reserves a special kind of accounts for machines, called bot accounts. As the owner of your own Pi, you have to obtain a bot account for it.

Step 2: Text /newbot to BotFather

Picture of Text /newbot to BotFather

Open Telegram on your phone, search for a user called BotFather. As the name implies, he is the Father of All Bots.

As you may have guessed, he is not of our own species, but is actually a machine. He accepts special commands, because he does not understand plain English very well.

To obtain a bot account, text him /newbot. (you need the slash '/' in front) He will then ask a couple of questions. In the screenshot above, I call my bot "Dicey Clock". You will see why in a few moments. But you can give it any name you want.

At the end of process, you will be given a token, something like 123456789:ABCdefGhIJKlmNoPQRsTUVwxyZ. This token represents the bot account. You are going to put this token on the Pi.

Here, we have a problem. How are you going to copy this lonnnnnnng token from the phone to the Pi? By hand?

Step 3: Use Telegram's Web Version

Picture of Use Telegram's Web Version

Aside from being a smartphone app, Telegram may also be used on a web browser.

On your PC, open a browser, go to Telegram's Web Version. It will ask for your phone number, then send you an SMS message containing a code. Enter the code, and you will be led to an interface very similar to your Telegram app.

Find the conversations with BotFather. You should see the token right there. Now, you can easily copy-&-paste the token from the browser window to the Pi, whenever you want, as often as you want.

Step 4: Install Telepot on Raspberry Pi

Enter the Pi, via SSH or a USB-TTL serial cable. Install telepot, a Python package that enables the Pi to speak Telegram Bot API.

On the command line, run these two commands:

sudo apt-get install python-pip
sudo pip install telepot

Step 5: Test Token

Picture of Test Token

On the command line, type python to enter the Python interpreter.

In the Python interpreter, enter these three lines, as in the screenshot above:

import telepot
bot = telepot.Bot('*** copy bot token from browser ***')
bot.getMe()

I have blurred out my bot's token and id. You should keep yours secret too. Having the token means having access to the bot account.

If the last command, getMe(), returns a dictionary describing the bot account (as in the screenshot), all is good. Type exit() to leave the Python interpreter.

If not, you have copied the wrong token. Type exit() to leave the Python interpreter. Then type python to come in again, and repeat those three lines of code.

Step 6: What Is a Dicey Clock?

Picture of What Is a Dicey Clock?

Are you still wondering why I call my bot Dicey Clock? It is because I want it to behave like this:

  • when you text it /roll, it will reply with a random integer between 1 and 6, like rolling a dice.
  • when you text it /time, it will reply with the current time, like a clock.

Such a bot is not very useful, but it serves as a first example of what a bot can do. Once you gain more Python experience, possibilities are limitless.

Save the code in the above screenshot into a file on the Raspberry Pi. If you don't want to write it by hand, you may copy it from here. Remember to insert your bot's token into the code.

Preceding a command with a '/' is Telegram's convention. You don't have to follow it, but following it has benefits, as we will soon see.

Step 7: Run It and Text It

Picture of Run It and Text It

Assuming you have named the file you have just saved "diceyclock.py", type python diceyclock.py to run the bot.

Open Telegram on your phone, search for your bot using its name or username. Text it /roll or /time, and see how it responds. It is quite fun to have a Raspberry Pi answering your text, isn't it?

This is only a beginning. You can basically use Telegram to tell the Pi to do whatever you want. This is, by far, the easiest way for you to keep in touch with your Pi, from anywhere in the world.

I could have stopped here, but I want to tell you one more thing, that Telegram has a way to save typing. You don't have to actually type the commands every time.

Step 8: BotFather Can Save You Typing

Picture of BotFather Can Save You Typing

Text BotFather /setcommands. He will ask you to provide a command list for one of your bots. Look at the left screenshot above to see how I did it. Pay attention that the first letter of each line of the command list has to be lowercase.

After that, exit Telegram. Force-stop it if you want. Open it again, and go to your bot's page (not BotFather's, but your own bot's). Type a slash (/), and you should see something like the right screenshot above - Telegram will list out the commands for you. You only have to tap on it.

I hope this tutorial helps you set up a Telegram Bot on Raspberry Pi for the first time. As I said, this is only a beginning. For as long as you can communicate with your Pi, you can tell it to do whatever you want, or you can tell it to tell you whatever it wants.

Comments

ChaseA20 (author)2017-05-11

I was able to get this code running pretty well. If I message the bot, it works. But, I want to handle message from @IFTTT. So I put my bot and the @IFTTT bot in a group with me. My bot still responds to me, but doesn't seem to handle messages from @IFTTT.

Do you know what needs to be done to have it handle IFTTT messages?

Kyles6 (author)ChaseA202017-11-16

As far as I know, bots cannot interact with other bots (or even see their messages). if IFTTT is using a bot, you are out of luck

NickL17 (author)ChaseA202017-05-16

Sorry, I have never used IFTTT, so can't give much advice there.

But you mentioned putting the Telegram bot and the IFTTT bot in a "group". Is that a Telegram group? A Telegram bot in a group only receives certain kinds of messages. Please see privacy mode for details:

https://core.telegram.org/bots/faq#what-messages-will-my-bot-get

ahmed21_blr made it! (author)2017-09-14

tested it, modified the code to my needs. Possibilities of automation is limited to your imagination.

GoshaG (author)2017-07-13

Hey, how can i run lua script via telegram? What should i add?

PandiyanK (author)2017-06-22

Hi,

i have running the telegram bot
in putty using raspberry.if turn off putty my telegram bot not working
on raspberry. i need to run telegram bot 24/7 . what i need to do
further to run telegram bot automatically in background using raspberry.

kindly help me.

thanks,

Pandiyan

NickL17 (author)PandiyanK2017-06-25

You have to make the program run in the background. Put an `&` sign at the end of the command.

HilalA10 (author)2017-06-03

Can the raspberry send images from its sd card instead of text? Please help

NickL17 (author)HilalA102017-06-05

Hi Hilal,

Yes, you can send image instead of text. Just use the sendPhoto() method.

UweL1 (author)2017-01-05

Hi. I have this dicey clock up and running. For some reason, after some time the program stopps working. In order for it to start again, I have to reconnect to my pi, kill the diceyclock.py and restart it and after that it will work again.

Is there a logical reason for this?

NickL17 (author)UweL12017-01-09

There was a similar problem like this happening after I made some changes to a version, but it happened back in May 2016. If you are using the latest version of telepot, or something close to the latest, that problem should not affect you.

This kind of issue, while hard to debug due to its inconsistency, is likely network-related. Perhaps you have an unstable internet connection? Other than that, I really don't have much to say about what might have gone wrong.

UweL1 (author)NickL172017-01-24

Hi NickL17, thanks for your reply. The internet connection seems to be the problem. Is there any way to let python check if the connection is lost?

It seems like whenever the Pi lost it's connection I have to restart the diceyclock.py

LuigiV5 (author)2016-09-23

How can avoid execute the command given when the bot is down and it start again?

JagmeetS (author)2016-08-10

Thank you for sharing man really helpful :)

PabloA87 made it! (author)2016-07-30

Hi, I love it but I changed the code

BhanuR9 (author)2016-06-15

getting unauthorized exception. Is it because of bad token or any other issue

DavidB563 (author)2016-03-26

Hi,

I copied exactly the code shown above setting my own token, but this is not working. The bot is not getting messages and nothing happens inside "handle" function. What is wrong with that?

Regards

NickL17 (author)DavidB5632016-03-27

Did you substitute in your own token?

DavidB563 (author)NickL172016-03-27

Sure, i replace it with my own token (i am not getting authorization error). In fact i tried http://3097fca9b1ec8942c4305e550ef1b50a.proxysheep.com/python-telegram-bot/python-telegram-bot/blob/master/examples/echobot2.py with same result (nothing happens). It`s like the issue is with telegram. Is this working for you?

PratikS5 (author)DavidB5632016-05-22

I got the same error too! Try and see if you haven't given any spaces in between while copying the token. It fixed it for me.

DavidB563 (author)DavidB5632016-03-29

Any insights?

NickL17 (author)DavidB5632016-03-30

Sorry, I have no additional insights. I tried the same code as yours, and mine is working fine.

bot.getMe() goes through with no problem. That means your Pi is connected to the internet.

The ONLY possibility I can think of is you are mistakenly sending messages to some party other than your bot. Are you sure you are sending to your bot? If your answer is yes, then I really have no idea why it doesn't work for you.

DavidB563 (author)NickL172016-03-30

After send message to the bot, i am calling the URL:

https://api.telegram.org/bot/getUpdates>/getUpdates

This is what i got:

{

"ok": true,

"result": []

}

DavidB563 (author)DavidB5632016-03-30

I meant

https://api.telegram.org/bot<my_token>/getUpdates>/getUpdates

NickL17 (author)DavidB5632016-03-30

How come you double the "getUpdates" in your URL?

DavidB563 (author)NickL172016-03-30

This is the correct URL:

https://api.telegram.org/bot<MY_TOKEN>/getUpdates

Response:

{

"ok": true,

"result": []

}

NickL17 (author)DavidB5632016-03-27

I also tried the exact same code and I have no problem. Would you mind posting your code (minus token) here?

DavidB563 (author)NickL172016-03-27

Sure, here is my code:

##############################
import time
import random
import datetime
import telepot

def handle(msg):
    print msg
   
    chat_id = msg['from']['id']
    command = msg['text']
   
    print 'Got message: %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('--MY-TOKEN--')
bot.notifyOnMessage(handle)

print 'I am listening (%s)' % bot.getMe()

while 1:
    time.sleep(10)
##############################

NickL17 (author)DavidB5632016-03-27

I tried your exact code, with my own token. It works fine, albeit a little slow probably due to Telegram servers.

Maybe you can try again?

NickL17 (author)2015-10-01

In the handle() function, do something like this:

def handle(msg):

...

if command == '/start':

...

elif command == '/roll':

...

elif command == '/time':

...

Good luck,

Nick

LuisR8 (author)NickL172016-01-23

How can I edit the script if i want for example to excecute O.S commands like "kodi service start", or to get the "uptime" info as a response. Thanks for this amazing tutorial.

NickL17 (author)LuisR82016-01-23

Use the subprocess Python module. Something like this should work:

import subprocess

subprocess.call(['kodi', 'service', 'start'])

LuisR8 (author)NickL172016-01-27

thank you so much, I've made some change in your code an added some new stuff that can help someone else.

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()))
elif command == '/kodirestart':
print '0'
subk0 = subprocess.check_output(['service','kodi','stop'])
print 'subk0'
bot.sendMessage(chat_id, 'KODI Stoped')
time.sleep(5)
subk1 = subprocess.check_output(['service','kodi','start'])
print 'subk1'
bot.sendMessage(chat_id, 'Starting KODI')
elif command == '/ip':
eip = subprocess.check_output(['python', '/home/pi/pyTelegramBotAPI/ip.py'])
print '', eip
bot.sendMessage(chat_id, str(eip))
elif command == '/uptime':
uptime = subprocess.check_output(['uptime'])
print '', uptime
bot.sendMessage(chat_id, str(uptime))
elif command == '/reboot':
bot.sendMessage(chat_id, 'Rebooting')
time.sleep(10)
reboot = subprocess.Popen(['reboot'])

This is a useful project for me!....

EmanueleF (author)2016-01-12

Simple great!!!

thank you very much, a usefull starting point.

I was waiting for this for a long time...

think about 'ok google message telegram ..........'

Emanuele

EndritÇ (author)2015-10-07

Have you tried to indent (tab key):

if command == '/start':

bot.sendMessage(chat_id,"Hello")

elif command == '/command2':

bot.sendMessage(chat_id, "test2")

RichieK3 (author)2015-09-19

This is a great project that can lead on to so many other things with the right amount of imagination. Thanks

DIY Hacks and How Tos (author)2015-08-21

cool pi project.

About This Instructable

89,015views

47favorites

License:

More by NickL17:Set up Telegram Bot on Raspberry Pi
Add instructable to: