Set Up Telegram Bot on Raspberry Pi

Published

Introduction: 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

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.

3 People Made This Project!

Recommendations

  • Woodworking Contest

    Woodworking Contest
  • Microcontroller Contest

    Microcontroller Contest
  • Make it Move Contest

    Make it Move Contest
user

We have a be nice policy.
Please be positive and constructive.

Tips

Questions

40 Comments

How to send message automatically..in telegram bot

1 reply

when i test token in pi it says connection error help plz,

i also checked internet connection and it works

pi@FAIZAN:~ $ python

Python 2.7.13 (default, Nov 24 2017, 17:33:09)

[GCC 6.3.0 20170516] on linux2

Type "help", "copyright", "credits" or "license" for more information.

>>> import telepot

>>> bot = telepot.Bot('505753216:AAFn9zYMpqrogUkyyCU-r1TtMGrQZhp3Dns')

>>> bot.getMe()

Traceback (most recent call last):

File "<stdin>", line 1, in <module>

File "/usr/local/lib/python2.7/dist-packages/telepot/__init__.py", line 503, in getMe

return self._api_request('getMe')

File "/usr/local/lib/python2.7/dist-packages/telepot/__init__.py", line 491, in _api_request

return api.request((self._token, method, params, files), **kwargs)

File "/usr/local/lib/python2.7/dist-packages/telepot/api.py", line 154, in request

r = fn(*args, **kwargs) # `fn` must be thread-safe

File "/usr/lib/python2.7/dist-packages/urllib3/request.py", line 148, in request_encode_body

return self.urlopen(method, url, **extra_kw)

File "/usr/lib/python2.7/dist-packages/urllib3/poolmanager.py", line 244, in urlopen

response = conn.urlopen(method, u.request_uri, **kw)

File "/usr/lib/python2.7/dist-packages/urllib3/connectionpool.py", line 671, in urlopen

release_conn=release_conn, **response_kw)

File "/usr/lib/python2.7/dist-packages/urllib3/connectionpool.py", line 671, in urlopen

release_conn=release_conn, **response_kw)

File "/usr/lib/python2.7/dist-packages/urllib3/connectionpool.py", line 671, in urlopen

release_conn=release_conn, **response_kw)

File "/usr/lib/python2.7/dist-packages/urllib3/connectionpool.py", line 643, in urlopen

_stacktrace=sys.exc_info()[2])

File "/usr/lib/python2.7/dist-packages/urllib3/util/retry.py", line 363, in increment

raise MaxRetryError(_pool, url, error or ResponseError(cause))

urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='api.telegram.org', port=443): Max retries exceeded with url: /bot505753216:AAFn9zYMpqrogUkyyCU-r1TtMGrQZhp3Dns/getMe (Caused by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x764dba90>: Failed to establish a new connection: [Errno 101] Network is unreachable',))

>>>

how to solve this

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?

2 replies

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

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

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

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

1 reply

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

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

1 reply

Hi Hilal,

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

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?

2 replies

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.

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

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

Thank you for sharing man really helpful :)

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

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