Telegram is a modern cross-platform messaging app that I use frequently for group messages. Since I use it everyday and it has an open API, I thought it would be a convenient interface for some small project ideas I’ve had recently.
So, I started by poking around the Telegram API . You can find it at https://core.telegram.org/bots
To register a bot, you need to talk with “TheBotfather” in the Telegram app.
You can find it here https://telegram.me/botfather or by searching for “botfather” in the Telegram app.
In the chat with The Botfather, enter “/newbot”. It will ask you for a name then a username for your bot. Once you provide both, The Botfather will provide you with a link to your bot and an API token.
Follow the link to your bot by clicking the link that looks like t.me/{yourBotUsername}. This is where you will receive messages.
Go ahead and send a message to your bot. To prevent spam, bots cannot initiate a chat, so we need to send it a message to enable the bot to message us back. We will read this message via the Telegram API to get the chat_id in the next step.
Next, lets call the Telegram API to get our chat_id. If you have curl installed, you can read the message you just sent via the terminal with the getUpdates method:
curl https://api.telegram.org/bot{YOUR_API_KEY_HERE}/getUpdates
Note: the format is /botXXXXXXXXXXXXXXXXXXXXXXXXX/, there are no backslashes or delimiters between the word bot and your API Token. or with Python 3:
>>> import requests
>>> token = {YOUR_API_KEY_HERE}
>>> url = f'https://api.telegram.org/bot{token}/getUpdates'
>>> requests.post(url).json()
It should then return a JSON payload that looks something like this:
{"ok":true,"result":[{"update_id":12671344,
"message":{"message_id":30,"from":{"id":{YOUR_ID},"is_bot":false,"first_name": "{YOUR_NAME}"
,"username":"{YOUR_USERNAME}","language_code":"en"},"chat":{"id":{YOUR_CHAT_ID},"first_name":"{YOUR_FIRST_NAME}","username":"{YOUR_USERNAME}","type":"private"},"date":1560719493,"text":"{YOUR_SENT_MESSAGE}"}}]}
If you just got this, you might have forgotten to send a message to your bot:
{“ok”:true,”result”:[]}
Take the {YOURCHATID} value, it should be around 9 numbers. Now you can send messages in a similar fashion using the sendMessage method:
curl -d chat_id={YOUR_CHAT_ID} -d text="test msg from curl" https://api.telegram.org/bot{YOUR_API_KEY_HERE}/sendMessage
or with python3
>>> import requests
>>> token = {YOUR_API_KEY_HERE}
>>> url = f'https://api.telegram.org/bot{token}/sendMessage'
>>> data = {'chat_id': {YOUR_CHAT_ID}, 'text': 'python msg'}
>>> requests.post(url, data).json()
and you should get back a receipt, but more importantly you now have a message from your bot in the Telegram app!
Sign up for more tutorials & updates at LearnTelegram.com
Thanks for reading.
Other Telegram articles: