subzeroid / instagrapi

🔥 The fastest and powerful Python library for Instagram Private API 2024
https://hikerapi.com/p/bkXQlaVe
MIT License
4.37k stars 684 forks source link

Problems while trying to set up a proxy[BUG] #808

Closed larubiano0 closed 2 years ago

larubiano0 commented 2 years ago

Describe the bug

I'm having trouble in the log in step when setting up a free proxy

To Reproduce

from config import *
from functions import *

from instagrapi import Client
import pandas as pd
from time import sleep
from random import (randint,choices)
import json
import shutil
from traceback import print_exc

IG_USERNAME = IGLOGIN['IGUSERNAME']
IG_PASSWORD = IGLOGIN['IGPASSWORD']

datasets = {} # account:[followers_ids] 

try: 
    with open('follow_track.json','r') as json_file:
        jsondata = json.load(json_file)
except:
    with open('follow_track.json', 'w') as json_file:
        print("follow_track.json created with success")
    jsondata = {}

for account in IGACCOUNTS:
    csvdata = pd.read_csv(DATA[account],index_col=False)
    datasets[account] = csvdata['User ID'].tolist()

    if account not in jsondata:

        accountdata = IgAccount(account,len(csvdata),0,0)

        jsondata[account] = {'name':accountdata.name,'followers':accountdata.followers,
                             'followed_by_VAI': accountdata.followed_by_VAI, 'ratio':accountdata.ratio}

with open('follow_track.json', 'w') as f:
    json.dump(jsondata, f)

class Bot:
    _cl = None

    def __init__(self):
        self._cl = Client()
        if os.path.exists(IG_CREDENTIAL_PATH):
            self._cl.load_settings(IG_CREDENTIAL_PATH)
            self._cl.login(IG_USERNAME, IG_PASSWORD)
        else:
            self._cl.set_proxy(PROXYSTR) 
            self._cl.set_locale(PROXYLOCALE)
            self._cl.set_timezone_offset(TIMEZONE_OFFSET)
            self._cl.set_device(DEVICE)
            self._cl.set_user_agent(USER_AGENT)
            self._cl.set_country(COUNTRY)
            self._cl.set_country_code(COUNTRY_CODE)

            self._cl.login(IG_USERNAME, IG_PASSWORD)
            self._cl.dump_settings(IG_CREDENTIAL_PATH)

    def follow_by_username(self, username) -> bool:
        userid = self._cl.user_id_from_username(username)
        return self._cl.user_follow(userid)

    def follow_by_userid(self, userid) -> bool:
        return self._cl.user_follow(userid)

    def update(self, datasets, jsondata):
        """
        Chooses first user_id from random dataset,
        Checks if active (more than MINFOLLOWERS followers, otherwise continues)
        Follows user
        Prints username
        Removes user_id from list
        Removes user from csv
        updates follow_track.json (ratio and followed_by_VAI)
        returns datasets

        """
        account = choices(list(datasets.keys()))[0]
        userID = datasets[account][0]
        accountinfo = self._cl.user_info(userID).dict()
        followercount = accountinfo['follower_count']

        sleep(randint(7,23)) #Sleeps random time between 7 and 23 seconds between getting account's info and following user

        if jsondata[account]['ratio'] > MAXRATIO:

            del datasets[account] #Deletes the account from datasets, therefore it can't be chosen anymore

            return datasets, jsondata

        if followercount < MINFOLLOWERS: 

            pass

        else:

            username = self._cl.username_from_user_id(userID)

            try:

                if self.follow_by_userid(userID):

                    print(f'{username} followed with success')

                else:

                    print(f'There has been a problem while trying to follow {username}')
                    print('Probably the account is private or already followed')

            except Exception: 

                print_exc()

                print('Something went wrong')

        datasets[account] = datasets[account][1:]

        with open(DATA[account],'r') as f: # DELETES ROW FROM CSV
            with open('temp.csv','w') as f1:

                c = 0 
                for line in f:

                    if c == 1: # SKIPS USER
                        c +=1 
                        continue

                    f1.write(line)
                    c+=1

        shutil.copyfile('temp.csv', DATA[account]) #Overwirtes DATA[account]

        accountdata = IgAccount(account,jsondata[account]['followers'],jsondata[account]['followed_by_VAI'],jsondata[account]['ratio']) #Update json data and follow_track.json

        accountdata.addFollowed()

        jsondata[account] = {'name':accountdata.name,'followers':accountdata.followers,
                             'followed_by_VAI': accountdata.followed_by_VAI, 'ratio':accountdata.ratio}

        with open('follow_track.json', 'w') as f:
            json.dump(jsondata, f)

        return datasets, jsondata

if __name__ == '__main__':
    bot = Bot()

    while True:
        """
        Infnit loop
        """
        datasets, jsondata = bot.update(datasets, jsondata)

        secs = randint(564,1164) #Expected value: 864. 100 users per day

        print(f'Waiting {secs} seconds')

        sleep(secs) #In seconds

        if datasets == {}: #RATIO has been followed for all csv's

            break

Proxy info:


