Halloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PCHalloween DealsAmazon USOctober picks are moving - compare before checkoutAmazon US: current deals, useful picks and tech finds.See Picks×
FREEDOM251

Freedom251 › Blog › Bot API

How to Self-Host the Telegram Bot API Server

By Freedom251 Team · · 9 min read

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

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 underlying network and bot-account service. You need both the bot token and Telegram application credentials (api_id and api_hash). Build the official server with CMake or deploy an unofficial Docker distribution, start it with --local for large files and local webhooks, place a TLS-terminating reverse proxy in front of it for public HTTPS, and call logOut on the cloud endpoint before moving an existing bot.

What self-hosting changes—and what it does not

The Telegram Bot API server is the HTTP gateway your application uses to send requests and receive updates. When you use https://api.telegram.org, Telegram operates that gateway. A self-hosted deployment runs Telegram’s open-source implementation on your own virtual machine, bare-metal host, or container platform instead.

As an Amazon Associate I earn from qualifying purchases.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Self-hosting does not create an independent Telegram network, replace Telegram accounts, or let a bot operate without Telegram’s service. Your server still communicates with Telegram. The benefit is control over the gateway process, its filesystem, networking, certificates, logs, and rollout schedule. The local mode also exposes capabilities that are unavailable through the public cloud endpoint, including local file paths and substantially larger uploads.

Prerequisites and credentials

Telegram application credentials

The project README says the only mandatory server options are --api-id and --api-hash. Obtain these values through Telegram’s official application process at my.telegram.org; Telegram’s documentation requires developers to register an official Telegram application before receiving the two parameters.

#1 Best Overall
Sale
TOZO A1 Wireless Earbuds Bluetooth 5.3 Light Weight in Ear Headphones | IPX5 Waterproof,2 Mics for AI Calls,Immersive Premium Sound Bass Headset with Charging Case,32 EQ via App Black
  • [Ultra-Lightweight Ear Buds Designed for Small Ears] Each earbud weighs only 3.7g and features a compact, ergonomic in-ear design made especially for small ears. Secure, low-profile, and comfortable for workouts, all-day wear or overnight sleeping.The ultra-slim profile sits flush in your ear with no hard edges poking or rubbing, so you can even sleep on your side without discomfort.
  • [Immersive Stereo Sound with TOZO OrigX Technology] TOZO OrigX tuning delivers clear vocals, balanced mids, and natural stereo sound for music, podcasts, and videos.
  • [Long Battery Life for Daily Use] Get up to 7 hours of playtime on a single charge, with up to 32 hours total using the charging case—ideal for workdays, commuting, and extended listening sessions.
  • [Bluetooth 5.3 & Stable Connection] Bluetooth 5.3 provides fast pairing, stable wireless performance, and reduced dropouts as you move around home or office.
  • [Deep Bass with Clear Vocals] High-performance drivers produce punchy bass while keeping vocals clean and detailed for everyday listening.

You can provide the values on the command line or through the environment variables TELEGRAM_API_ID and TELEGRAM_API_HASH. Keep them in a protected secret store or service manager rather than committing them to source control or placing them in a publicly readable configuration file.

Bot token and host

Each bot still has its own Telegram bot token. The server’s application credentials identify your Telegram application; the bot token identifies the bot that your program controls. Plan a host with reliable outbound connectivity to Telegram, enough disk for the server’s working data and files, and a firewall policy that exposes only the ports you intentionally publish.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The canonical project documentation does not publish a universal CPU, memory, storage, cost, throughput, or uptime recommendation. Size the host from your bot’s update rate, file workload, retention needs, and proxy or monitoring stack, then measure those workloads in your own environment.

Choose a deployment method

Decision area Official source build Unofficial Docker distribution
Host toolchain You install and maintain a C++17-compatible compiler, gperf, CMake 3.10 or newer, OpenSSL, and zlib. The image packages the server and reduces host-toolchain work, but Docker itself becomes a prerequisite.
Build control Direct control over compiler, dependency versions, compiler flags, and patch application. Control shifts to the image tag and its build provenance; review and pin the version you deploy.
Rollback Requires retaining binaries or rebuilding a chosen commit and dependency set. Image tags make versioned rollbacks straightforward when the persistent volume is compatible.
Filesystem and volume handling You decide where the installed process and its data live and how the host backs them up. The documented quick start mounts /var/lib/telegram-bot-api as persistent storage; volume ownership and backup become container-operations tasks.
Credentials and TLS Inject credentials through the process environment or protected service configuration; terminate TLS in a proxy. Pass TELEGRAM_API_ID and TELEGRAM_API_HASH as protected container settings and keep the proxy outside or alongside the container.
Updates and observability You choose when to rebuild, patch, restart, and collect process logs. You choose image refresh timing, container restart policy, log driver, and image provenance.

