Пример #1
0
    def complain(self, result):
        """Recieve the result dict object that represent the test results"""

        bot = instabot.Bot(save_logfile=False, log_follow_unfollow=False
                           )  # create the instance of the instagram bot
        bot.login(username=self.login_var.get(),
                  password=self.passwd_var.get())  # do login operation
        utils.clear_instabot_files(
            self.login_var.get())  # clear all the generated files

        try:
            media = bot.get_user_medias(
                self.provider_login_var.get(), filtration=False)[
                    0]  # get the most recent post from the provider perfil
        except Exception:
            messagebox.showerror(
                "Erro",
                "Não foi possível acessar o Instagram, verifique seu usuário e senha e tente novamente."
            )
            return False

        reclamation_message = "[RECLAMAÇÃO] - Minha internet está muito lenta, vocês só estão me entregando %.2f Megas, que representa apenas %.2f%% da velocidade contratada que foi de %.2f Megas. Para mais detalhes sobre o teste de qualidade de conexão que realizei aqui em casa: %s" % (
            self.down_shiped,
            (100 * self.down_shiped) / self.down_contract_var.get(),
            self.down_contract_var.get(), result['share'])
        bot.comment(media,
                    reclamation_message)  # post the results on the instagram
        messagebox.showinfo("Tudo OK...",
                            "A sua reclamação foi postada com sucesso...")
Пример #2
0
    def __init__(self, configfile: str = None):
        self.configfile = configfile
        parser = argparse.ArgumentParser(add_help=True)
        parser.add_argument('-settings', type=str, help="json settings file")
        args = parser.parse_args()
        self.settings = json.load(open(args.settings))

        self.logger = logger
        self.logger.add("log/{}.log".format(
            self.settings['instagram']['username']),
                        backtrace=True,
                        diagnose=True,
                        level="WARNING")

        try:
            self.logger.info("Lets do it!.")

            self.predict = Predict(
                api_key=self.settings['clarifai']['api_key'],
                logger=self.logger)

            self.instabot = instabot.Bot(base_path="InstaBot/")
            self.instabot.logger = self.logger
            self.instabot.api.logger = self.logger

            self.instabot.login(
                username=self.settings['instagram']['username'],
                password=self.settings['instagram']['password'],
                proxy=None)

        except Exception as err:
            self.treat_exception(err)
            self.end()
            pass
Пример #3
0
def get_image_posted(username, password, folder_path):
    folder_with_picture_names = listdir(folder_path)
    bot = instabot.Bot()
    bot.login(username=username, password=password)

    for picture_name in folder_with_picture_names:
        bot.upload_photo(folder_path + picture_name)
Пример #4
0
 def launch(self):
     b = instabot.Bot()
     b.login(username="******", password="******")
     self.format_img()
     self.resize()
     b.upload_photo(self.img_path, self.caption)
     b.logout()
Пример #5
0
    def __init__(
            self,
            timeline_comment_path=None,
            whitelist=None,
            all_comments=None,
            like_first=False,
            follow_followers=False,
            amount=0,
            stop_words=['shop', 'store', 'free', 'buy', 'compra', 'comprar']):

        self.bot = instabot.Bot(stop_words=[])
        #        self.bot.proxy = "free-nl.hide.me"
        self.bot.login()
        self.timeline_comment = timeline_comment_path
        self.all_comments = all_comments
        self.like_after_follow = like_first
        self.follow_followers = follow_followers
        self.amount = amount
        if self.timeline_comment is not None:
            self.timeline_comment_number = get_size(self.timeline_comment)

        if self.all_comments is not None:
            self.all_comments_number = get_size(self.all_comments)
        if whitelist is not None:
            self.add_whiteList(whitelist)
Пример #6
0
def send_images_to_instagram(login, password):
    files = os.listdir('images_for_inst')
    images = filter(lambda x: x.endswith('.jpg'), files)
    bot = instabot.Bot()
    bot.login(username=login, password=password)
    for image in tqdm(images):
        bot.upload_photo(os.path.join('images_for_inst', image))