PROXYSTR = 'HTTP://bogota:proxy@181.118.158.130:999' #TODO fix proxy
PROXYLOCALE = 'es_CO'
TIMEZONE_OFFSET = -5 * 3600
DEVICE = {"app_version": "244.1.0.19.110",
          "android_version": 31,
           "android_release": "12.0.0",
            "dpi": "480dpi",
             "resolution": "1080x2280",
              "manufacturer": "samsung",
               "device": "SM-G998B",
                "model": "p3s",
                 "cpu":"exynos2100",
                  "version_code":"384108453"}
USER_AGENT = 'Mozilla/5.0 (Linux; Android 12; SM-G998B Build/SP1A.210812.016; wv) AppleWebKit/537.36 (KHTML, like Gecko) Version/4.0 Chrome/103.0.5060.71 Mobile Safari/537.36 Instagram 244.1.0.19.110 Android (31/12; 480dpi; 1080x2280; samsung; SM-G998B; p3s; exynos2100; es_CO; 384108453)'
COUNTRY = 'CO'
COUNTRY_CODE = 57

*Country and language were changed to my country’s

Traceback

Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/urllib3/connectionpool.py", line 595, in urlopen self._prepare_proxy(conn) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/urllib3/connectionpool.py", line 816, in _prepare_proxy conn.connect() File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/urllib3/connection.py", line 319, in connect self.sock = ssl_wrapsocket( File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/urllib3/util/ssl.py", line 329, in ssl_wrap_socket return context.wrap_socket(sock, server_hostname=server_hostname) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/ssl.py", line 500, in wrap_socket return self.sslsocket_class._create( File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/ssl.py", line 1040, in _create self.do_handshake() File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/ssl.py", line 1309, in do_handshake self._sslobj.do_handshake() ssl.SSLError: [SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:1129)

During handling of the above exception, another exception occurred:

Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/requests/adapters.py", line 440, in send resp = conn.urlopen( File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/urllib3/connectionpool.py", line 638, in urlopen retries = retries.increment(method, url, error=e, _pool=self, File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/urllib3/util/retry.py", line 388, in increment raise MaxRetryError(_pool, url, error or ResponseError(cause)) urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='i.instagram.com', port=443): Max retries exceeded with url: /api/v1/accounts/contact_point_prefill/ (Caused by SSLError(SSLError(1, '[SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:1129)')))

During handling of the above exception, another exception occurred:

Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/instagrapi/mixins/private.py", line 284, in _send_private_request response = self.private.post( File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/requests/sessions.py", line 577, in post return self.request('POST', url, data=data, json=json, kwargs) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/requests/sessions.py", line 529, in request resp = self.send(prep, send_kwargs) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/requests/sessions.py", line 645, in send r = adapter.send(request, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/requests/adapters.py", line 517, in send raise SSLError(e, request=request) requests.exceptions.SSLError: HTTPSConnectionPool(host='i.instagram.com', port=443): Max retries exceeded with url: /api/v1/accounts/contact_point_prefill/ (Caused by SSLError(SSLError(1, '[SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:1129)')))

During handling of the above exception, another exception occurred:

Traceback (most recent call last): File "/Users/larubiano0/Desktop/Vai/Instagram-Bot-Vai/follow_bot.py", line 187, in bot = Bot() File "/Users/larubiano0/Desktop/Vai/Instagram-Bot-Vai/follow_bot.py", line 62, in init self._cl.login(IG_USERNAME, IG_PASSWORD) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/instagrapi/mixins/auth.py", line 372, in login self.pre_login_flow() File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/instagrapi/mixins/auth.py", line 47, in pre_login_flow self.set_contact_point_prefill("prefill") File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/instagrapi/mixins/auth.py", line 147, in set_contact_point_prefill return self.private_request("accounts/contact_point_prefill/", data, login=True) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/instagrapi/mixins/private.py", line 445, in private_request raise e File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/instagrapi/mixins/private.py", line 432, in private_request self._send_private_request(endpoint, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/instagrapi/mixins/private.py", line 376, in _send_private_request raise ClientConnectionError( instagrapi.exceptions.ClientConnectionError: SSLError HTTPSConnectionPool(host='i.instagram.com', port=443): Max retries exceeded with url: /api/v1/accounts/contact_point_prefill/ (Caused by SSLError(SSLError(1, '[SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl.c:1129)')))

Expected behavior Being able to log-in successfully

Desktop (please complete the following information):

Additional context

I was running a follow bot (1 account) on a Google Cloud compute-engine instance, it worked well for 5-6 days, then the IP got banned and the instagram account received a phishing notification.

Captura de Pantalla 2022-07-26 a la(s) 8 14 00 p m

I've been trying to fix the problem by setting up a proxy, using free proxies form my country (Colombia)

adw0rd commented 2 years ago

Check your proxy first

curl --proxy "HTTP://bogota:proxy@181.118.158.130:999" https://www.instagram.com/

or

import requests
resp = requests.get('https://www.instagram.com/', proxies={'https': "HTTP://bogota:proxy@181.118.158.130:999"}, timeout=4)
print(resp.status_code)
larubiano0 commented 2 years ago

Thank you so much