Send and Receive Messages with the Telegram API

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:

Note: the format is /botXXXXXXXXXXXXXXXXXXXXXXXXX/, there are no backslashes or delimiters between the word bot and your API Token.

or with Python 3:

It should then return a JSON payload that looks something like this:

If you just got this, you might have forgotten to send a message to your bot:

Take the {YOUR_CHAT_ID} value, it should be around 9 numbers.

Now you can send messages in a similar fashion using the sendMessage method:

or with python3

and you should get back a receipt, but more importantly you now have a message from your bot in the Telegram app!

Up next, we will run a basic Telegram bot from AWS Lambda. Check it out here: Running a Serverless Telegram Bot from AWS Lambda

Sign up for more tutorials & updates at LearnTelegram.com

More sign ups ⇒ more content

Check out my personal site: https://wk0.dev

Thanks for reading.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store