Neither route removes the need for firewall rules, backups, certificate management, secret rotation, and update testing. Choose the source build when compiler-level control is important; choose Docker when repeatable packaging and simpler host preparation matter more.

Build the official server from source

The official repository is https://github.com/tdlib/telegram-bot-api. Install the documented prerequisites first: OpenSSL, zlib, a C++17-capable compiler, gperf, and CMake 3.10 or newer. Use your operating system’s package manager or approved internal toolchain to provide them.

  1. Clone the repository, including its submodules:

    git clone --recursive https://github.com/tdlib/telegram-bot-api.git
  2. Enter the checkout and create a separate build directory:

    What’s actually slowing this PC down?

    Pick the symptom - the matching free tool is one click away.

    Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
    cd telegram-bot-api
    mkdir build
    cd build
  3. Configure a release build:

    cmake -DCMAKE_BUILD_TYPE=Release ..
  4. Compile and install the target:

    cmake --build . --target install

Keep the repository revision and the dependency versions recorded with your deployment. That record makes a rebuild or rollback reproducible when you upgrade the host or move to another machine.

Rank #2
Sale
Smart Watch for Men Women Compatible with iPhone Samsung Android Phone 1.69 inch Full Touch Screen IP68 Waterproof Bluetooh Fitness Tracker Heart Rate/Sleep Monitor (Black)
  • 【IP68 Waterproof Multifunctinal Smart Watch】Torjalph fitness activity tracker smart watch is IP68 waterproof technology ,you can wear it when swimming,handwashing,it's rain-proof which means that you perform multiple exercise modes outside without worrying about sweat or rain corroding your fitness smart watch,and this watch equipped with a 230 mAh large capacity battery magnetic charging ,and this sports activity tracker watch can be used 5-7 days If fully charged.
  • 【Larger 1.83'' Full Screen Watch & Multi-dial Selection】1.83 inch full HD color touch screen smart watch for men / women provides excellent 240*284 resolution image quality ,This Bluetooth smart watch offers a better touch experience and remarkable immersion and ,more than 200 watch faces for you to choose from App"Da Fit ", you can change the dial style according to your mood to wear keeping the world on your wrist
  • 【Accurate Activity Tracker Smart Watch 】sports watch activity tracker uses sweat and dust resistant breathable silicone strap, our Fitness Tracker Smart Watch for Android iOS Phones supports 12 sports modes,walking,running,bicycle,swimming,badminton,basketball,football,rope skipping. This bluetooth calls smart watch for men women is lightweight and stylish, bringing more convenient and relaxing sports experience while also providing more protection.
  • 【Your 24 Hour Personal Daily Health Monitor】Fitness watch for women men full touch screen IP67 waterproof bluetooth smartwatch for Android iOS Phones with heart rate blood pressure monitor multifunction Andriod smart watch with steps counter sleep monitor sports fitness watch, monitoring blood oxygen saturation allows you to understand your physical condition in real time to track fitness progress ,to know your health status in time.
  • 【More Functions Bluetooth Call Smart Watch】This fitness activity smart watch full screen for iPhone and Android phones includes a bunch of new features including:The bluetooth smart watch can hang up the phone, receive and display WhatsAPP /Text /Facebook /Twitter /Messenger reminder.Support sedentary reminder, alarm clock, stopwatch, timer,weather information,music control, remote camera control compatible with Android 5.0 and above or iOS 9.0 and above smartphones.

Start the process with credentials

After installation, start the resulting Bot API server executable with the two mandatory values. A typical invocation passes them as options:

telegram-bot-api --api-id <your-api-id> --api-hash <your-api-hash>

Instead of command-line options, set TELEGRAM_API_ID and TELEGRAM_API_HASH in the protected environment used by the service manager. Do not expose the process command line or environment to untrusted users, because either can reveal credentials.

Enable local mode for files and webhooks

Add --local when your bot needs features that the public endpoint does not provide. The project README documents these local-mode capabilities:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Capability Documented behavior Operational meaning
Downloads No size limit is stated for local-mode downloads. Your disk, bandwidth, proxy limits, and application behavior still determine practical capacity.
Uploads Up to 2000 MB. Check available disk, request-body limits, timeouts, and transfer capacity throughout your proxy chain.
Local files Uploads can use local paths and file URIs. The path must exist and be readable by the Bot API process on the server that receives the request.
Webhooks HTTP webhooks are supported. The Bot API process itself speaks HTTP; public HTTPS requires a front-end TLS terminator.
Webhook bind address Any local webhook IP and any port can be used. Bind only where your firewall and proxy design require it.
Webhook concurrency max_webhook_connections can be set up to 100000. This is a documented configuration ceiling, not a promise that one host can sustain 100000 active connections.
getFile results Absolute local paths are returned. Treat returned paths as sensitive host information and avoid leaking them to clients.

