Update: I have recently started working on a new project to keep track of events from my projects which I use now over Telegram. I would love to hear your feedback on the project: LogSnag - Track your projects' events
In my opinion, Telegram has one of the best, if not the best, chatbot API. What they have created is extremely easy to use, yet it is unbelievably powerful. And I have used it for dozens of small projects over the years. One of my prominent use cases for their API is to send myself events and logs from my applications and projects.
Consider this example; you are developing a new project for which you may need to crawl hundreds or thousands of web pages or any other similar long-running tasks. You would deploy this script to a VM, or maybe your machine, and let it run for the next day or two. But, how do you usually check on the progress? Do you ssh to the VM, find the right tmux session, and read the logs? What if you want to leave home and don’t have access to the computer? Well, this is one of those situations that made me think… “hmm, what if I could use Telegram as a remote output?” I mean, the API is very, very easy to use, and all I need to do is to make an HTTP request to their endpoint, so why not?
This is just one of the dozens of examples where I found it convenient to push events to myself, and ever since, I have used it for many different projects to update myself on user actions, product sales, hell even stock prices. So in this blog post, I will be going over how to set up your first chatbot and how to send events to yourself via Python or JavaScript :)
Register a Telegram Chatbot.
Alright, the first step is to message @botfather on Telegram and to create your first chatbot! The process is very straightforward, as you can see in the following screenshot.
Let’s copy the API token and add it to our environment variables. You can, of course, skip this process and add it directly to your code. Also, make sure to keep this token private! I will be revoking mine after writing this post.
export BOT_TOKEN=2104030722:AAGdY_FeAFqvriecqv3lhissc-uG4t0arL4
Find your telegram Chat Id
Ok, we have one more step to do before getting our hands dirty with some code. Thankfully this one is straightforward, we have to find our chat_id in Telegram, and there are multiple ways to find it. I will be using the chatbot API to find out my chat_id.
So, open the chatbot we have just created and send it a message; it could be anything. Then, make a get request to the following URL with your API token, using your browser or postman, and it should tell you your chat_id.
// template
[https://api.telegram.org/bot](https://api.telegram.org/bot)<BOT_TOKEN>/getUpdates
// how mine looks like with my bot token
[https://api.telegram.org/bot2104030722:AAGdY_FeAFqvriecqv3lhissc-uG4t0arL4/getUpdates](https://api.telegram.org/bot2104030722:AAGdY_FeAFqvriecqv3lhissc-uG4t0arL4/getUpdates)
As you see in the screenshot, you can see your chat_id via the following path result[].message.chat.id. Copy and again, add it to your environment variables or paste directly in the code.
export CHAT_ID=<MY_CHAT_ID>
Ok, that’s pretty much all we had to do with Telegram; let’s write some code. For this post, I will be providing an example with Python and JavaScript, so feel free to skip to whichever one you prefer.
Publishing Events via Python
First, let’s access our environment variables and assign them to variables
import os
BOT_TOKEN = os.environ.get('BOT_TOKEN')
CHAT_ID = os.environ.get('CHAT_ID')
I will be using the requests package to handle my HTTP requests. So, let’s also install that via PyPi by running the following command.
pip install requests
Awesome! Now let’s define a method for sending our events to Telegram. We’re going to call it send_message, and it will need to accept a message string.
def send_message(msg):
Then, we will add Telegram’s send message endpoint and populate it via our bot token.
url = f”https://api.telegram.org/bot{BOT_TOKEN}/sendMessage"
Next, let’s define the URL parameters that we need to send to Telegram. We need a chat_id, and text and by now, we should have both ready.
params = { “chat_id”: CHAT_ID, “text”: msg }
Finally, we will import requests and make a GET request and pass in our URL parameters.
requests.get(url, params=params)
Putting these all together, our method should look like the following.
import requests
def send_message(msg):
url = f"https://api.telegram.org/bot{BOT_TOKEN}/sendMessage"
params = { "chat_id": CHAT_ID, "text": msg }
requests.get(url, params=params)
That’s pretty much it :) Now we can send whatever event that we have to ourselves through Telegram. So, remember the crawler job? Imagine we want to send periodic progress. We can do something like this:
send_message(“🔥 Crawling progress: 56% done”)
Once we run our code, if everything goes right, we should see something like this. How cool is that?
Publishing Events via JavaScript
Ok, let’s repeat the same process in JavaScript. First, let’s access our environment variables and set them to variables.
const BOT_TOKEN = process.env.BOT_TOKEN
const CHAT_ID = process.env.CHAT_ID
Next, I will be using the Axios package to handle my HTTP requests. You can install via NPM by running the following command.
npm i axios
Now, let’s define our sendMessage method. It needs to take our string message as an argument. Then we will add the endpoint URL and populate it via our BOT_TOKEN. Next, let’s define our URL parameters required by Telegram; chat_id and text. Finally, we can make our get request via Axios and pass in our params.
import axios from 'axios';
const BOT_TOKEN = process.env.BOT_TOKEN
const CHAT_ID = process.env.CHAT_ID
async function sendMessage(message) {
const url = `https://api.telegram.org/bot${BOT_TOKEN}/sendMessage`
const params = { chat_id: CHAT_ID, text: message }
await axios.get(url, { params: params })
}
That’s pretty much it! Let’s give this one a shot as well.
await sendMessage("💰 New user signed up")
That’s pretty much it! By adding these couple of lines, we get another superpower that we can use for almost anything!
Top comments (0)