loading

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

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

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

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

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?

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

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

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.

<p>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. </p><p>Do you know what needs to be done to have it handle IFTTT messages?</p>
Sorry, I have never used IFTTT, so can't give much advice there.<br><br>But you mentioned putting the Telegram bot and the IFTTT bot in a &quot;group&quot;. Is that a Telegram group? A Telegram bot in a group only receives certain kinds of messages. Please see privacy mode for details:<br><br>https://core.telegram.org/bots/faq#what-messages-will-my-bot-get
<p>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. </p><p>Is there a logical reason for this?</p>
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.<br><br>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.
<p>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? </p><p>It seems like whenever the Pi lost it's connection I have to restart the diceyclock.py</p>
<p>How can avoid execute the command given when the bot is down and it start again?</p>
<p>Thank you for sharing man really helpful :)</p>
Hi, I love it but I changed the code
<p>getting unauthorized exception. Is it because of bad token or any other issue</p>
<p>Hi, </p><p>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 &quot;handle&quot; function. What is wrong with that?</p><p>Regards</p>
Did you substitute in your own token?
<p>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?</p>
<p>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.</p>
<p>Any insights?</p>
<p>Sorry, I have no additional insights. I tried the same code as yours, and mine is working fine.</p><p>bot.getMe() goes through with no problem. That means your Pi is connected to the internet.</p><p>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.</p>
<p>After send message to the bot, i am calling the URL:</p><p>https://api.telegram.org/bot/getUpdates&gt;/getUpdates</p><p>This is what i got:</p><p>{</p><p> &quot;ok&quot;: true,</p><p> &quot;result&quot;: []</p><p>}</p>
<p>I meant</p><p>https://api.telegram.org/bot&lt;my_token&gt;/getUpdates&gt;/getUpdates</p>
<p>How come you double the &quot;getUpdates&quot; in your URL?</p>
<p>This is the correct URL:</p><p>https://api.telegram.org/bot&lt;MY_TOKEN&gt;/getUpdates</p><p>Response:<br><br>{</p><p> &quot;ok&quot;: true,</p><p>&quot;result&quot;: []</p><p>}</p>
I also tried the exact same code and I have no problem. Would you mind posting your code (minus token) here?
Sure, here is my code:<br> <br> ##############################<br> import time<br> import random<br> import datetime<br> import telepot<br> <br> def handle(msg):<br> &nbsp;&nbsp;&nbsp; print msg<br> &nbsp;&nbsp;&nbsp;<br> &nbsp;&nbsp;&nbsp; chat_id = msg['from']['id']<br> &nbsp;&nbsp;&nbsp; command = msg['text']<br> &nbsp;&nbsp;&nbsp;<br> &nbsp;&nbsp;&nbsp; print 'Got message: %s' % command<br> &nbsp;&nbsp;&nbsp;<br> &nbsp;&nbsp;&nbsp; if command == '/roll':<br> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; bot.sendMessage(chat_id, random.randint(1, 6))<br> &nbsp;&nbsp;&nbsp; elif command == '/time':<br> &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; bot.sendMessage(chat_id, str(datetime.datetime.now()))<br> <br> bot = telepot.Bot('--MY-TOKEN--')<br> bot.notifyOnMessage(handle)<br> <br> print 'I am listening (%s)' % bot.getMe()<br> <br> while 1:<br> &nbsp;&nbsp;&nbsp; time.sleep(10)<br> ##############################
<p>I tried your exact code, with my own token. It works fine, albeit a little slow probably due to Telegram servers.</p><p>Maybe you can try again?</p>
<p>In the handle() function, do something like this:</p><p>def handle(msg):</p><p>...</p><p>if command == '/start':</p><p>...</p><p>elif command == '/roll':</p><p>...</p><p>elif command == '/time':</p><p>...</p><p>Good luck,</p><p>Nick</p>
<p>How can I edit the script if i want for example to excecute O.S commands like &quot;kodi service start&quot;, or to get the &quot;uptime&quot; info as a response. Thanks for this amazing tutorial.</p>
<p>Use the subprocess Python module. Something like this should work:</p><p>import subprocess</p><p>subprocess.call(['kodi', 'service', 'start'])</p>
<p>thank you so much, I've made some change in your code an added some new stuff that can help someone else.</p><p>def handle(msg):<br> chat_id = msg['chat']['id']<br> command = msg['text']<br><br> print 'Got command: %s' % command<br><br> if command == '/roll':<br> bot.sendMessage(chat_id, random.randint(1,6))<br> elif command == '/time':<br> bot.sendMessage(chat_id, str(datetime.datetime.now()))<br> elif command == '/kodirestart':<br> print '0'<br> subk0 = subprocess.check_output(['service','kodi','stop'])<br> print 'subk0'<br> bot.sendMessage(chat_id, 'KODI Stoped')<br> time.sleep(5)<br> subk1 = subprocess.check_output(['service','kodi','start'])<br> print 'subk1'<br> bot.sendMessage(chat_id, 'Starting KODI')<br> elif command == '/ip':<br> eip = subprocess.check_output(['python', '/home/pi/pyTelegramBotAPI/ip.py'])<br> print '', eip<br> bot.sendMessage(chat_id, str(eip))<br> elif command == '/uptime':<br> uptime = subprocess.check_output(['uptime'])<br> print '', uptime<br> bot.sendMessage(chat_id, str(uptime))<br> elif command == '/reboot':<br> bot.sendMessage(chat_id, 'Rebooting')<br> time.sleep(10)<br> reboot = subprocess.Popen(['reboot'])</p><p>This is a useful project for me!....</p>
<p>Simple great!!!</p><p>thank you very much, a usefull starting point.</p><p>I was waiting for this for a long time...</p><p>think about 'ok google message telegram ..........'</p><p>Emanuele</p>
<p>This is a great project that can lead on to so many other things with the right amount of imagination. Thanks</p>
<p>cool pi project.</p>

About This Instructable

78,667views

44favorites

License:

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