Пример #7
0
def upload_photos(username, password, photos_dir, file_with_published):
    bot = instabot.Bot()
    bot.login(username=username, password=password)
    for photo in os.listdir(photos_dir):
        if not check_is_published(photo, file_with_published):
            bot.upload_photo('{}/{}'.format(photos_dir, photo))
            add_to_published(photo, file_with_published)
        print('Skiped')
def place_or_music_or_thought():
    import instabot
    bot = instabot.Bot()
    bot.login(username=USERNAME, password=PASSWORD, proxy=None)

    latitude, longitude = 0, 0

    if 0:  #not randint(0, 3):
        pic, venue, locale, type_ = go_random_tripadvisor()
        caption = get_random_tripadvisor_caption(venue, locale, type_)
        fn = "{}.jpg".format(randint(1111, 9999))
        img = get_web_data(pic).content

    elif randint(0, 1):  #need to fix randint(0, 2):

        latitude, longitude, place_name, img = get_random_place()
        img = get_web_data(img).content
        caption = get_random_travel_caption(place_name)
        text = "".join([t for t in place_name if t.isalpha()])
        fn = "{}.jpg".format(text)

    elif randint(0, 1):

        song_data = get_song()
        song, artist = song_data['song'], song_data['artist']
        text = "".join([t for t in artist + song if t.isalpha()])
        fn = "{}.jpg".format(text)
        img = get_web_data(song_data['img']).content
        youtube = song_data["youtube"]
        caption = get_random_song_caption(song, artist, youtube)

    else:

        caption = get_random_thought()
        img = random_pic()
        fn = ""
    try:
        with open("previous_captions.json", "r", encoding="utf-8") as f:
            previous_captions = loads(f.read())

        for cap in previous_captions:
            if similarity(cap, caption) >= TOO_SIMILAR:
                print(cap)
                print("...and...")
                print(caption)
                print("... deemed too similar")
                place_or_music_or_thought()

        previous_captions.append(caption)

    except:
        previous_captions = [caption]

    post_image(bot, caption, img, fn, latitude, longitude)
    with open("previous_captions.json", "w", encoding="utf-8") as f:
        f.write(dumps(previous_captions))

    bot.logout()
Пример #9
0
def unfollow(username):
    for x in accounts:
        bot = instabot.Bot()
        uname = x.split(":")[0]
        upass = x.split(":")[1]
        bot.login(username=uname, password=upass)
        bot.unfollow(username)
        clear()
        bot.logout
def publish_on_instagram(photos):
    bot = instabot.Bot()
    bot.login(username=login, password=password)
    for photo in photos:
        try:
            bot.upload_photo(photo)
        except PermissionError:
            time.sleep(2)
            continue
Пример #11
0
def post(caption, username="", password=""):
    caption += " #bot #random"
    bot = instabot.Bot()
    bot.login(username=username, password=password)
    # cleanup before posting
    try:
        os.remove('post.jpg.REMOVE_ME')
    except FileNotFoundError:
        print('nothing to clear.. for this time')
        pass
    bot.upload_photo('post.jpg', caption=caption)
Пример #12
0
def upload_photo_to_insta(image_folder_path, login, password):
    bot = instabot.Bot()
    bot.login(username=login, password=password)
    valid_files_for_instagram = filter(
        lambda x: (x.endswith('.jpg') | x.endswith('.png') | x.endswith('.gif')
                   | x.endswith('.jpeg')), listdir(image_folder_path))
    list_image_path_and_name = [[
        joinpath(image_folder_path, valid_file), valid_file
    ] for valid_file in valid_files_for_instagram]
    for image_path_and_name in list_image_path_and_name:
        image_path, image_name = image_path_and_name
        bot.upload_photo(image_path, caption=image_name)
Пример #13
0
def main():
    load_dotenv()
    login = getenv('INSTAGRAM_LOGIN')
    password = getenv('INSTAGRAM_PASSWORD')
    bot = instabot.Bot()
    bot.login(username=login, password=password)
    urllib3.disable_warnings()
    fetch_spacex_last_launch()
    fetch_hubble_image()
    for name in listdir('image'):
        file = crop_photo(f'image/{name}')
        bot.upload_photo(file)
        remove(f'{file}.REMOVE_ME')