The default HTTP port is 8081. Change it with --http-port when another service already uses that port or when your network layout calls for a different internal listener. For example:

telegram-bot-api --api-id <your-api-id> --api-hash <your-api-hash> --local --http-port 8081

The port number above is the project default; explicitly setting it makes service configuration easier to audit. If you choose another port, use that same value in the reverse proxy and firewall rules.

Expose the API safely over HTTPS

The official README states that the Bot API server accepts only HTTP requests. For a remote HTTPS endpoint, place a reverse proxy or equivalent front end in front of it and terminate TLS there. The proxy then forwards requests over the protected internal network to the Bot API listener.

  1. Assign a DNS name to the public endpoint and obtain a certificate for that name from a certificate authority appropriate to your organization.

    Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
    Rank #3
    New Bee Guitar Cable 10ft Electric Instrument Bass AMP Cord | 6.35mm Jack, Durable Design, Stage and Home Studio Use, Low Noise Shielded Electric Cord for Bass, Keyboard, Amp, Mixer
    • [Low Noise High Fidelity] New bee guitar cord with 22AWG oxygen-free-copper center conductors provides enhanced signal transfer, the PVC insulation material and the high-density stranded copper double shield provide noise rejection for quiet operation
    • [Ideal for Choice] New bee 1/4 straight and right angle metal connectors, ensures a secure connection in any instrument, pedal, or amp jack. L shape great fro on stage guitar stands
    • [Wide Compatible] Suitable for mixer, power amplifier, microphone, effector, decoder, equalizer, electoronic organ, electric guitar, electric bass and other electronic equipments. Widely used in the installation of smart home, karaoke speaker, professional stage audio, etc
    • [Easy Disassemble] Making incidental repairs quick and easy! Very nice, flexible cable
    • [Dont Hesite to Order] 24 hours customer services and professional technology team are standing by
  2. Configure the proxy to listen on the public HTTPS port, present the certificate, and forward the Bot API path to the server’s HTTP listener, commonly port 8081.

  3. Restrict the Bot API listener so it is not directly reachable from the public internet unless that exposure is deliberate and separately secured.

  4. Set firewall rules to allow only the proxy-to-server path and the outbound traffic your host needs. Keep administrative ports separate from the bot endpoint.

  5. Configure your bot’s webhook URL to use the public HTTPS hostname. Verify that the proxy preserves request bodies, supports the timeout behavior your bot needs, and does not impose a smaller request-size limit than your file workload.

    Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Protect webhooks with a secret token

Telegram’s Bot API supports a webhook secret token. Configure a strong secret and verify the X-Telegram-Bot-Api-Secret-Token header in the bot-facing application or proxy path. Reject requests with a missing or incorrect header before they reach update-processing code. Store the secret like any other credential and rotate it through a controlled maintenance procedure.

Run the unofficial Docker distribution

An aiogram-maintained image is an unofficial Docker distribution of the official Telegram Bot API server. It can be useful when you want to avoid installing the compiler and native dependencies directly on the host, but treat the image as a separate supply-chain input: review its provenance, pin a specific version in production, and test upgrades before changing the running tag.

