How to Connect to Telegram with Python

Published: Jan 18, 2025

Telegram offers us an incredibly simple and powerful set of APIs that allow you to create applications on top of. In this blog I’m going to show you how you can use python to connect to your telegram account via the API, send messages to your own telegram account and listen to any messages you receive to your telegram account.

This will lay the foundation for you to build any program you want on top of the telegram API such as an automated chat bot, marketing messages to your customers or even reminders for bookings. For us, this blog will form part of a larger series where we use telegram alerts to buy and sell cryptocurrencies.

To get set up you will need python installed which you can follow along here, as well as any text editor of your choice (I use vscode).

Firstly we will install the package telethon using the code below

Block type not supported

We can then import the code into our file as follow:

Block type not supported

We can then begin initialising a TelegramClient which will act as the client for us to send and receive messages automatically. For this we have one simple line of code which handles everything for us:

Block type not supported

This is a python Class that acts as an interface for all the methods we would like to use, without all the headache of coding it from scratch. It will manage sessions, authentication, error handling etc. all in one line of code. To add your own TELEGRAM APP ID and API HASH you can head to https://my.telegram.org/apps and enter a few details and it will spit out an APP ID and API HASH for you. Remember these are secret so don’t share them with anyone or they’ll have access to your telegram.

To start the client we can call the method:

Block type not supported

which on the first run will require input of a phone number and a code. This will create a .session file so you won’t need to do this again and can deploy this anywhere.

Now we’re ready to test this out, we can run the following to send a message to ourselves, you can adjust the message as you see fit:

Block type not supported

Because some of these methods involve us waiting for telegrams servers to give us a response, we have to wrap the code in an async function, you don’t need to worry about that right now but I have a video on it here: https://www.youtube.com/watch?v=5Wl0OhUq9V4

The final code will look something like this:

Block type not supported

And we should see the following in our telegram messages:

And there we have it, you now know how to connect to the telegram API using python and your opportunities to build cool programs on top of it are endless!