Simple Guide to Telegram Bot (Webhook)

Leonardi Fabianto
EDTS
Published in
5 min read6 days ago

One way to utilize or monetize big data is to make insightful and up-to-date reports. Many BI tools can solve this task, but reporting is not always about creating an interactive dashboard. Sometimes, a simple text-based report is enough to summarize business conditions. This is where Chatbots (such as Telegram Bot) shine. This article will show a simple guide to implementing the Telegram Bot to generate reports.

Telegram Bot Data Flow

First, let’s look at how data flows in the Telegram Bot Basic Conversation Architecture:

Telegram Bot Basic Conversation

Diagram flows:
1. The user sends a message to the Telegram App
2. The Telegram App forwards messages and metadata to the Telegram Server
3. The Telegram Server sends updated information to the Bot Server
4. The Bot Server does some tasks and sends messages (or any media) to the Telegram Server
5. The Telegram Server forwards messages to the User/Group chat room

As you can see, this is the normal conversation flow. Before we move to implementation, let’s take a look at Telegram Bot Webhook Architecture:

Telegram Bot Webhook Architecture

Diagram flows:
1. External Trigger send request (HTTPS) to Telegram Server including data and media to be sent.
2. The Telegram Server forwards messages and media to the Telegram App
3. The Telegram App shows sent data to Users/Group

This one is a simpler implementation. The user doesn’t need to send any requests. Messages (or reports) are sent automatically by external triggers.

Now, let’s try to create a simple chatbot. We will test our ChatBot via HTTP Request and create our Telegram Bot Server.

Create New Bot

First, we need to create a new bot. This can be done by adding BotFather (@BotFather). Follow the instructions to create a new bot.

Keep the HTTP API Token safe, because it will be our authentication key.

To enable Chatbot to read Users’ messages, we must set the Privacy Settings of our Bots. You can follow the instructions below:

We can add the Chatbot to our Private Chat (by starting a chat with the Bot) or Groups (by adding the Bot to the group). This way, the Bot can send messages to User/Group.

Now we can start testing and implementing our ChatBot. I always encourage you to read the documentation too:

Implementation: HTTP API

We can use the Telegram HTTP API Bot server to send messages as our Bot. We’ll need an HTTP API Token.

To check the status of our Bot, we can request /getMe route:

# Change HTTP_API_TOKEN with your token
curl https://api.telegram.org/bot{{HTTP_API_TOKEN}}/getMe
Get Bot Status via Postman

To send a message, we can request sendMessage route:

# Change HTTP_API_TOKEN with your token
curl https://api.telegram.org/bot{{HTTP_API_TOKEN}}/sendMessage?chat_id=675439471&text=Test
Send a Message via Postman

Implementation: WebHook

Now we’ll try to create our own Telegram Bot Server. In this implementation, I’ll be using Python with Flask and TeleBot libraries. Why do we need Flask? Because the Telegram Server will send/forward requests from the Telegram App to our Telegram Bot Server via HTTPS Requests, we need an HTTP Endpoint to receive the updates.

For full code, please refer to this:

I’ll be explaining some crucial parts only, for a more detailed explanation feel free to contact me or see the full code.

First, we will initiate the Flask server and Bot object.

# /src/main.py (line 13)

# Init Service
C = Config()

app = Flask(__name__)
bot = TeleBot(C.BOT_TOKEN.get_secret_value(), threaded=False)

Then we create an endpoint for receiving Webhook updates. Received updates from API will be used to update Bot status and conditions.

# /src/main.py (line 24)

# WebHook Endpoint
@app.post("/webhook")
def webhook(tw: TelegramWebhookHelper):
req_body = request.get_json()
try:
tw.update_bot(req_body)
current_app.logger.info(req_body)
except Exception:
current_app.logger.error(json.dumps(req_body))
return jsonify({"msg": "Success"})

Then we create a handler to interact with incoming messages or media.

# /src/handler.py (line 6)

# Configure
def configure_webhook(bot: TeleBot):
bot.message_handler(regexp="^!report")(generate_report)


# Handler
def generate_report(message: Message):
chat_id = message.chat.id
bot.send_message(chat_id, "Report ABC (from Message Handler)")

And that’s it! Well, we need to integrate all of these, I used some dependency injection with FlaskInjector and configured the webhook helper function in main.py .

To try this implementation, we can run these commands (make sure to add environment variable BOT_TOKEN with Bot HTTP API Token:

pip install -r requirements.txt # One time only
gunicorn --bind=:8080 --workers=1 --threads=8 --timeout=0 main:app

Now, the Telegram Server needs to access our local Telegram Bot Server. One way to make local API open for the public is by using ngrok . To install ngrok follow this instructions:

Run your ngrok service:

ngrok http 8080
ngrok Server Interface

Copy the forwarding URL, we will use it to set the API Webhook Push URL. To set this URL, we’ll request to /setWebhook route:

# Change HTTP_API_TOKEN with your token
curl https://api.telegram.org/bot{{HTTP_API_TOKEN}}/setWebhook?url=https://0adc-202-158-32-186.ngrok-free.app/webhook

NNow if we chat with the Bot with a valid message, we’ll get the report:
Message from Telegram Bot

Message from Telegram Bot

Conclusion

This is only a simple how-to guide for Telegram Bot development. By adding data source connection, report formatting, scheduling, or more message handlers, you could build a Reporting Engine with ChatBot. Read the documentation, check out StackOverflow, or ask ChatGPT if you ever got stuck while developing these Telegram APIs.

Fin Up and Happy Coding!

--

--