Skip to content

Working Behind a Proxy

Harshil edited this page May 21, 2024 · 20 revisions

PTBs default networking backend HTTPXRequest comes with built-in support for proxies. Note that the details below only apply to HTTPXRequest. If you use a different implementation of BaseRequest, you'll have to configure proxies yourself.

How is a Proxy Server Chosen?

PTB will obtain its proxy configuration in the following order (the first to be found will be used):

  1. Programmatic.
  2. Using HTTP_PROXY environment variable.
  3. Using HTTPS_PROXY environment variable.
  4. Using ALL_PROXY environment variable.

Setting a HTTP(S) Proxy Server Programmatically

Proxies can be setup like this:

from telegram.ext import ApplicationBuilder

# "USERNAME:PASSWORD@" is optional, if you need authentication:
proxy_url = 'http://USERNAME:PASSWORD@PROXY_HOST:PROXY_PORT'  # can also be a https proxy
app = ApplicationBuilder().token("TOKEN").proxy(proxy_url).get_updates_proxy(proxy_url).build()

In the last line, we setup the proxy such that it'll be used both for making requests to the Bot API like Bot.send_message (proxy()) and for fetching updates from Telegram (get_updates_proxy). It is not necessary to setup a proxy for both, you can do it for either of them.

Working Behind a Socks5 Server

This configuration is supported, but requires an optional/extra python package. To install:

pip install python-telegram-bot[socks]
from telegram.ext import ApplicationBuilder

proxy_url = "socks5://user:pass@host:port"

app = ApplicationBuilder().token("TOKEN").proxy(proxy_url).get_updates_proxy(proxy_url).build()

If you're more of an advanced user and would like to customize your proxy setup even further, check out the docs of httpx for more info.

Clone this wiki locally
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy