requests.exceptions.ConnectTimeout: HTTPSConnectionPool(host='api.telegram.org', port=443): # python telegram bot using pytelegrambotapi and Tor

Question:

When I want to connect to telegram bot using Tor that returns error blow

requests.exceptions.ConnectTimeout: HTTPSConnectionPool(host=’api.telegram.org’, port=443): Max retries exceeded with url: /bot/getUpdates?offset=1&timeout=20 (Caused by ConnectTimeoutError(<urllib3.connection.HTTPSConnection object at 0x7f28923f4a30>, ‘Connection to api.telegram.org timed out. (connect timeout=20)’))

Asked By: Nima

||

Answers:

first install tor using sudo apt install tor
then run commeds blow

sudo apt install privoxy torsocks

nano /etc/privoxy/config

then pip install pysocks after that uncommnet line that contains forward-socks5t / 127.0.0.1:9050 .

now

sudo systemctl enable privoxy.service
sudo systemctl start privoxy.service

now make sure that in /etc/tor/torsocks.conf file commends blow are uncommnted

TorAddress 127.0.0.1
TorPort 9050

restart your system

next add codes blow in your bot source code

from telebot import apihelper

apihelper.proxy = {'https': 'socks5h://127.0.0.1:9050',
#    'http':'http://127.0.0.1:8118',
#    'https':'https://127.0.0.1:8118'
}
bot = telebot.TeleBot(TOKEN) # be sure telebot.TeleBot calls after apihelper.proxy

Note: if you cant connect stop tor and reconnect it by yourself

Answered By: Nima