Пример #14
0
def log_to_user(account_data):
    try:
        L = instaloader.Instaloader()
        L.login(user=account_data["user"],passwd=account_data["pass"])
    except:
        print("Error couldn't login to account with instaloader")

    try:
        bot = instabot.Bot()
        bot.login(username = account_data["user"], password = "******")
    except:
        print("Error couldn't login to account with instabot")

    return L, bot
Пример #15
0
def main():
    bot = instabot.Bot()
    bot.login()

    counter = 0
    os.system("cp msjww.jpg msjwwcopy.jpg")

    while (True):
        bot.upload_photo("msjwwcopy.jpg", caption="#msjww19")
        print("Number of posts: ", counter)
        counter += 1

        os.system("rm msjwwcopy.jpg.REMOVE_ME")
        os.system("cp msjww.jpg msjwwcopy.jpg")
Пример #16
0
def get_winners(inst_login, inst_password, post_url, author_username, 
                    debug_mode):
    bot = instabot.Bot()
    bot.login(username=inst_login, password=inst_password)
    if not bot.api.last_response.status_code == 200:
        raise AuthError(f"Can't authozrize in Instagramm "
            "{bot.api.last_response}")
    try:
        comments = get_comments_of_post(
            bot, 
            post_url, 
            debug_mode
        )
    except ValueError as error:
        raise ValueError(error)
    filtered_comments = filter_comments_with_link_to_friend(comments)
    if not filtered_comments:
        return 
    validation_errors = []
    try:
        comments_with_likes = list(validate_user_names_by_likes(
            bot,
            filtered_comments,
            post_url,
        ))
    except ValidationError as error:
        comments_with_likes = filtered_comments
        validation_errors.append(error)
    try:    
        comments_of_followers = list(validate_user_names_by_following(
            bot,
            comments_with_likes,
            author_username,
        ))
    except ValidationError as error:
        comments_of_followers = comments_with_likes
        validation_errors.append(error)       
    try:        
        comments_with_friends = list(validate_user_names_by_real_friends(
            bot, 
            comments_of_followers,
            debug_mode,
        ))
    except ValidationError as error:
        comments_of_followers = comments_with_likes
        validation_errors.append(error)
    participants_id = [(comment["comment"]["user_id"], comment["username"]) 
                            for comment in comments_with_friends]
    winners = set(participants_id)
    return (winners, validation_errors)
Пример #17
0
 def __init__(self, token):
     if PP_instagram.__instance__ is None:
         PP_instagram.__instance__ = self
         self._bot = instabot.Bot()
         credentials = token.strip().split(',')
         try:
             self._bot.login(username=credentials[0],
                             password=credentials[1],
                             use_cookie=False,
                             is_threaded=True)
             print(" > Instagram: Authentication OK")
         except Exception as err:
             print(" > Instagram: unable to login. " + str(err))
             raise Exception("Unable to login in Instagram")
Пример #18
0
def main():
	bot = instabot.Bot()
	bot.login()

	pauseseconds = random.randrange(60, 90, 1)
	os.system("cp msjww.jpg msjwwcopy.jpt")

	while(True):
		bot.upload_photo("msjwwcopy.jpg", caption="#msjww19")
		time.sleep(pauseseconds)
		pauseseconds = random.randrange(60, 90, 1)
		print("Waiting: ", pauseseconds)

		os.system("rm msjwwcopy.jpg.REMOVE_ME")
		os.system("cp msjww.jpg msjwwcopy.jpg")
Пример #19
0
def init_bot():
    proxy = config['proxy']['url'] if 'proxy' in config and 'url' in config['proxy'] else None
    print(proxy)
    bot = instabot.Bot(filter_business_accounts=True,
        filter_verified_accounts=False,
        max_followers_to_follow=10000,
        max_following_to_follow=5000,
        filter_users_without_profile_photo=True,

    )
    bot.login(
        username=config['username'],
        proxy=proxy)
    
    return bot
