Creating a No Dependency Telegram Bot in Python
So recently I’ve been wanting my software to communicate with me about its state via notifications. I have some email notifications set up but I don’t love my inbox being spammed with technical notifications. I set out to find a better soltion.
Another Telegram Bot
I listened to a podcast with Levels.io about how he used telegram to recieve error messages of his running applicaions. I figured that setting up one of these bots was an easy solution for monitoring.
Telegram makes it super easy to create a bot. That along with the solid mobile application make it great solution for notifications.
There are a great deal of libraries that exist that have all sorts of features. I wanted to keep my client as simple and low dependency as possible. Mainly I just wanted a way to send myself a message so I decided to write my own ~20 liner.
Telegram Bot Setup
Let’s get to the business of this post and show from start to finish how to set one of these up.
1. Obtaining Your Token
The Telegram documentation is pretty good. This tutorial here goes into detail. We’ll just cover the basics.
Open a new chat with the
@BotFather
Send the message(or technically the command)
/newbot
Follow the prompt to complete setup.
On the final step message there will be a token that will look like
4839574812:AAFD39kkdpWt3ywyRZergyOLMaJhac60qc
. Save this token! You will also have provided a name or handle for your bot save that as well.
2. Setup Chat With Your Bot
Go ahead and start a new chat with your bot from your Telegram account. It doesn’t matter what you send. We just want to establish a chat so we can send messages to this chat from the bot.
3. Basic Client Setup
I like to setup classes for clients like this. I’ll be doing that in this guide.
Class Setup
In your desired location create your class and provide it with the token from step 1.
class Telegram: def __init__(self): self.telegram_token = "myTelegramToken"
Create Updates Method
The Telegram API provides a
getUpdates
endpoint that provides us a list of the chats and message updates from each chat. We’re goint to use this method to obatin our chat id to send messages to.import requests class Telegram: def __init__(self): self.telegram_token = "myTelegramToken" def GetUpdates(self): url = f"https://api.telegram.org/bot{self.telegram_token}/getUpdates" response = requests.get(url).json() return response
Get Updates
Let’s run our new method and print out the response so we can grab our chat id.
telegram = Telegram() updatesResponse = telegram.GetUpdates() print(updatesResponse)
Adding chat id to our client
Using the chat id retrieved from the previous step, we’re going to go ahead and create another instance variable for our class called
chat_id
class Telegram: def __init__(self): self.telegram_token = "myTelegramToken" self.chat_id = "myChatId"
4. Making Our Client Good
Send Update Method
Telegram provides the
sendMessage
api which allows us to use the api to send messages fromt he bot to the desired chat. Our method looks like:def SendUpdate(self, message: str): url = f"https://api.telegram.org/bot{self.telegram_token}/sendMessage?chat_id={self.chat_id}&text={message}" response = requests.get(url).json() return response
Complete Example
Great so now our Telegram client is complete and ready to use. It should look like the following:
import requests class Telegram: def __init__(self): self.telegram_token = "myTelegramToken" self.chat_id = "myChatId" def GetUpdates(self): url = f"https://api.telegram.org/bot{self.telegram_token}/getUpdates" response = requests.get(url).json() return response def SendUpdate(self, message: str): url = f"https://api.telegram.org/bot{self.telegram_token}/sendMessage?chat_id={self.chat_id}&text={message}" response = requests.get(url).json() return response
Testing Let’s do a quick test. We’ll just fire a message to ourselves
telegram = Telegram() updatesResponse = telegram.SendUpdate("Hello world from python!") print(updatesResponse)
On your Telegram application you should see the message appear in your chat.
Wrapping Up and Integrating
Our client is super lightwieght and can be included in any Python project easily. This has replaced a ton of workflows that I had previously used email or slack for.
I found it being a great solution for solo devs or small teams that want notifications but don’t need to set up their own infrastructure for handling it. Try it out next time you want an easy notification service.