Want your Telegram bot to respond instantly to users? That’s where webhooks come in. While long polling is fine for testing, webhooks are faster and better for real-time updates—especially in production. In this guide, you’ll learn how to set up and test Telegram bot webhooks using Pinggy, a super easy tool that gives your local server a public URL with just one command. No downloads, no headaches.
Telegram Bot Webhooks Explained
Quick Setup Guide
/newbot
command)ssh -p 443 -R0:localhost:8000 qr@a.pinggy.io
curl -X POST "https://api.telegram.org/bot<TOKEN>/setWebhook" -d "url=https://your-pinggy-url/webhook"
Why Use Webhooks?
Telegram bots can receive messages and updates through two different mechanisms:
While long polling is simpler to set up initially, webhooks offer significant advantages for production bots:
For webhooks to function properly, Telegram needs to be able to reach your server through a public URL. This is where many developers face challenges during development and testing.
Before setting up a webhook, you need a Telegram bot and its API token:
/newbot
123456789:ABCDefGhIJKlmNoPQRsTUVwxyZ
Keep this token secure as it grants full access to control your bot.
Next, you’ll need a server that can receive and process webhook updates from Telegram. Here’s a simple example using Python and Flask
from flask import Flask, request, jsonify
import logging
app = Flask(__name__)
logging.basicConfig(level=logging.INFO)
@app.route('/webhook', methods=['POST'])
def webhook():
update = request.get_json()
logging.info(f"Update received: {update}")
# Extract message information
if 'message' in update:
chat_id = update['message']['chat']['id']
text = update.get('message', {}).get('text', '')
logging.info(f"Message from {chat_id}: {text}")
# Process the message here
# You would typically send a response back to the user
return jsonify({'status': 'ok'})
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8000)
Save this code as telegram_webhook.py
and install the required packages:
pip install flask
Run the server with:
python telegram_webhook.py
This creates a simple webhook endpoint at http://localhost:8000/webhook
that logs incoming messages.
For Telegram to send webhooks to your server, it needs a public URL. During development, you can use Pinggy to expose your local server to the internet without complex configuration:
Open your terminal and run:
ssh -p 443 -R0:localhost:8000 qr@a.pinggy.io
https://abcdefghij.a.pinggy.link
This URL now points to your local webhook server and can be accessed from anywhere, including Telegram’s servers.
Now you need to tell Telegram where to send updates for your bot. You can do this using the Telegram Bot API’s setWebhook
method:
Using cURL:
curl -X POST "https://api.telegram.org/bot<YOUR_BOT_TOKEN>/setWebhook" \
-d "url=https://abcdefghij.a.pinggy.link/webhook"
Replace <YOUR_BOT_TOKEN>
with the token you received from BotFather, and use your actual Pinggy URL.
If successful, Telegram will respond with:
{
"ok": true,
"result": true,
"description": "Webhook was set"
}
Now it’s time to test if your webhook is working properly:
You should see log entries showing the received update, including the message text and chat ID. If you see these logs, congratulations! Your webhook is working correctly.
Example log output:
INFO:root:Update received: {'update_id': 123456789, 'message': {'message_id': 1, 'from': {'id': 987654321, 'is_bot': False, 'first_name': 'User', 'language_code': 'en'}, 'chat': {'id': 987654321, 'first_name': 'User', 'type': 'private'}, 'date': 1625097600, 'text': 'Hello, bot!'}}
INFO:root:Message from 987654321: Hello, bot!
Once you have the basic webhook working, you can enhance your bot server to:
sendMessage
API to reply to user messagesHere’s an example of how to send a response message:
import requests
def send_message(chat_id, text, token):
url = f"https://api.telegram.org/bot{token}/sendMessage"
payload = {
"chat_id": chat_id,
"text": text
}
response = requests.post(url, json=payload)
return response.json()
You can call this function from your webhook handler to reply to incoming messages.
Setting up a Telegram bot webhook allows your bot to receive real-time updates, creating a more responsive and efficient user experience. By using Pinggy to expose your local development environment, you can easily test and debug your webhook implementation before deploying to production.
Webhooks are particularly valuable for bots that need to respond quickly to user interactions or process high volumes of messages. With the approach outlined in this guide, you can develop and test your Telegram bot webhook locally, then deploy the same code to your production environment.
For more advanced use cases, consider exploring Telegram's Bot API documentation to leverage features like inline keyboards, location sharing, and file transfers to create rich, interactive bot experiences.