Пример #20
0
def main():
    import argparse

    parser = argparse.ArgumentParser(description="Instacron.")
    parser.add_argument(
        "--fname",
        metavar="fname",
        type=str,
        default=None,
        help="filename of the photo, random if empty.",
    )
    parser.add_argument(
        "--caption_only", action="store_true", help="only return the caption."
    )
    args = parser.parse_args()
    caption = get_random_quote(
        ["Hunter S. Thompson", "Albert Einstein", "Charles Bukowski"]
    )
    dir_path = os.path.dirname(os.path.realpath(__file__))
    uploaded_file = os.path.join(dir_path, "uploaded.txt")

    if args.fname is None:
        photo_folder = os.path.join(dir_path, "photos")
        photo = choose_random_photo(uploaded_file, photo_folder)
    else:
        photo = args.fname

    pic = prepare_and_fix_photo(photo)
    caption += get_caption(photo)
    print(caption)

    if not args.caption_only:
        print(f"Uploading `{photo}`")
        print(os.path.basename(photo))
        bot = instabot.Bot()
        bot.login(**read_config())
        upload = bot.upload_photo(pic, caption=caption)

        # After succeeding append the fname to the uploaded.txt file
        photo_base = os.path.basename(photo)
        if upload:
            time.sleep(4)  # XXX: why this?
            print(colored(f"Upload of {photo_base} succeeded.", "green"))
            append_to_uploaded_file(uploaded_file, photo_base)
        else:
            print(colored(f"Upload of {photo_base} failed.", "red"))
        bot.logout()
Пример #21
0
def main():
    load_dotenv()
    username = os.getenv('INST_LOGIN')
    password = os.getenv('INST_PWD')

    bot = instabot.Bot()
    bot.login(username=username, password=password)
    timeout = 30
    images = os.listdir("images")

    for image in images:
        path_to_file = Path.cwd().joinpath('images', image)
        try:
            bot.upload_photo(path_to_file, caption=f'This is images/{image} photo! Nice shot!')
            time.sleep(timeout)
        except OSError:
            continue
    bot.logout()
Пример #22
0
    def __init__(self ,timeline_comment_path=None, whitelist= None, all_comments=None,
                like_first=False,follow_followers=False
                , stop_words=None,proxy=None,
                followers=None, blacklist=None, hashtags=None,
                locations=None, config=None):


        filters = read_dict_file(config)
        self.bot = instabot.Bot(whitelist=whitelist,blacklist=blacklist,
             max_followers_to_follow=int(filters["max_followers_to_follow"]),
                 min_followers_to_follow=int(filters["min_followers_to_follow"]),
                 max_following_to_follow=int(filters["max_following_to_follow"]),
                 min_following_to_follow=int(filters["min_followers_to_follow"]),
                 max_followers_to_following_ratio=int(filters["max_followers_to_following_ratio"]),
                 max_following_to_followers_ratio=int(filters["max_following_to_followers_ratio"]),
                 min_media_count_to_follow=int(filters["min_media_count_to_follow"]),)
        self.bot.login()

        #my internal variables


        self.like_after_follow = like_first
        self.follow_followers=follow_followers
        self.max_following_amount = filters["follow_amount"]
        self.max_likes_amount = filters["like_amount"]
        self.linking_interval = filters["like_time"]
        self.following_interval = filters["follow_time"]
        self.config = filters
        #paths
        self.hashtags_file = hashtags
        self.timeline_comment = timeline_comment_path
        self.all_comments = all_comments



        if self.timeline_comment is not None:
            self.timeline_comment_number = get_size(self.timeline_comment)

        if self.all_comments is  not None:
            self.all_comments_number = get_size(self.all_comments)
        if whitelist is not None:
            self.add_whiteList(whitelist)
def album_cover_challenge(day):
    try:
        import instabot
        bot = instabot.Bot()
        bot.login(username=USERNAME, password=PASSWORD, proxy=None)

        song_data = get_song()
        song, artist = song_data['song'], song_data['artist']
        text = "".join([t for t in artist + song if t.isalpha()])
        fn = "{}.jpg".format(text)
        img = get_web_data(song_data['img']).content
        youtube = song_data["youtube"]
        caption = """DAY {}
        
        I've been given a task to choose ten albums that greatly influenced my taste in music. One album per day for ten consecutive days. No explanations, no reviews, just album covers.""".format(
            day)
        post_image(bot, caption, img, fn)
        bot.logout()
        return True
    except:
        return False
