Search code examples
pythonproxytelegram-bottorpython-telegram-bot

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


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)'))


Solution

  • You got this error because of that there is a problem to connect telegram servers directly (due to censorship)! You may need to use a VPN or change your dns provider for using tor with Telegram Bot in Ubuntu. Just use eny VPN or to use Tor you have to do this:

    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 can't connect, just force stop tor and reconnect it by yourself