Telegram bot webhook on localhost
A bot gets updates in one of two ways: it polls Telegram with getUpdates, or it receives them through a webhook. For a webhook, Telegram needs a public HTTPS address with a valid certificate. tuna gives your local bot such an address, so you can debug the bot in webhook mode on your own machine.
Step 1. Install the clientβ
Instructions are available on the installation page.
Step 2. Run the bot in webhook modeβ
Start the bot so that it receives updates over HTTP, for example on port 8080 and path /telegram. All popular libraries support webhook mode: aiogram, python-telegram-bot, grammY, Telegraf.
Step 3. Start tunaβ
Use your free permanent subdomain so the address doesn't change on restart and you don't have to register the webhook again:
tuna http 8080 --subdomain=<your-subdomain>
Step 4. Register the webhookβ
Pass the tunnel address and path to the setWebhookOpens in a new tab method. The secret_token parameter is a string Telegram will send in the X-Telegram-Bot-Api-Secret-Token header, so the bot can tell real updates from other requests.
curl "https://api.telegram.org/bot<bot_token>/setWebhook" \
-d "url=https://<your-subdomain>.a.tuna.free/telegram" \
-d "secret_token=<secret>"
Telegram responds with {"ok":true,"result":true,"description":"Webhook was set"}.
Step 5. Checkβ
Send the bot a message. The request from Telegram shows up in the inspector at http://127.0.0.1:4040: the update body, headers and the bot's response. To run the same update again after changing the code, click Replay β no need to message the bot again.
If updates don't arrive, ask Telegram what it sees:
curl "https://api.telegram.org/bot<bot_token>/getWebhookInfo"
In the response, url is the registered address, pending_update_count is how many updates are waiting for delivery, and last_error_message is the last delivery error. Then follow the steps in Webhook doesn't reach the app.
Verifying the secretβ
Compare the X-Telegram-Bot-Api-Secret-Token header with secret_token in the bot's code: most libraries have a parameter for this.
With a subscription, you can drop other requests before they reach the bot with a traffic policy in .tuna.yml:
rules:
- expressions:
- not any(req.Headers["X-Telegram-Bot-Api-Secret-Token"], {# == "<secret>"})
actions:
- type: deny
config:
statusCode: 401
Don't commit a file with the secret to the repository.
Switching back to getUpdatesβ
While a webhook is registered, getUpdates doesn't work. To poll Telegram again, delete the webhook:
curl "https://api.telegram.org/bot<bot_token>/deleteWebhook"