Self-hosting the Telegram Bot API means running Telegram’s open-source Bot API server on infrastructure you control while Telegram continues to provide the bot account and messaging network. Your bot still needs its bot token, and the server also requires Telegram application credentials: an api_id and api_hash.
Need a server to try this on? Antihost offers Linux VPS plans with NVMe storage, full root access and a 14-day free trial.
The official route is to compile the tdlib/telegram-bot-api repository with CMake. An unofficial Docker distribution can reduce host-toolchain work. Start the server with --local if you need local file paths, uploads up to 2000 MB, HTTP webhooks, arbitrary local webhook addresses and ports, or as many as 100000 webhook connections. The server itself accepts HTTP only, so a public HTTPS deployment needs a TLS-terminating reverse proxy. Before moving an existing bot, call logOut on Telegram’s cloud endpoint and do not run that bot on multiple Bot API servers at once.
As an Amazon Associate I earn from qualifying purchases.
What self-hosting changes—and what it does not
The self-hosted component is Telegram’s Bot API server, not a replacement for Telegram’s network. The server translates your application’s HTTP requests into Bot API operations and maintains the local state and files needed to serve those requests. Telegram still owns the bot account, authenticates the bot token, delivers updates, and carries messages between users and your bot.
With the hosted endpoint, your code normally calls URLs under https://api.telegram.org. With a local server, your code points to the address where your instance listens, commonly an internal URL such as http://127.0.0.1:8081. Bot API method paths retain the familiar form, for example /bot<token>/getMe; only the base address changes.
#1 Best Overall
- Includes Raspberry Pi 5 with 2.4Ghz 64-bit quad-core CPU (8GB RAM)
- Includes 128GB Micro SD Card pre-loaded with 64-bit Raspberry Pi OS, USB MicroSD Card Reader
- CanaKit Turbine Black Case for the Raspberry Pi 5
- CanaKit Low Noise Bearing System Fan
- Mega Heat Sink - Black Anodized
Self-hosting is useful when the hosted API’s file and networking constraints do not fit your application, or when you need the files and request path to stay inside infrastructure you administer. It also makes you responsible for operating the process, storage, firewall, proxy, certificates, updates and secrets. Telegram’s project documentation does not publish a universal CPU, memory, cost or uptime target, so capacity planning must follow your own update rate, file sizes, retention policy and availability requirements.
Requirements and credentials
Telegram application credentials
The server’s only mandatory command-line options are --api-id and --api-hash. These are application credentials, separate from an individual bot’s token. Telegram instructs developers to register an official Telegram application and obtain those parameters through my.telegram.org.
The Tool Desk
Outbyte Driver Updater FREEScan for outdated or missing drivers - takes under a minuteDriver Scan →Outbyte PC Repair FREERepair Windows errors before they cause bigger problemsFix Now →api_id: the numeric identifier issued for your Telegram application.api_hash: the corresponding application secret. Treat it as confidential.- Bot token: issued by Telegram for each bot. Your bot code uses this token in Bot API requests; it is not a substitute for the application credentials.
You may pass the application values as options or provide them through the environment variables TELEGRAM_API_ID and TELEGRAM_API_HASH. Keep all three secrets out of source control, public container manifests and logs. Use your operating system’s secret store, a protected environment file, or an equivalent mechanism with permissions limited to the service account.
Build dependencies
The official README names OpenSSL and zlib as runtime/build prerequisites. The build toolchain must include a C++17-compatible compiler, gperf, and CMake 3.10 or newer. Install the versions supplied by your operating system, then verify them before configuring the project. A missing compiler, CMake or generated-code tool will stop the build before a server binary is produced.
Choose an installation method
| Decision area | Source build | Docker distribution |
|---|---|---|
| Compiler and dependencies | You install and control the C++ compiler, CMake, gperf, OpenSSL and zlib directly on the host. | The image packages the application and most user-space dependencies, reducing host-toolchain work. |
| Repeatability and rollback | Record the repository revision and build environment yourself; rollback means rebuilding a known revision. | Pin and review the image version so an earlier image can be restored predictably. |
| Filesystem and volume management | You choose the service user, directories, permissions and backup process on the host. | Persist the documented data directory, /var/lib/telegram-bot-api, with a durable volume. |
| Patch cadence | You decide when to pull source, rebuild and restart. | You decide when to pull, verify and redeploy a newer image; image provenance becomes part of the decision. |
| Observability | Integrate the native process with your init system, logs and metrics. | Collect container logs and health information in addition to host-level monitoring. |
| Credential and TLS injection | Options or environment variables are supplied by the service manager; a separate proxy terminates TLS. | Environment variables and mounted secrets enter the container; a separate proxy still terminates TLS. |
The Docker option described by the aiogram distribution is unofficial: it packages the official server but is not the project’s source-build path. Review the image source, release notes and digest before production use. The source build offers the clearest control over exactly what is compiled; the image offers simpler, repeatable host deployment when your team already operates containers.
Build the official server from source
1. Install the host prerequisites
Install a C++17-capable compiler, CMake 3.10 or newer, gperf, OpenSSL development files and zlib development files. Package names differ by operating system, so use the distribution’s development-package equivalents. Confirm that the compiler, cmake and gperf resolve on the service account’s PATH.
Free tools Windows power users keep installed
One-click scans. No signup required.
2. Clone the repository with submodules
Run the project’s documented clone command so all required submodules are fetched:
git clone --recursive https://github.com/tdlib/telegram-bot-api.git
cd telegram-bot-api
mkdir build
cd build
The --recursive flag matters. A plain clone can leave submodules unavailable, causing configuration or compilation failures that look like missing source files.
Rank #2
- Includes Raspberry Pi 4 4GB Model B with 1.5GHz 64-bit quad-core CPU (4GB RAM)
- Includes Pre-Loaded 32GB EVO+ Micro SD Card (Class 10), USB MicroSD Card Reader
- CanaKit Premium High-Gloss Raspberry Pi 4 Case with Integrated Fan Mount, CanaKit Low Noise Bearing System Fan
- CanaKit 3.5A USB-C Raspberry Pi 4 Power Supply (US Plug) with Noise Filter, Set of Heat Sinks, Display Cable - 6 foot (Supports up to 4K60p)
- CanaKit USB-C PiSwitch (On/Off Power Switch for Raspberry Pi 4)
3. Configure a Release build
From the new build directory, configure CMake in Release mode:
cmake -DCMAKE_BUILD_TYPE=Release ..
Read the configuration output before continuing. It should detect the compiler, OpenSSL, zlib and the generated-code tools. If CMake reports a missing dependency, install the corresponding development package and rerun the command; do not work around a failed detection by silently removing a required library.
What’s actually slowing this PC down?
Pick the symptom - the matching free tool is one click away.
4. Compile and install
Build and install the target with the official sequence:
cmake --build . --target install
The resulting executable is installed according to the CMake configuration. Record the install path and repository revision in your deployment notes so a later operator can reproduce or roll back the binary.
5. Create a service boundary
Run the server under a dedicated, non-root service account. Give it ownership only of its data directory and bind it to an internal interface unless the host is intentionally acting as the public edge. Configure your init system to restart the process after a failure, send logs to your central collector and stop it cleanly during upgrades. The Bot API server is stateful enough that its data directory must be included in backups and migration plans.
Start the server and select local mode
Basic startup
Supply the application credentials either through TELEGRAM_API_ID and TELEGRAM_API_HASH or as options. A shell invocation using the environment variables is:
telegram-bot-api --api-id "$TELEGRAM_API_ID" --api-hash "$TELEGRAM_API_HASH"
The README says those two options are mandatory. Your service manager should inject the variables before launching the process and should not print them in command-line diagnostics or process listings where your platform exposes arguments to other users.
Enable the features that require --local
Add --local when the bot needs capabilities unavailable through https://api.telegram.org:
Rank #3
- Design for Raspberry Pi: Supports installation of 4 Raspberry Pis and 4 ssds, compatible with any 2.5” Solid State Drive (7mm/9mm) and Rpi 4B/3B+, and other B/B+ models.
- The SSD mounting bracket also has two holes reserved for the SD card extension adapter ASIN: B09CKRDFTH, which allows you to access the SD card from the front of the rack.
- Easy to Setup: Just use two included thumbscrews to mount the rackmount, which adopts a screw-in design, which helps you install and replace quickly and easily, no tools needed!
- Applications: This is a hardware solution to get ingenious use of the Raspberry Pi, with this kit and open source software OpenMediaVault, you can use the Pi as a NAS Server, Surveillance station, or even a Web server.
- Optional accessories: Single mounting bracket: B09GFQLPTY; Micro SD card extension adapter ASIN: B09CKRDFTH. I/O Panel: B09FXRQPFM
telegram-bot-api --api-id "$TELEGRAM_API_ID" --api-hash "$TELEGRAM_API_HASH" --local --http-port 8081
In local mode, the project documents these operational differences:
- Downloads have no documented size limit in local mode.
- Uploads can be as large as 2000 MB.
- Methods can use local filesystem paths and file URIs instead of first copying every file through the hosted service.
- Webhooks can use HTTP.
- You can select any local webhook IP address and any port.
max_webhook_connectionscan be set as high as 100000.getFileresults can contain absolute local paths.
These are project limits and features, not a promise that your disk, network, proxy or bot code can sustain the maximum. A 2000 MB upload still requires enough temporary and persistent storage, and a high webhook-connection setting still requires a listener and operating system limits sized for it.
PC Slower Than It Used to Be?
A free scan shows the junk files, broken settings and background clutter dragging Windows down - then fixes them in one click.Free scan · Windows 10 & 11Crashes, No Sound, or Screen Glitches?
Random freezes, missing sound and display glitches usually trace back to one bad driver. Find and replace yours safely.Free scan · under a minuteChoose the listening port
The default HTTP port is 8081. Change it with --http-port if another service already occupies that port or if your internal network standard uses a different one. Bind the port to a private interface when only local applications should call it; expose it through a controlled proxy when remote clients need access.
Point bot code at the local endpoint
Most Bot API libraries let you configure a custom API root or server URL. Set that root to the local listener, then keep using normal method names and the bot token. For a process on the same machine, an internal base such as http://127.0.0.1:8081 avoids exposing the API on the network. For separate application and API hosts, use the API host’s private address and restrict ingress to the application’s network identity.
Test with a harmless method such as getMe before enabling polling or webhooks. The request should reach your server and return the bot identity. A connection refusal indicates address, port or firewall trouble; an authentication error usually indicates a bot-token problem; a server-side startup error requires checking the Bot API process logs and its application credentials.
HTTP, HTTPS and reverse-proxy design
The official server accepts only HTTP requests. Telegram’s project documentation states that a TLS-termination proxy is required for remote HTTPS requests. Do not treat the Bot API process itself as your certificate endpoint.
Quick wins for a faster PC:
Clear out junk files and repair common Windows errorsFree Scan →Scan for outdated or missing drivers - takes under a minuteDriver Scan →Internal topology
A typical public deployment has three layers:
- A public DNS name resolves to your edge proxy.
- The proxy terminates TLS, validates the certificate and forwards the request over a protected network to the Bot API server’s HTTP listener.
- Your bot application calls the internal Bot API address, or the proxy address when it is intentionally sharing the public path.
Configure the firewall so the Bot API port is not directly reachable from the internet when the proxy is the intended entry point. Restrict the proxy’s upstream to the expected Bot API host and port, set request and body-size limits compatible with your chosen upload size, and monitor certificate renewal. The canonical project materials do not prescribe a particular proxy, hostname, certificate authority, server size or uptime design; those are deployment responsibilities.
Webhook protection
Telegram’s Bot API supports a webhook secret token. Configure a secret when registering the webhook and verify the X-Telegram-Bot-Api-Secret-Token header in the bot-facing application or in the proxy path where that check is appropriate. Reject requests with a missing or incorrect header before handing the update to application code. Keep the secret separate from the bot token and application credentials, rotate it through a planned change window, and ensure your proxy forwards the header unchanged if verification occurs behind the proxy.
Rank #4
- [ULTIMATE RASPBERRY PI 5 CASE & MINI PC] - Unlock the full potential of your Raspberry Pi 5 with the Pironman 5-MAX — the most advanced Raspberry Pi 5 Case for power users. This high-performance Raspberry Pi 5 Cooling Case features dual NVMe M.2 slots with RAID 0/1 support, AI accelerator compatibility ( e.g. Hailo-8l M.2 AI), a PCIe Gen2 switch, a PWM tower cooler + dual RGB fans and a smart OLED display. With its dual transparent panels and optimized cable management (including full-size HDMI), it’s the ideal Raspberry Pi 5 Enclosure for building a high-speed NAS, AI edge computing device, or Home Assistant hub. (Raspberry Pi NOT Included)
- [DUAL NVMe M.2 SLITS & NAS RAID SUPPORT] - Supercharge your storage with the best Raspberry Pi 5 NVMe Case solution. Featuring two expandable NVMe M.2 slots (2230-2280) powered by a built-in PCIe Gen2 switch, this Raspberry Pi 5 NAS Case supports RAID 0/1 for ultra-fast data setups. Whether you're using a high-speed NVMe SSD or a Hailo-8L AI accelerator, Pironman 5-MAX delivers the ultimate performance boost for advanced Raspberry Pi 5 AI applications and edge computing
- [ADVANCED COOLING SYSTEM] - Engineered for high-performance builds, Pironman 5-MAX features a powerful tower cooler, one PWM fan, and dual RGB fans for enhanced airflow. The dual transparent panel design improves ventilation while showcasing vibrant RGB lighting. Ideal for cooling both the Raspberry Pi 5 and dual NVMe SSDs or AI accelerators like Hailo-8L, it ensures stable operation under heavy workloads with low noise and long-term durability
- [SMART OLED DISPLAY WITH VIBRATION WAKE-UP] - Pironman 5-MAX features a 0.96" OLED screen that delivers real-time system insights including CPU usage, memory, temperature, IP address, and disk status. With customizable display options and auto sleep mode, the screen can be instantly reactivated by a light tap thanks to the built-in vibration sensor—offering a smarter and more interactive experience
- [ENHANCED FUNCTIONALITY] - Pironman 5-MAX empowers your Raspberry Pi 5 with advanced features like safe shutdown via a metal power button, customizable RGB lighting, dual full-size HDMI ports, vibration-triggered OLED wake-up, and an external GPIO extender. It also includes RTC battery support for timekeeping and seamless Home Assistant integration. With detailed guides, online tutorials, and full technical support from SunFounder, setup and use are effortless and worry-free
Use the Docker distribution safely
The aiogram image is an unofficial Docker distribution of the official server. Its documented quick start publishes port 8081, supplies TELEGRAM_API_ID and TELEGRAM_API_HASH, applies a restart policy and mounts /var/lib/telegram-bot-api as persistent storage.
Deployment checklist
- Choose and pin a specific image version rather than relying on a moving
latesttag. Review the image’s release notes and provenance before pulling it. - Provide
TELEGRAM_API_IDandTELEGRAM_API_HASHthrough your container secret mechanism or protected environment configuration. - Publish only the port that your network design requires. If a reverse proxy is the public edge, keep the container port private and proxy to it.
- Mount a durable volume at
/var/lib/telegram-bot-api. Back up that volume and test restoring it on a separate host. - Set a restart policy, collect container logs, and alert on repeated restarts or loss of the persistent volume.
- Pin the image digest where your registry and release process support it, and schedule controlled updates rather than automatic unreviewed pulls.
Container isolation does not remove the need for host firewall rules, TLS termination, secret rotation or update planning. A deleted container with an unmounted data directory can lose the local state you expected to retain, so verify the volume mapping before the first production start.
Move an existing bot from the cloud endpoint
Migration is a handoff, not simply a change to a URL. Telegram’s official README says that to guarantee a bot receives all updates, you must deregister it from the cloud server by calling logOut on https://api.telegram.org, then replace the API address with the local server address.
Plan a short maintenance window
- Confirm the local binary or container starts successfully with valid application credentials.
- Verify the local listener, firewall path and (if applicable) TLS proxy with a
getMerequest. - Stop the old bot worker so it cannot continue polling or processing webhooks during the handoff.
- Call the cloud method using the bot token. For example, with the token held in a protected shell variable:
curl -sS "https://api.telegram.org/bot${BOT_TOKEN}/logOut"
- Change the bot library’s API root to the local HTTP address or to your controlled HTTPS proxy address.
- Start one bot worker against the local server and configure the intended polling or webhook flow.
- Send a test update, confirm that it arrives once, and watch logs for the first production traffic.
The project warns that running one bot on more than one local server at the same time does not guarantee update delivery. Keep the old instance stopped until the new path is stable, and do not use two active servers as an informal high-availability strategy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Polling and webhook choices after migration
Long polling
Polling keeps the bot application responsible for repeatedly requesting updates. It is straightforward for an internal deployment because the application initiates the connection to the local server. Ensure only one active poller owns the bot, use a process supervisor for restarts, and monitor the delay between requests and received updates.
Webhooks
Webhooks let Telegram deliver updates to an HTTP endpoint. Local mode permits HTTP webhooks, any local webhook IP and any port, and raises the documented max_webhook_connections ceiling to 100000. For an internet-facing webhook, place the endpoint behind TLS termination and verify the secret-token header. For an internal-only arrangement, keep the listener on a private address and allow only the expected network path.
Choose the model that matches your failure handling. Polling concentrates outbound connectivity in the bot worker; webhooks add DNS, certificate, proxy and inbound-firewall dependencies. Neither option removes the requirement to process updates idempotently and to record enough logs to diagnose a duplicate or delayed delivery.
Storage, files and permissions
Local mode exposes absolute paths in getFile results and accepts local paths and file URIs. That makes file handling faster and avoids unnecessary copies, but it also means the Bot API process and your bot application must agree on path visibility. A path valid inside a container may not exist on the host, and a path readable by the application may be inaccessible to the service account.
- Use a dedicated data directory with explicit ownership and restrictive permissions.
- Mount the same path into both containers when the Bot API and bot application are containerized separately.
- Keep temporary upload space and long-term storage on monitored filesystems.
- Back up the persistent directory and document restore permissions.
- Set retention rules for downloaded media so large local files do not silently consume all available space.
The 2000 MB local upload ceiling describes what the project accepts, not how much free disk you have. Check available space before accepting large files and return a controlled application error when your own quota is lower.
Recommended Free Tools
Security checklist
- Protect the bot token,
api_hash, webhook secret and container secret files. - Run the process as a non-root account and expose the HTTP listener only to trusted callers.
- Terminate TLS at a maintained proxy for remote HTTPS access; do not publish the plain Bot API port directly to the internet.
- Use firewall rules and proxy access controls to limit who can reach the listener.
- Validate
X-Telegram-Bot-Api-Secret-Tokenfor webhook requests. - Patch the source build or pinned image on a scheduled, tested cadence.
- Redact tokens and application secrets from command output, crash reports and centralized logs.
- Back up and protect the Bot API data directory, then periodically test restoration.
Troubleshoot common failures
CMake cannot find OpenSSL, zlib or gperf
Install the operating system’s development packages, verify that their headers and libraries are visible to the build environment, and rerun cmake -DCMAKE_BUILD_TYPE=Release .. from the build directory. Do not copy random libraries into the source tree; fix the host dependency path or provide an explicit, documented CMake toolchain.
The process starts and exits immediately
Check that both application credentials are present and non-empty, that the service account can read its data directory, and that the selected HTTP port is free. Run the same binary interactively with protected environment variables to capture the first error, then return it to the service manager after correcting the configuration.
The bot works against the cloud endpoint but not locally
First call getMe through the local address. If the connection fails, inspect DNS, bind address, firewall and proxy forwarding. If getMe succeeds but updates do not arrive, verify that the cloud bot was logged out, that the old worker is stopped, and that only one local server is active.
Large uploads fail despite local mode
Confirm that the server was started with --local. Then inspect every layer: application request limits, reverse-proxy body limits, temporary filesystem capacity, container volume capacity and any upstream timeout. The documented 2000 MB ceiling does not override a smaller limit imposed by your proxy or application.
Do these 3 things before closing this tab:
1Scan for outdated or missing drivers - takes under a minute2Clear out junk files and repair common Windows errors3Fix the driver behind crashes, sound loss and screen glitchesWebhooks return errors
Check that the public hostname resolves to the TLS proxy, the certificate is valid, the proxy forwards to the Bot API HTTP listener, and the configured port is reachable from the expected path. If secret-token protection is enabled, verify the exact X-Telegram-Bot-Api-Secret-Token value and make sure the proxy has not removed the header.
Updates, rollback and operational ownership
Record the source revision or container digest, credential-injection method, listener address, proxy configuration, data-volume location and backup schedule. Test an upgrade in a staging environment with a non-production bot, then stop the single production instance, replace the binary or image, and confirm getMe before accepting updates. If the new release fails, restore the previous revision or image while preserving the data directory and the same credential configuration.
Monitor process health, HTTP error rates, update latency, disk usage, certificate expiry and restart frequency. Because Telegram does not publish a universal hardware or cost profile for this server, use these measurements to choose capacity rather than relying on a generic VPS size. Increase storage and network headroom before your workload reaches the local file and webhook limits, and document who can perform the cloud logOut and rollback operations.
When self-hosting is the right choice
Self-hosting is a good fit when you need local file paths, very large transfers, HTTP webhooks inside a controlled network, a custom webhook address or port, or operational control over where Bot API state is stored. It is less attractive when your team cannot maintain a Linux service or container, protect secrets, operate a TLS proxy, monitor storage and perform upgrades. In that case, the hosted endpoint avoids this infrastructure burden but does not provide the local-mode capabilities described above.
The practical path is straightforward: obtain the application credentials, build or deploy the official server, start it with --local only when its additional capabilities are needed, put TLS termination in front of any public HTTPS route, and migrate one bot at a time after calling logOut on the cloud endpoint. Keep one active server per bot and treat the data directory, credentials and proxy as production infrastructure rather than incidental configuration.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.




