Diniz Martins

Oct 28, 20211 min

Telegram message with Python

In this post I am showing how to send text message and photo from any computer to mobile telegram app. This is only few lines of code to send automatic message to smartphone from raspberry pi or from any computer.

Useful for IOT or A.I. projects, like sending automatic data to smartphone or sending alert message from A.I. security camera.

You just need the Python commands below and start your @BotFather.

@BotFather is the one bot to rule them all. Use it to create new bot accounts and manage your existing bots.

Let's go!

Here's the Python command:

import telepot
 

 
token = 'your_token_here'
 
receiver_id = your_ID_here
 

 
bot = telepot.Bot(token)
 
bot.sendMessage(receiver_id, 'This is a automated test message.')
 
bot.sendPhoto(receiver_id, photo=open('STENGE.png', 'rb'))

Don't forget to install the telepot package.

This is a Python framework for the Telegram bot API, as you can see in the screenshot below:

Open a chat with @BotFather in Telegram and type:

/start
 
/newbot
 
<type_your_bot_name>
 
<type_your_username>

Finally your bot is created and the following message is shown. You must use the bot token to communicate with the Telegram, so make sure you write it down.

With the gained token you now can send a test message by calling the website:

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

You will see this message on your web browser:

{"ok":true,"result":[]}

The next step is to get your Telegram username and type any message to get your ID and now update your browser on the same tab above.

{"ok":true,"result":[{"update_id":433138085,
 
"message":{"message_id":2,"from":{"id":129027001,"is_bot":false,"first_name":"\u1d07\u026a\u0274\u026a\u1d22 \u1d0d\u1d00\u0280\u1d1b\u026a\u074s","username":"stenge.info","language_code":"pt-br"},"chat":{"id":129027001,"first_name":"\u1d07\u026a\u0274\u026a\u1d22 \u1d0d\u1d00\u0280\u1d1b\u026a\u074s","username":"stenge.info","type":"private"},"date":1635430307,"text":"Hello World!"}}]}

Now you have your ID and your token.

Grab all the information and run your script!

    3290
    3