Пример #24
0
def upload_insta():
    load_dotenv()

    username = os.getenv('INSTAGRAM_USERNAME')
    password = os.getenv('INSTAGRAM_PASSWORD')

    parser = create_parser()
    args = parser.parse_args()
    images_path = args.path

    insta_path = 'insta_images'
    Path(insta_path).mkdir(parents=True, exist_ok=True)

    images_names = os.listdir(images_path)

    for image_name in images_names:
        image = Image.open(f'{images_path}/{image_name}')
        image.thumbnail((1080, 1080))
        rgb_image = image.convert('RGB')
        root_ext_image_name = os.path.splitext(image_name)
        rgb_image.save(f'{insta_path}/{root_ext_image_name[0]}.jpg',
                       format='JPEG')

    bot = instabot.Bot()
    bot.login(username=username, password=password)

    insta_images_names = os.listdir(insta_path)

    try:
        for insta_image_name in insta_images_names:
            bot.upload_photo(f'{insta_path}/{insta_image_name}')
    except Exception as e:
        print(e)
        print(
            'Не все ваши фотографии удалось загрузить. Попробуйте еще раз позже.'
        )
    finally:
        shutil.rmtree(insta_path)
Пример #25
0
    def login_instagram(self):
        #Try logging in, if there is a problem, try again.
        try:
            #Instagram Username and Password, insta_keys[0] : Username, insta_keys[1] : Password
            insta_keys = ['username', 'password']
            fp = open(self.access_keys_i_loc, 'r')
            insta_keys[0] = fp.readline().rstrip('\n')
            insta_keys[1] = fp.readline().rstrip('\n')
            print("-Using Login Credentials-\n\tUsername :"******"\n\tPassword :"******"Starting Instagram login...")
            instagram_credential = instabot.Bot()
            instagram_credential.login(username=insta_keys[0],
                                       password=insta_keys[1])
            print("Instagram login successful.")
            return insta_keys, instagram_credential
        except:
            print(
                "ERROR :::> Instagram Login Failed. Retrying in 10 seconds...")
            time.sleep(10)
            return self.login_instagram()
Пример #26
0
import instabot
bot = instabot.Bot()
bot.login()
1
#Obtener la lista de followers que interesa.

hashtags = ["Bariloche", "SanMartin", "Patagonia", "Sur"]
hashtag_users = []
for hashtag in hashtags:|
    users_one_hashtag = bot.get_hashtag_users(hashtag)
    for users in users_one_hashtag:
        hashtag_users.append(users)

#La lista de potenciales a seguir está en hashtag_users

#Pruebo seguir a 50
bot.follow_users(hashtag_users[1:50])

# Quiero obtener toda la informacion que se pueda de ellos.

# df = DataFrame(list(diccionario.items()) #Lo transformo a dataframe, o me amigo con los diccionarios.

user_info_dic_list = []
for user in hashtag_users:
    user_info = bot.get_user_info(user)  # Es un diccionario
    user_info_dic_list.append(user_info)

ds = user_info_dic_list.append
d = {}
for k in ds[1].keys():
    d[k] = tuple(d[k] for d in ds)
Пример #27
0
def main():
    global bot
    bot = instagram(instabot.Bot(comment_delay=0))
Пример #28
0
 def __init__(self, imgs: List, usr, pwd) -> None:
     self.images = imgs
     self._ig = instabot.Bot()
     self.login(usr, pwd)
     self._timeout = 30 * 60  # 30 minutes
Пример #29
0
 def __init__(self, _username='', _password=''):
     self._username = '******'
     self._password = '******'
     self.acting = instabot.Bot()
Пример #30
0
import instabot

bot = instabot.Bot()  #instagram bot


def logIn():
    """Log in
    """
    username = ""  #your username
    password = ""  #your password
    bot.login(username=username, password=password)


def uploadPost(picturePath, caption):
    """Upload picture
    Args:
        picturePath: path of the picture
        caption: caption of the picture
    """
    bot.upload_photo(picturePath, caption=caption)