The documented quick-start configuration has four essential parts:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
BSIMB 15.6" Digital Family Calendar & Chore Chart, No Subscription Fees
  • Digital Family Calendar: BSIMB digital calendar wall touch screen puts an end to your chaotic life. Designed for busy families, the digital calendar keeps you organised and in step with your family. Assign different colours and tasks to each family member to make family scheduling easier and more intuitive.
  • Easy Setup and Auto-Sync: Plug in, connect to WLAN and auto-syn your electric calendar in minutes. Digital wall calendar compatible with Google calendar, iCloud calendar, Outlook calendar, Cozi calendar and Yahoo calendar. Add events directly on the device or through the ecalendar app. Electronic calendar stays current whether you're at work or traveling—no manual updates needed.
  • All-In-One Home Assistant: Smart calendar builds habits and encourage independence with personalised chores. Display daily meal plan to reduce the daily ‘What's for dinner?’ stress. To-do lists keep track of everything you want. Turning chores into valuable achievements with stars and rewards, making life easier and more enjoyable.
  • Manage Anytime Anywhere: BSIMB electronic calendar for family stay connected with the powerful ecalendar app. Access and manage your digital wall calendar anytime, anywhere with free features like stars & rewards, photo screensaver, chore charts, meals plans, to-do lists etc. Electronic planner paid features like Magic Import tailor advanced tools for users with special needs.
  • Stay in Touch with Loved Ones: Share photos or videos from your phone to electronic wall calendar with app, instantly update your life moment, and keep in touch with your family, especially those who are far away; you can also surprise your smart calendar digital wall by sending him a wish card; it's also great for keeping tech-illiterate elders in touch with the youngsters.
  • Publish the container’s HTTP port 8081 to the host or to the internal network where your reverse proxy can reach it.
  • Provide TELEGRAM_API_ID and TELEGRAM_API_HASH through protected container environment settings.
  • Use a restart policy so the service returns after an expected host or container restart.
  • Mount /var/lib/telegram-bot-api as persistent storage and include that volume in your backup plan.

Keep TLS termination outside the container unless you have a deliberate design to place a proxy in the same deployment. The Bot API process remains an HTTP backend. Do not put credentials in a public compose file, image layer, issue tracker, or shell history. Before upgrading the image, confirm that the existing volume is backed up and that the new image can read it.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Move an existing bot from the cloud endpoint

Changing the base URL alone is not enough. Telegram associates update delivery with the server handling the bot, and the official README warns that running one bot on more than one local server at the same time does not guarantee update delivery.

  1. Schedule a maintenance window and stop workers that could send requests to the old endpoint.

  2. Confirm that the self-hosted process is running, reachable from the bot application, and configured with the correct api_id, api_hash, and local-mode settings if required.

    Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  3. On https://api.telegram.org, call the Bot API method logOut for the bot. The project documentation says deregistration is required to guarantee that the bot receives all updates after the move.

  4. Change the bot application’s API base address to the self-hosted HTTPS hostname (or the internal HTTP address when both services are on a trusted private network).

  5. Register or update the webhook against the new endpoint, including the secret-token configuration if you use one. If you poll instead, start polling only after the old registration has been removed.

  6. Send a controlled test message and verify that exactly one worker receives the resulting update. Check application logs, proxy logs, and Bot API server logs together.

    Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  7. Keep the old integration disabled until the new path has passed your monitoring checks. Never leave the same bot actively served by multiple servers.

Operations, security, and troubleshooting

Credentials are rejected at startup

Check for typographical errors in both values and confirm that the process received the intended environment variables or command-line options. The mandatory server credentials are the application’s api_id and api_hash; a bot token alone cannot satisfy those startup requirements.

HTTPS requests fail before reaching the server

Verify that the certificate matches the public hostname, the proxy is listening on the expected port, and the firewall permits proxy-to-backend traffic. Remember that the Bot API process accepts HTTP, not TLS; sending HTTPS directly to its listener will not work without a TLS-termination layer.

Large uploads fail in local mode

Confirm that the process was started with --local, then inspect every intermediary for request-size, body-buffer, and timeout limits. The documented local-mode ceiling is 2000 MB, but a proxy or application limit below that value will fail first. Also verify free disk space and permissions for the path used by the upload.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Webhooks receive no updates after migration

Check that logOut was called on the cloud endpoint, that the webhook URL resolves to the new proxy, and that the proxy forwards the request to the correct internal port. Validate the secret-token header if enabled. A second server still running the same bot can make update delivery unreliable.

Local file paths expose too much information

Local mode and getFile can return absolute paths. Limit who can call your bot-facing application, avoid returning raw paths to end users, and treat logs containing those paths as sensitive operational data.

Plan backups and updates

Back up the persistent data used by your deployment, especially the Docker volume at /var/lib/telegram-bot-api when using the container distribution. Record the source revision or image tag, test upgrades in a staging environment, and monitor restart loops, disk usage, webhook response codes, and update lag. The project’s documented limits are configuration boundaries, not capacity guarantees, so alerting should be based on the behavior of your workload.

Source build or Docker: a practical decision

Use the source build if you need to audit and control the compiler and dependencies, apply a specific patch, or integrate the process tightly with an existing host service manager. Use Docker if your team already standardizes on image scanning, immutable deployments, volume backups, and controlled image rollouts. In either case, the externally visible architecture is the same: the Bot API server listens over HTTP, a proxy handles public TLS, and your bot application points to the resulting endpoint.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

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.

Bot APICMakeDockerLinuxself-hostingTelegramwebhooks

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.