Working Behind a Proxy
TelegramBotClient
allows you to use a proxy for Bot API connections. This guide covers using three different proxy solutions.
If you are in a country, such as Iran, where HTTP and SOCKS proxy connections to Telegram servers are blocked, consider using a VPN, using Tor Network, or hosting your bot in other jurisdictions.
HTTP Proxy
You can configure HttpClient
with WebProxy
and pass it to the Bot client.
// using System.Net;
// using System.Net.Http;
WebProxy webProxy = new (Host: "https://example.org", Port: 8080)
{
// Credentials if needed:
Credentials = new NetworkCredential("USERNAME", "PASSWORD")
};
HttpClient httpClient = new (
new HttpClientHandler { Proxy = webProxy, UseProxy = true, }
);
var bot = new TelegramBotClient("YOUR_API_TOKEN", httpClient);
SOCKS5 Proxy
As of .NET 6, SocketsHttpHandler
is able to use Socks4, Socks4a and Socks5 proxies!
// using System.Net;
// using System.Net.Http;
WebProxy proxy = new ("socks5://127.0.0.1:9050")
{
Credentials = new NetworkCredential("USERNAME", "PASSWORD")
};
HttpClient httpClient = new (
new SocketsHttpHandler { Proxy = proxy, UseProxy = true, }
);
var bot = new TelegramBotClient("YOUR_API_TOKEN", httpClient);
SOCKS5 Proxy over Tor
Warning: Use for Testing only!
Do not use this method in a production environment as it has high network latency and poor bandwidth.
Using Tor, a developer can avoid network restrictions while debugging and testing the code before a production release.
-
Install Tor Browser
-
Open the
torcc
file with a text editor (Found inTor Browser\Browser\TorBrowser\Data\Tor
) -
Add the following lines: (configurations are described below)
EntryNodes {NL} ExitNodes {NL} StrictNodes 1 SocksPort 127.0.0.1:9050
-
Look at the Socks5 proxy example above.
-
Start the Tor Browser
Usage:
// using System.Net;
// using System.Net.Http;
WebProxy proxy = new ("socks5://127.0.0.1:9050");
HttpClient httpClient = new (
new SocketsHttpHandler { Proxy = proxy, UseProxy = true }
);
var bot = new TelegramBotClient("YOUR_API_TOKEN", httpClient);
Note that Tor has to be active at all times for the bot to work.
Configurations in torcc
EntryNodes {NL}
ExitNodes {NL}
StrictNodes 1
These three lines make sure you use nodes from the Netherlands as much as possible to reduce latency.
SocksPort 127.0.0.1:9050
This line tells tor to listen on port 9050 for any socks connections. You can change the port to anything you want (9050 is just the default), only make sure to use the same port in your code.