def test_lg(self): settings = { "uuids": { "phone_id": "57d64c41-a916-3fa5-bd7a-3796c1dab122", "uuid": "8aa373c6-f316-44d7-b49e-d74563f4a8f3", "client_session_id": "6c296d0a-3534-4dce-b5aa-a6a6ab017443", "advertising_id": "8dc88b76-dfbc-44dc-abbc-31a6f1d54b04", "device_id": "android-e021b636049dc0e9" }, "device_settings": { "cpu": "h1", "dpi": "640dpi", "model": "h1", "device": "RS988", "resolution": "1440x2392", "app_version": "117.0.0.28.123", "manufacturer": "LGE/lge", "version_code": "168361634", "android_release": "6.0.1", "android_version": 23 }, # "user_agent": "Instagram 117.0.0.28.123 Android (23/6.0.1; US; 168361634)" "user_agent": "Instagram 117.1.0.29.119 Android (27/8.1.0; 480dpi; 1080x1776; motorola; Moto G (5S); montana; qcom; ru_RU; 253447809)" } api = Client(settings) api.login(ACCOUNT_USERNAME, ACCOUNT_PASSWORD) self.assertIsInstance(api.user_id, int) self.assertEqual(api.username, ACCOUNT_USERNAME)
def get_client(self): """We return the client class, in which we automatically handle exceptions You can move the "handle_exception" above or into an external module """ def handle_exception(client, e): if isinstance(e, BadPassword): client.logger.exception(e) client.set_proxy(self.next_proxy().href) if client.relogin_attempt > 0: self.freeze(str(e), days=7) raise ReloginAttemptExceeded(e) client.settings = self.rebuild_client_settings() return self.update_client_settings(client.get_settings()) elif isinstance(e, LoginRequired): client.logger.exception(e) client.relogin() return self.update_client_settings(client.get_settings()) elif isinstance(e, ChallengeRequired): api_path = client.last_json.get("challenge", {}).get("api_path") if api_path == "/challenge/": client.set_proxy(self.next_proxy().href) client.settings = self.rebuild_client_settings() else: try: client.challenge_resolve(client.last_json) except ChallengeRequired as e: self.freeze('Manual Challenge Required', days=2) raise e except (ChallengeRequired, SelectContactPointRecoveryForm, RecaptchaChallengeForm) as e: self.freeze(str(e), days=4) raise e self.update_client_settings(client.get_settings()) return True elif isinstance(e, FeedbackRequired): message = client.last_json["feedback_message"] if "This action was blocked. Please try again later" in message: self.freeze(message, hours=12) # client.settings = self.rebuild_client_settings() # return self.update_client_settings(client.get_settings()) elif "We restrict certain activity to protect our community" in message: # 6 hours is not enough self.freeze(message, hours=12) elif "Your account has been temporarily blocked" in message: """ Based on previous use of this feature, your account has been temporarily blocked from taking this action. This block will expire on 2020-03-27. """ self.freeze(message) elif isinstance(e, PleaseWaitFewMinutes): self.freeze(str(e), hours=1) raise e cl = Client() cl.handle_exception = handle_exception cl.login(self.username, self.password) return cl
def __init__(self, *args, **kwargs): filename = '/tmp/instagrapi_tests_client_settings.json' settings = {} if os.path.exists(filename): settings = json.load(open(filename)) self.api = Client(settings) # self.api.set_proxy("socks5://127.0.0.1:30235") self.api.login(ACCOUNT_USERNAME, ACCOUNT_PASSWORD) json.dump(self.api.get_settings(), open(filename, 'w')) super().__init__(*args, **kwargs)
def __init__(self, folder_one, folder_two): self.folder_one = folder_one self.folder_two = folder_two self.list_files_one = folder_to_list(folder_one) self.list_files_two = folder_to_list(folder_two) self.cl = Client() self.cl.login(ACCOUNT_USERNAME, ACCOUNT_PASSWORD) create_dir(CURRENT_FOLDER) create_dir(ERRORS_FOLDER)
class BaseClientMixin: def __init__(self, *args, **kwargs): if self.api is None: self.api = Client() self.set_proxy_if_exists() super().__init__(*args, **kwargs) def set_proxy_if_exists(self): proxy = os.environ.get("IG_PROXY", "") if proxy: self.api.set_proxy(proxy) # "socks5://127.0.0.1:30235" return True
class FakeClientTestCase(unittest.TestCase): api = None def __init__(self, *args, **kwargs): self.api = Client() super().__init__(*args, **kwargs) def test_login(self): try: self.api.login(ACCOUNT_USERNAME, "fakepassword") except Exception as e: self.assertEqual( str(e), "The password you entered is incorrect. Please try again.")
def __init__(self, *args, **kwargs): filename = f'/tmp/instagrapi_tests_client_settings_{ACCOUNT_USERNAME}.json' try: settings = json.load(open(filename)) except FileNotFoundError: settings = {} except JSONDecodeError as e: print('JSONDecodeError when read stored client settings. Use empty settings') print(str(e)) settings = {} self.api = Client(settings) self.set_proxy_if_exists() self.api.login(ACCOUNT_USERNAME, ACCOUNT_PASSWORD) json.dump(self.api.get_settings(), open(filename, 'w')) super().__init__(*args, **kwargs)
def schedulePost(): global success global reddit global cl success = False print("Logging In") cl = Client() cl.login(username, password) reddit = praw.Reddit(client_id='--YOUR CLIENT ID--', client_secret='--YOUR CLIENT SECRET--', user_agent='my user agent') print("Logged In") while not success: try: uploadPost() except Exception as ex: print(ex) print(f"r/{subreddit}\n{title}") time.sleep(0.1)
def __init__(self, *args, **kwargs): filename = f'/tmp/instagrapi_tests_client_settings_{ACCOUNT_USERNAME}.json' self.api = Client() try: settings = self.api.load_settings(filename) except FileNotFoundError: settings = {} except JSONDecodeError as e: print('JSONDecodeError when read stored client settings. Use empty settings') print(str(e)) settings = {} self.api.set_settings(settings) self.api.request_timeout = 1 self.set_proxy_if_exists() if ACCOUNT_SESSIONID: self.api.login_by_sessionid(ACCOUNT_SESSIONID) else: self.api.login(ACCOUNT_USERNAME, ACCOUNT_PASSWORD) self.api.dump_settings(filename) super().__init__(*args, **kwargs)
class UploadToIG: def __init__(self, folder_one, folder_two): self.folder_one = folder_one self.folder_two = folder_two self.list_files_one = folder_to_list(folder_one) self.list_files_two = folder_to_list(folder_two) self.cl = Client() self.cl.login(ACCOUNT_USERNAME, ACCOUNT_PASSWORD) create_dir(CURRENT_FOLDER) create_dir(ERRORS_FOLDER) def upload(self, image_one, image_two, caption): self.cl.album_upload([image_one, image_two], caption=caption) def process(self): while self.list_files_one: # take first element file_one = self.list_files_one[0] if self.list_files_one else None file_two = self.list_files_two[0] if self.list_files_two else None # move it to the current folder img_one = CURRENT_FOLDER + file_one img_two = CURRENT_FOLDER + file_two os.replace(self.folder_one + file_one, img_one) os.replace(self.folder_two + file_two, img_two) del (self.list_files_one[0]) del (self.list_files_two[0]) # upload to IG try: self.upload(image_one=img_one, image_two=img_two, caption=CAPTION) except: os.replace(img_one, ERRORS_FOLDER + file_one) os.replace(img_two, ERRORS_FOLDER + file_two)
def check_instagram_subscribe(instagram_id): """ Проверка подписки в Instagram """ if instagram_id is None: return 'Не подписан' cl = Client() cl.login(INSTAGRAM_LOGIN, INSTAGRAM_PASSWORD) user = cl.user_id_from_username(instagram_id) user_followers = cl.user_followers(INSTAGRAM_GROUP_ID).keys() return 'Подписан' if user in user_followers else 'Не подписан'
class ClientPublicTestCase(unittest.TestCase): api = Client() def test_user_info_gql(self): user = self.api.user_info_gql(1903424587) for key, value in { "biography": "Engineer: Python, JavaScript, Erlang...", "external_url": "https://adw0rd.com/", "full_name": "Mikhail Andreev", "pk": 1903424587, "is_private": False, "is_verified": False, "profile_pic_url": "https://...", "username": "******", }.items(): if isinstance(value, str) and "..." in value: self.assertTrue(value.replace("...", "") in user[key]) else: self.assertEqual(value, user[key])
class ClientPrivateTestCase(BaseClientMixin, unittest.TestCase): api = None def __init__(self, *args, **kwargs): filename = f'/tmp/instagrapi_tests_client_settings_{ACCOUNT_USERNAME}.json' self.api = Client() try: settings = self.api.load_settings(filename) except FileNotFoundError: settings = {} except JSONDecodeError as e: print( 'JSONDecodeError when read stored client settings. Use empty settings' ) print(str(e)) settings = {} self.api.set_settings(settings) self.api.request_timeout = 1 self.set_proxy_if_exists() self.api.login(ACCOUNT_USERNAME, ACCOUNT_PASSWORD) self.api.dump_settings(filename) super().__init__(*args, **kwargs)
from instagrapi import Client, types import datetime from weather import get_weather BASE_URL = "https://magicseaweed.com/Tynemouth-Longsands-Surf-Report/26/" CAMERA = 2 VIDEO_CLIP_LENGTH = 30 # Seconds POST_FREQUENCY = 120 # Minutes START_TIME = 8 END_TIME = 16 PAST_URL = "" USERNAME = '' PASSWORD = '' cl = Client() cl.login(USERNAME, PASSWORD) while True: try: try: os.remove("surf.mp4") except: print("no file") try: os.remove("surf.mp4.jpg") except: print("no file") now = datetime.datetime.now().time() if datetime.time(START_TIME) < now < datetime.time(END_TIME): r = requests.get(BASE_URL)
def __init__(self, *args, **kwargs): self.api = Client() super().__init__(*args, **kwargs)
ClientLoginRequired, ClientThrottledError, GenericRequestError, PleaseWaitFewMinutes, RateLimitError, SentryBlock, ) def next_proxy(): return random.choices([ 'http://*****:*****@147.123123.123:412345', 'http://*****:*****@147.123123.123:412346', 'http://*****:*****@147.123123.123:412347' ]) cl = Client(proxy=next_proxy()) try: cl.login('USERNAME', 'PASSWORD') except (ProxyError, HTTPError, GenericRequestError, ClientConnectionError): # Network level cl.set_proxy(next_proxy()) except (SentryBlock, RateLimitError, ClientThrottledError): # Instagram limit level cl.set_proxy(next_proxy()) except (ClientLoginRequired, PleaseWaitFewMinutes, ClientForbiddenError): # Logical level cl.set_proxy(next_proxy())
#!/usr/bin/env python3 import os from instagrapi import Client from PIL import Image import requests from utils import display_num, convert_num, download from tweet import twitter_post, twitter_post_image module = "Instagram" # Get Instagram cookies ACCOUNT_USERNAME = os.environ.get('INSTAGRAM_ACCOUNT_USERNAME') ACCOUNT_PASSWORD = os.environ.get('INSTAGRAM_ACCOUNT_PASSWORD') # Init cl = Client() def instagram_data(group): """Runs all the Instagram related tasks It scrapes data from Instagram for the whole group and the single artists Args: group: dictionary with the data of the group to scrape Returns: the same group dictionary with updated data """ print("[{}] Starting tasks...".format(module))
import sys print(sys.argv[1]) username = sys.argv[1] def read_file(path_file, object_hook=None): with open(path_file, 'r', encoding='utf8') as json_file: return json.load(json_file, object_hook=object_hook) if __name__ == '__main__': IG_CREDENTIAL_PATH = "credential.json" import os cl = None if os.path.exists(IG_CREDENTIAL_PATH): cl = Client(read_file(IG_CREDENTIAL_PATH)) user_id = cl.user_id_from_username(username) followers = cl.user_following(user_id) for item in followers: print(item) print("--------------------------------") chickstory = cl.user_stories(item) if chickstory != []: stories = cl.user_stories_gql(item) for itemttt in stories: ab = itertools.chain([itemttt.pk]) cl.story_seen(list(ab))
print("Match from email:", match.group(1)) match = re.search(r">(\d{6})<", body) if not match: print('Skip this email, "code" not found') continue code = match.group(1) return code return False def get_code_from_sms(username): while True: code = input(f"Enter code (6 digits) for {username}: ").strip() if code and code.isdigit(): return code return None def challenge_code_handler(username, choice): if choice == 0: return get_code_from_sms(username) elif choice == 1: return get_code_from_email(username) return False if __name__ == '__main__': cl = Client() cl.challenge_code_handler = challenge_code_handler cl.login(IG_USERNAME, IG_PASSWORD)
from instagrapi import Client from instagrapi.types import Location, Usertag # Removing of the previous post if it is not already done files = glob.glob('Image/*') for f in files: os.remove(f) # Gathering some information about the images lat, lon, country = getImage.start() USERNAME = account_username PASSWORD = acount_password # Creating a bot from instagrapi and login in into the instagram account bot = Client() bot.login(USERNAME, PASSWORD) """ Getting informations about 2 users with their Instagram user Id Instagram user Id can be get by running "print(bot.user_info_by_username(username))" User id is a integer: "123456789" """ usr1_id = bot.user_info(XXXXXXXXXXX) usr2_id = bot.user_info(XXXXXXXXXXX) # Create Usertag objet to pin on the post tag = [Usertag(user=usr1_id, x=0, y=1), Usertag(user=usr2_id, x=1, y=1)] # List of Path to images to post album_path = ["Image/Panorama.jpg", "Image/imageToPost.jpg"]
def __init__(self, *args, **kwargs): if self.api is None: self.api = Client() self.set_proxy_if_exists() super().__init__(*args, **kwargs)
def login(): global api print("Login con", user_name) if os.path.exists(path_file): api = Client(readcookie(path_file)) else: api = Client() api.uuid = "99f90278-174d-420c-9b07-47677e09ab20" api.phone_id = "51224ec5-943d-4ea8-b71d-bd3249c0d588" api.device_id = "android-ef688bb0d352317c" api.user_agent = "Instagram 135.0.0.1.1 Android (28/9.0; 420dpi; 1080x1920; OnePlus; ONEPLUS A3003; OnePlus3; qcom; en_US; 180322800)" api.client_session_id = "dfc8810b-633d-4048-b396-e170f2037832" api.login(user_name, password, relogin=True) savecookie(api.get_settings())
for hashtag in hashtags: if ht_type == 'top': ht_medias.extend( cl.hashtag_medias_top(name=hashtag, amount=amount if amount <= 9 else 9)) elif ht_type == 'recent': ht_medias.extend( cl.hashtag_medias_recent(name=hashtag, amount=amount)) return list(dict([(media.pk, media) for media in ht_medias]).values()) if __name__ == '__main__': import os log = get_logger( "example_media", **{ "level": "DEBUG", "format": "%(asctime)s %(levelname)s %(name)s: %(message)s" }) cl = Client() if os.path.exists(IG_CREDENTIAL_PATH): cl.load_settings(IG_CREDENTIAL_PATH) cl.login(IG_USERNAME, IG_PASSWORD) else: cl.login(IG_USERNAME, IG_PASSWORD) cl.dump_settings(IG_CREDENTIAL_PATH) m = get_medias(HASHTAGS, amount=4) m = filter_medias(m, like_count_min=1, days_ago_max=365) log.info(len(m))
import json import time import random from instagrapi import Client cl = Client() cl.login('USERNAME', 'PASSWORD') json.dump(cl.get_settings(), open('session.json', 'w')) # cl = Client(json.load(open('settings.json'))) print('Login Successfully...') media = cl.hashtag_medias_recent( 'python', amount=10) # get 10 recent post with python hashtag c = 0 for m in media: c += 1 try: cl.media_like(m.id) cl.media_comment(m.id, 'comment_text') # change comment text print( str(c) + ': ' + m.code + '\t\tTime: ' + str(m.taken_at) + '\t\tLike: ' + str(m.like_count) + '\t\tComment: ' + str(m.comment_count)) time.sleep(random.randint(30, 60)) # sleep to avoid the account ban except Exception as e: print(e.args) print('Done')
import io from pathlib import Path import requests import shutil import textwrap import datetime from address import Address import image_maker from image_maker import image_maker # get credentials with open("./token.txt") as f: TOKEN = f.readlines() # instagram log in bot = Client() username = TOKEN[1] password = TOKEN[2] bot.login(username, password) print("Logged in") client = commands.Bot(command_prefix=".") @client.event async def on_ready(): print("Bot is ready") @client.event async def on_message(message):
for image in post: imageset[image] = find_faces(image) final = sorted(imageset.items(), key=lambda kv: kv[1]) final = collections.OrderedDict(final) instapost = [] numofimages = 0 for number in range(len(final) - 1, -1, -1): if numofimages < 10: instapost.append(list(final.keys())[number]) numofimages += 1 if len(instapost) != 0: bot = Client() bot.login("username", "password") album_path = instapost text = "caption" bot.album_upload(album_path, caption=text) print("Posted!") else: print("No need to post") driver.quit()
import textwrap from resizeimage import resizeimage from instagrapi import Client # from instabot import Bot import os from os import environ ACCESS_KEY_UNSPLASH = environ['ACCESS_KEY_UNSPLASH'] username_insta = environ['username_insta'] password_insta = environ['password_insta'] var1 = 0 try: f = open('/app/data/_memebot_10101_uuid_and_cookie.json') setting = json.load(f) cl = Client(setting) cl.login(username_insta, password_insta) except: print("login error") def key_word(): response = requests.get( "https://uselessfacts.jsph.pl/random.json?language=en") fact = response.json()['text'] print(fact) r = Rake() r.extract_keywords_from_text(fact) key_word = r.get_ranked_phrases() unsplash_img(fact, key_word[0]) return "fact_watermark.jpg", fact
from instagrapi import Client cl = Client() cl.login("YOUR_LOGIN", "YOUR_PASSWORD") loc = cl.location_search(59.93318, 30.30605) print(loc) print("-") print("-") loc1 = cl.location_search_pk(107617247320879) print(loc1) print("-") print("-") loc2 = cl.location_search_name("Choroni") print(loc2)
) ) elif ht_type == 'recent': ht_medias.extend( cl.hashtag_medias_recent( name=hashtag, amount=amount ) ) return list(dict([(media.pk, media) for media in ht_medias]).values()) if __name__ == '__main__': import os log = get_logger("example_media", **{ "level": "DEBUG", "format": "%(asctime)s %(levelname)s %(name)s: %(message)s" }) cl = None if os.path.exists(IG_CREDENTIAL_PATH): cl = Client(read_file(IG_CREDENTIAL_PATH)) else: cl = Client() cl.login(IG_USERNAME, IG_PASSWORD) write_file(cl.get_settings(), IG_CREDENTIAL_PATH) m = get_medias(HASHTAGS, amount=4) m = filter_medias(m, like_count_min=1, days_ago_max=365) log.info(len(m))
def main(username: str, amount: int = 5) -> dict: """ Download all medias from instagram profile """ amount = int(amount) cl = Client() cl.login(ACCOUNT_USERNAME, ACCOUNT_PASSWORD) user_id = cl.user_id_from_username(username) medias = cl.user_medias(user_id) result = {} i = 0 for m in medias: if i >= amount: break paths = [] if m.media_type == 1: # Photo paths.append(cl.photo_download(m.pk)) elif m.media_type == 2 and m.product_type == 'feed': # Video paths.append(cl.video_download(m.pk)) elif m.media_type == 2 and m.product_type == 'igtv': # IGTV paths.append(cl.video_download(m.pk)) elif m.media_type == 2 and m.product_type == 'clips': # Reels paths.append(cl.video_download(m.pk)) elif m.media_type == 8: # Album for path in cl.album_download(m.pk): paths.append(path) result[m.pk] = paths print(f'http://instagram.com/p/{m.code}/', paths) i += 1 return result