예제 #1
0
    def __init__(self, web_driver):
        self.logger = logging.getLogger()

        self.instagram_api = InstagramAPI()

        self.browser = web_driver

        # wait object to wait for elements to be loaded
        self.wait = WebDriverWait(driver=self.browser, timeout=5)

        self.liked_media_session_count = 0

        self.total_media_like_count = 0

        self.is_logged_in = False

        self.slept_after_limit = False
예제 #2
0
def show_unfollower():    
    followers   = []
  
    next_max_id = True
    while next_max_id:
        print next_max_id
        #first iteration hack
        if next_max_id == True: next_max_id=''
        _ = InstagramAPI.getUserFollowers(user_id,maxid=next_max_id)
        followers.extend ( InstagramAPI.LastJson.get('users',[]))
        next_max_id = InstagramAPI.LastJson.get('next_max_id','')
        time.sleep(1)
        
    followers_list=followers
    user_list = map(lambda x: x['username'] , following_list)
    following_set= set(user_list)
    user_list = map(lambda x: x['username'] , followers_list)
    followers_set= set(user_list)
    
    not_following_back=following_set-followers_set
    Label(functions_screen, text="\n".join(map(str, not_following_back))).pack()
예제 #3
0
def getTime(user, password):
    api = InstagramAPI(user, password)
    api.login()
    #print(api.username_id)
    api.getTimeline()
    g = api.LastJson
    ##print(g)
    ##
    ##likesval = 0
    ##count = 0
    ##
    #for x in g['items']:
    ##    likesval += x['like_count']
    ##    count += 1
    ##        print(y)
    ##
    ##print(likesval)
    ##print(count)

    totallikes = 0
    avg = 0

    for x in g["items"]:
        avg += x['like_count'] * x['taken_at']
        totallikes += x['like_count']
        #print(x)
    #	for y in x.keys():
    #		print(y)

    avg = avg / totallikes  #get avg timestamp
    #avg = avg * 1000
    avg = math.floor(avg)

    #the following 3 lines rounds the time down to the nearest hour (ex 1:05 goes to 1:00)
    avg = avg / 3600
    avg = math.floor(avg)
    avg = avg * 3600

    returnstring = "Your followers are most active between "
    returnstring += datetime.datetime.fromtimestamp(
        int(avg)).strftime('%H:%M:%S')
    returnstring += " and "
    returnstring += datetime.datetime.fromtimestamp(
        int(avg + 3600)).strftime('%H:%M:%S')
    returnstring += " (24 hour notation)."

    return returnstring
예제 #4
0
파일: app.py 프로젝트: jajosheni/instaBot
def login():
    username = input('instabot> Username: '******'instabot> Password: '******'user']
        global followers_count, following_count
        followers_count = user['follower_count']
        following_count = user['following_count']
        time.sleep(0.5)
        os.system("cls")
    else:
        print("Cannot login, please check your credentials.")
        login()
예제 #5
0
def main():
    """Console script for grips."""
    parser = argparse.ArgumentParser()
    parser.add_argument('username', help="Instagram username")
    parser.add_argument('password', help="Instagram password")
    args = parser.parse_args()

    api = InstagramAPI(args.username, args.password)

    api.login()

    # currently not working due to Instagram
    photo_path = 'C:\\Users\\goali\\Downloads\\www.reddit.com_r_science_.jpg'
    caption = "Interesting"
    api.uploadPhoto(photo_path, caption=caption)

    return 0
예제 #6
0
def main(photo, igCaption):
    dir = os.getcwd()
    
    #read login file
    os.chdir("..")
    with open("instaLogin.txt", 'r') as f: 
        igUser = f.readline()
        igPassword = f.readline()
    igapi = InstagramAPI(igUser, igPassword)
    igapi.login() #login
    
    #start uploading
    os.chdir(dir)
    print("----------------------------------------------------------")
    print("Now uploading this photo to Instagram: " + photo)
    igapi.uploadPhoto(photo, caption=igCaption, upload_id=None)
    print("Upload Successful")
예제 #7
0
 async def followRandom(self):
     try:
         api = InstagramAPI(self.account, self.password)
         if (api.login()):
             amountToFollow = r.randint(self.follow_amount_min,
                                        self.follow_amount_max)
             hashValues = list(self.hashtags.values())
             hashList = r.choice(hashValues)
             hashtag = r.choice(hashList)
             mediaList = self.getHashtagFeed(hashtag)
             amountFollowed = 0
             while mediaList and amountFollowed < amountToFollow:
                 mediaId = mediaList.pop(r.randint(0, len(mediaList) - 1))
                 api.like(mediaId)
                 self.db.insert("Like", [self.account, mediaId])
                 likersList = self.getMediaLikers(mediaId, api)
                 if not likersList:
                     continue
                 r.shuffle(likersList)
                 for i in range(
                         0,
                         min(amountToFollow - amountFollowed,
                             len(likersList))):
                     print("trying to follow")
                     try:
                         user_pk = likersList[i]
                         followers = self.db.c.execute(
                             "SELECT PK from FOLLOWING").fetchall()
                         if user_pk not in followers:
                             api.follow(user_pk)
                             self.db.insert("Following",
                                            [self.account, user_pk])
                     except Exception as e:
                         print(
                             "ERRROR DURING followRandom while trying to follow"
                         )
                     finally:
                         await asyncio.sleep(r.randint(5, 120))
                         amountFollowed += 1
     except Exception as e:
         print("ERROR DURING followRandom: ", e)
예제 #8
0
def get_credentials(file_name):
	# Local variables
	count = 0
	user = ""
	pswd = ""

	# ******** start get_credentials() ******** #

	# Get keys from file
	f = open(file_name, "r")
	for line in f:
		if line.strip()[0] == "#":
			continue
		elif count == 0:
			user = line.strip()
			count += 1
		elif count == 1:
			pswd= line.strip()
			count += 1
	f.close()

	instagram = InstagramAPI(user, pswd)
	return instagram
예제 #9
0
def add_hash_tag_users(hash_tag):
    login_obj = LoginData.objects.all().first()

    username = login_obj.username
    password = login_obj.password

    tags = TargetHashTags(htags=hash_tag, login_user=login_obj)
    tags.save()

    api = InstagramAPI(username, password)

    if (api.login()):
        api.getSelfUserFeed()  # get self user feed
        print(api.LastJson)  # print last response JSON
        print("Login succes!")
    else:
        print("Can't login!")

    api.getHashtagFeed(hash_tag)

    user_ids = []

    response = api.LastJson

    with open('hashtags_feed.txt', 'w') as outfile:
        json.dump(response, outfile)

    with open('hashtags_feed.txt') as json_data:
        d = json.load(json_data)

        for x in d['ranked_items']:
            for keys in x:
                if keys == 'user':
                    user_ids.append(x['user']['username'])

    queryset = TargetHashTags.objects.all().first()

    for user in user_ids:
        TargetedHashTagUsers.objects.create(targethashtags=tags,
                                            user_name=user)
def unFollow(number: int):
    api = InstagramAPI(USERNAME, PASS)
    api.login()
    user_id = api.username_id
    followers = getTotalFollowers(api, user_id)
    following = getTotalFollowings(api, user_id)
    nonFollow = nonFollowers(followers, following)
    totalNonFollowers = len(nonFollow)
    print('Number of followers:', len(followers))
    print('Number of followings:', len(following))
    print('Number of nonFollowers:', len(nonFollow))

    for i in range(number):
        if i >= totalNonFollowers:
            break
        user = list(nonFollow.keys())[len(nonFollow) - 1]
        api.unfollow(nonFollow[user])
        nonFollow.pop(user)
예제 #11
0
파일: test.py 프로젝트: NickVK9/insta-pump
def search(user):  #search procedure
    mean_likes = 0
    mean_comments = 0
    mean_time = list()
    followers = 0
    following = 0
    media_count = 0

    api = InstagramAPI('zaribrown37', 'youknowguysblm123')
    api.login()
    api.searchUsername(user)
    result = api.LastJson

    followers = result['user']['follower_count']  #getting info from account
    following = result['user']['following_count']
    media_count = result['user']['media_count']
    biography = result['user']['biography']
    category = result['user']['category']

    username_id = result['user']['pk']  # Get user ID
    user_posts = api.getUserFeed(username_id)  # Get user feed
    result = api.LastJson

    for i in range(18):  #getting info from last 18 publications
        mean_likes += result['items'][i]['like_count'] / 18
        mean_comments += result['items'][i]['comment_count'] / 18
        mean_time.append(result['items'][i]['taken_at'])
    mean_time = parse_time(mean_time)

    print('User: '******'Followers: ', followers)
    print('Following: ', following)
    print('Publications count: ', media_count)
    print('Category: ', category)
    print('Mean likes', round(mean_likes, 2))
    print('Mean comments: ', round(mean_comments, 2))
    print('Mean time between publications(days): ', round(mean_time, 3))
    print('Bio: ', biography)
예제 #12
0
def pubblica():
    print("..Pubblicazione")

    IGUSER = '******'  
    PASSWD = '...la tua password'

    IGCaption = 'Questa è la descrizione della nostra immagine posso aggiungere anche dei tag #motivazione #dailymotivational...'

    igapi = InstagramAPI(IGUSER, PASSWD)
    #Ci colleghiamo all'API di instgram
    igapi.login() 
    
    #Pubblico l'immagine
    photo = foldername'+ fileNames[0]
    igapi.uploadPhoto(photo, caption=IGCaption, upload_id=None)
    
    #eliminiamo la foto pubblicata
    print("Elimino : " + foldername + fileNames[0])
    os.remove(foldername + fileNames[0])
예제 #13
0
def post_once(bot, job):
    try:
        username, password = job.context.split(':')

        log.info('CRAWLER: start post')
        t = time.time()
        posts = search(last_post_time())
        posts.reverse()
        log.info('CRAWLER: found {} posts, for {} sec'.format(
            len(posts), round(time.time() - t, 2)))

        if posts:
            ig = InstagramAPI(username, password)
            ig.login()

            log.info('CRAWLER: login ok')
            for p in posts:

                try:
                    files = download(p.urls)
                    media = list({'type': 'photo', 'file': f} for f in files)

                    caption = u'Panorama from @' + p.username + u'\n' + p.caption
                    caption = caption.replace(u'#photoslicebot', u'')
                    # проверить на длину caption
                    ig.uploadAlbum(media, caption=caption)
                    log.info(
                        'CRAWLER: upload {} from user {} successfully'.format(
                            p.code, p.username))
                    report.track_event(0, 'crawler', 'new post')

                except Exception, err:
                    log.error(
                        'CRAWLER: download or upload album error: {}'.format(
                            err))
                    report.track_event(0, 'crawler',
                                       'download or upload error')

                finally:
                    for f in files:
                        os.unlink(f)
예제 #14
0
def igfeed():
    from InstagramAPI import InstagramAPI
    if request.method == 'GET':
        username = request.args.get('user')
        password = request.args.get('pass')
        usertofind = request.args.get('usertofind')
    else:
        username = request.values.get('users')
        password = request.values.get('passws')

    InstagramAPI = InstagramAPI(username, password)
    InstagramAPI.login()

    user_name = usertofind

    InstagramAPI.searchUsername(user_name)
    #filter info about user
    username_id = InstagramAPI.LastJson["user"]["pk"]
    x = InstagramAPI.LastJson["user"]["full_name"]
    n = InstagramAPI.LastJson["user"]["biography"]
    y = InstagramAPI.LastJson["user"]["follower_count"]
    z = InstagramAPI.LastJson["user"]["following_count"]

    result = InstagramAPI.getTotalUserFeed(username_id)

    time.sleep(2)

    loc = [{"name": x, "bio": n, "followers": y, "followings": z}]
    #filter lat, lng, label and time
    for u in result:
        try:
            loc.append({
                "lat": u['location']['lat'],
                "lng": u['location']['lng'],
                "label": u['location']['name'],
                "time": u['taken_at']
            })
        except KeyError:
            pass

    return jsonify(loc)
def unfollow(username, pwd, listFollower, LitsFollowing):
    API = InstagramAPI(username, pwd)
    API.login()
    s1 = set(listFollower)
    s2 = set(LitsFollowing)
    s3 = s2 - s1
    lista = list(s3)

    print('Numero de followers ', len(s1))
    print('Numero de Followigs', len(s2))

    print('Total de unfollows', len(lista))
    for x in lista:
        print(x)
        g = API.unfollow(x)
        while g == False:
            print("wait")
            n = randint(50, 90)
            time.sleep(3 * n)
            g = API.unfollow(x)
        time.sleep(3)
예제 #16
0
def post_trending_repo(repo):
    temp_dir = TemporaryDirectory()

    if not _should_post_repo(repo):
        _logger.info(f"Not appropriate for posting: {repo.link}")
        return

    gif = _download_gif_file(repo.gif_link, directory=temp_dir)
    mp4 = _convert_gif_to_mp4(gif, output_directory=temp_dir)
    shortened_mp4 = _shorten_video(mp4, directory=temp_dir)
    resized_mp4 = _resize_video(shortened_mp4, directory=temp_dir)
    thumbnail = _generate_thumbnail_from_video(resized_mp4, directory=temp_dir)
    caption = _generate_caption(repo=repo)

    instagram_client = InstagramAPI("github_trending_videos",
                                    os.environ.get('INSTAGRAM_PASSWORD'))
    instagram_client.login()  # login

    instagram_client.uploadVideo(resized_mp4, thumbnail, caption=caption)

    temp_dir.cleanup()
예제 #17
0
def add_attribute(data_frame, attribute, login, password):
    user_names = data_frame['USERNAME']
    length = len(user_names)

    api = InstagramAPI(login, password)
    api.login()

    to_add = list()
    for i in tqdm(range(length)):
        api.searchUsername(user_names[i])
        last_json = api.LastJson
        print(last_json)

        if attribute == 'ID':
            to_add.append(last_json['user']['pk'])
        elif attribute == 'FOLLOWERS':
            to_add.append(last_json['user']['followers_count'])

    # if attribute in data_frame.columns:
    #     to_add = [item for item in data_frame[attribute] if item != 0]
    #     start = [item for item in data_frame[attribute]].index(0)
    # else:
    #     to_add = list()
    #     start = 0

    # Go to specific user
    # for i in tqdm(range(start, length), unit='user'):
    #     url = 'https://www.instagram.com/' + user_names[i] + '/?__a=1'
    #     data = requests.get(url=url)
    #     data = data.json()
    #
    #     value = int()
    #     if attribute == 'ID':
    #         value = data['graphql']['user']['id']
    #     elif attribute == 'FOLLOWERS':
    #         value = data['graphql']['user']['edge_followed_by']['count']
    #
    #     to_add.append(value)

    data_frame[attribute] = pd.Series(to_add)
예제 #18
0
파일: models.py 프로젝트: Deriont/AUDS
    def serchComentarios(self):
        anonimUser = instagramUser.objects.get(pk=1)
        api = InstagramAPI("taeusdsspyt", "test.pyt")
        api.login()
        has_more_comments = True
        max_id = ''
        anonimComments = []

        logging.warning('Media Id ' + self.instaId)

        while has_more_comments:
            api.getMediaComments(self.instaId, max_id=max_id)
            commentsJson = api.LastJson
            logging.warning('comentJsonBug: ' +
                            str(commentsJson.get('comments')))

            #verificar usuarios
            tmpUsList = []
            for tmpComment in commentsJson.get('comments'):
                tmpUsList.append(str(tmpComment.get('user_id')))
            if len(tmpUsList) != 0:
                userList = instagramUser.objects.filter(pk__in=tmpUsList)
                logging.warning('logged comment user ' + str(userList))
            else:
                logging.warning('Not logged user comments')

            #Despues de sacar la lista de intagram user la asignamos en este bucle
            for tmpComment in commentsJson.get('comments'):
                if len(tmpUsList) != 0:
                    self.setComentUser(userList, tmpComment, anonimComments)
                self.setComentUserAnonim(anonimComments, anonimUser)
                #logging.warning('No registered Users on new comments')
            has_more_comments = commentsJson.get('has_more_comments', False)
            if has_more_comments:
                max_id = commentsJson.get('next_max_id', '')
                time.sleep(2)
                #logging.warning('Comment Json: ' + str(commensJson))

        return 'Comment Json: ' + str(commentsJson.get('comments'))
예제 #19
0
def setup_list_of_users(data_path, login, password):
    users_data_frame = pd.read_csv(data_path)
    users_names = users_data_frame['USERNAME'].tolist()

    # Add ID to csv
    api = InstagramAPI(login, password)
    api.login()

    users_username = list()
    users_full_name = list()
    users_id = list()
    users_private = list()
    users_media_count = list()
    users_follower_count = list()
    users_following_count = list()
    users_biography = list()

    for user in tqdm.tqdm(users_names):
        api.searchUsername(user)
        last_json = api.LastJson
        users_username.append(last_json['user']['username'])
        users_full_name.append(last_json['user']['full_name'])
        users_id.append(last_json['user']['pk'])
        users_private.append(last_json['user']['is_private'])
        users_media_count.append(last_json['user']['media_count'])
        users_follower_count.append(last_json['user']['follower_count'])
        users_following_count.append(last_json['user']['following_count'])
        users_biography.append(last_json['user']['biography'])

    users_list = [('NAME', users_full_name), ('USERNAME', users_username),
                  ('ID', users_id), ('PRIVATE', users_private),
                  ('MEDIA_COUNT', users_media_count),
                  ('FOLLOWERS', users_follower_count),
                  ('FOLLOWING', users_following_count),
                  ('MEDIA_COUNT', users_biography)]
    # TODO gerer les erreurs en memorisant a chaque iteration

    return pd.DataFrame.from_items(users_list)
예제 #20
0
def follow_me():
    with open('data_feeded.csv', 'r') as f:
        reader = csv.reader(f, delimiter=',')
        i = 0
        info_generate = {}
        for row in reader:
            info_generate[i] = {}
            info_generate[i]['username'] = row[0]
            info_generate[i]['password'] = row[1]
            info_generate[i]['email'] = row[2]
            info_generate[i]['full_name'] = row[3]
            info_generate[i]['user_id'] = row[3]
            username = info_generate[i]['username']
            pwd = info_generate[i]['password']
            user_id = info_generate[i]['user_id']
            API = InstagramAPI(username, pwd)
            try:
                API.login()
                API.follow(my_user_id)
                print API.LastJson
            except:
                continue
            i += 1
예제 #21
0
 async def likeTimelineRandom(self):
     try:
         api = InstagramAPI(self.account, self.password)
         if api.login():
             if not api.getTimeline():
                 raise Exception("Couldn't get timeline!")
             amountToLike = r.randint(self.like_ammount_min,
                                      self.like_ammount_max)
             amountLiked = 0
             mediaList = re.findall("(?<=\'id\'\: \')[0-9]*_[0-9]*(?=\')",
                                    str(api.LastJson))
             liked = self.db.c.execute(
                 "SELECT MediaID from Like").fetchall()
             while mediaList and amountLiked < amountToLike:
                 mediaId = mediaList.pop(r.randint(0, len(mediaList) - 1))
                 if mediaId not in liked:
                     print("trying to like")  #Still need to do check
                     api.like(mediaId)
                     amountLiked += 1
                     self.db.insert("Like", [self.account, mediaId])
                     await asyncio.sleep(r.randint(
                         3, 40))  #You should have a like wait time min/max
     except Exception as e:
         print("ERROR DURING likeRandom: ", e)
예제 #22
0
def main():
    USERNAME = environ['INSTAGRAM_USERNAME']
    PASSWORD = environ['INSTAGRAM_PASSWORD']
    API = InstagramAPI(USERNAME, PASSWORD)
    API.login()

    last_posted_day = None
    tz = timezone('EST')
    while True:
        t = datetime.now(tz)
        # Post every day at 10am (eastern time)
        if t.day != last_posted_day and t.hour > 10:
            try:
                text, username = most_liked_comment(API,
                                                    most_recent_post_id(API))
                img = comment_to_image(text)
                API.uploadPhoto(img, caption=f'Submitted by @{username}')

                last_posted_day = t.day
                sleep(20 * 60 * 60)  # 20 hours
            except:
                pass

        sleep(2 * 60)  # 2 Minutes
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Use text editor to edit the script and type in valid Instagram username/password

import subprocess

from InstagramAPI import InstagramAPI

USERNAME = ''
PASSWORD = ''
FILE_PATH = '/path/to/video/file'
PUBLISH_TO_LIVE_FEED = False
SEND_NOTIFICATIONS = False

api = InstagramAPI(USERNAME, PASSWORD, debug=False)
assert api.login()

# first you have to create a broadcast - you will receive a broadcast id and an upload url here
assert api.createBroadcast()
broadcast_id = api.LastJson['broadcast_id']
upload_url = api.LastJson['upload_url']

# we now start a boradcast - it will now appear in the live-feed of users
assert api.startBroadcast(broadcast_id, sendNotification=SEND_NOTIFICATIONS)

ffmpeg_cmd = "ffmpeg -rtbufsize 256M -re -i '{file}' -acodec libmp3lame -ar 44100 -b:a 128k -pix_fmt yuv420p -profile:v baseline -s 720x1280 -bufsize 6000k -vb 400k -maxrate 1500k -deinterlace -vcodec libx264 -preset veryfast -g 30 -r 30 -f flv '{stream_url}'".format(
    file=FILE_PATH,
    stream_url=upload_url.replace(':443', ':80', ).replace('rtmps://', 'rtmp://'),
)
예제 #24
0
class AutolikeBot:
    def __init__(self, web_driver):
        self.logger = logging.getLogger()

        self.instagram_api = InstagramAPI()

        self.browser = web_driver

        # wait object to wait for elements to be loaded
        self.wait = WebDriverWait(driver=self.browser, timeout=5)

        self.liked_media_session_count = 0

        self.total_media_like_count = 0

        self.is_logged_in = False

        self.slept_after_limit = False

    def run(self):
        self.browser.get("https://www.instagram.com/")

        self.log_in(config.USERNAME, config.PASSWORD)

        try:
            self.wait.until(EC.presence_of_element_located((By.CLASS_NAME, '_etslc')))
        finally:
            while True:  # infinite for now
                random_pics = self.instagram_api.get_random_pics(tags=config.TAG_LIST, count=random.randint(7, 13))
                for url in random_pics:

                    if self.total_media_like_count % 800 > 710 and self.liked_media_session_count == 100:
                        logging.debug("Sleeping for an hour")
                        time.sleep(60 * 60)

                    if self.liked_media_session_count < 150:
                        self.open_new_tab(url)
                        self.like_current_image()
                        self.browser.close()
                        self.browser.switch_to.window(self.browser.window_handles[0])
                        time.sleep(random.randint(10, 20))
                    else:
                        logging.info("Liked in a session %s" % self.liked_media_session_count)
                        self.total_media_like_count += self.liked_media_session_count
                        self.liked_media_session_count = 0
                        time.sleep(60 * random.randint(61, 100))  # ~1 hour
                        self.slept_after_limit = False

    def log_in(self, username, password):
        if not self.is_logged_in:
            try:
                log_in_button = self.browser.find_element_by_class_name('_k6cv7')
                log_in_button.click()

            except NoSuchElementException:
                pass

            try:
                user_name_field = self.browser.find_element_by_name('username')
                user_name_field.send_keys(username)

                password_field = self.browser.find_element_by_name('password')
                password_field.send_keys(password)

                log_in_btn = self.browser.find_element_by_tag_name('button')
                log_in_btn.click()

                self.is_logged_in = True

            except NoSuchElementException:
                self.browser.quit()

    def open_new_tab(self, url):
        template = Template("window.open('$url');")
        result = template.substitute(url=url)
        self.browser.execute_script(result)
        self.browser.switch_to.window(self.browser.window_handles[1])  # switch to the actual new window

    def like_current_image(self):
        try:
            self.wait.until(EC.presence_of_element_located((By.CLASS_NAME, '_ebwb5')))
            first_like = self.browser.find_element_by_class_name('_ebwb5')
            first_like.click()
            self.liked_media_session_count += 1
        except TimeoutException:
            pass
예제 #25
0
파일: serv.py 프로젝트: qxZap/Coliw
def client_thread(conn,addr):
    loggedIn = False
    loggedInIG = False
    userInstagram= None
    username=None
    while True:
        try:
            data = conn.recv(1024)
        except Exception as disconnected:
            print("[-] Disconnected "+addr[0]+":"+str(addr[1]))
            q=disconnected
            break
        if not data:
            break
        arguments = data.split(" ")
        
        if arguments[0]=='--help' or arguments[0]=='-h':
            to_send="CoLiW\n\nCommands:\n\tlogin\n\tlogout\n\tregister\n\tweb module\n\thistory"
        
        elif arguments[0] == "login":
            if loggedIn==True:
                to_send="You are already logged in"
                
            else:
                if len(arguments)<3:
                    to_send="Too few arguments!\nSyntax: login <username> <password>"
                elif len(arguments)>3:
                    to_send="Too many arguments!\nSyntax: login <username> <password>"
                else:
                    db = MySQLdb.connect(host="localhost", user="******", passwd="", db="aplicatiebd")
                    cur = db.cursor()
                    stringalau="SELECT password FROM USERS WHERE username ='******'"
                    cur.execute(stringalau)
                    if arguments[2]==cur.fetchall()[0][0]:
                        loggedIn=True
                        username=arguments[1]
                        to_send="Login sucessfull"
                    else:
                        to_send="Wrong creditals"
                
        
        
            #flag = subprocess.check_output([sys.executable, "login.py", arguments[1], arguments[2]])
            
            #if flag == '1\n':
            #    to_send = "Login sucessfull"
            #    loggedIn = True
            #else:
            #    to_send = "Error with login creditals. Check again your user/password"
        elif arguments[0]=='history':
            if loggedIn:
                if len(arguments)==2:
                    if arguments[1]=='-h':
                        to_send="Hystory\nBasicly, it prints command history of the user\n\n\t-h prints this message\n\t-o prints output also (rather not)\n\t-c clears the history"
                    elif arguments[1]=='-o':
                        db = MySQLdb.connect(host="localhost", user="******", passwd="", db="aplicatiebd")
                        cur=db.cursor()
                        stringalau="SELECT command,output from history where username='******'"
                        cur.execute(stringalau)
                        output=cur.fetchall()
                        sortedOutput=list(set(output))
                        to_send=""
                        for i in sortedOutput:
                            to_send=to_send+i[0]+"\t\t"+i[1]+"\n"
                    elif arguments[1]=='-c':
                        flag=subprocess.check_output( [sys.executable, "clearHistory.py", username])
                        to_send="History cleared"
                    else:
                        to_send="Expected -o -h or -c and recieved"+arguments[1]
                        
                elif len(arguments)==1:
                    db = MySQLdb.connect(host="localhost", user="******", passwd="", db="aplicatiebd")
                    cur=db.cursor()
                    stringalau="SELECT command from history where username='******'"
                    cur.execute(stringalau)
                    output=cur.fetchall()
                    sortedOutput=list(set(output))
                    to_send=""
                    for i in sortedOutput:
                        to_send=to_send+i[0]+"\n"
                else:
                    to_send="Wrong syntax\nType in 'history -h' for more info"
            else:
                to_send="You cannot use this command if you`re not logged in"
            
        elif arguments[0] == "register":
            if loggedIn==True:
                to_send="You cannot register while you are logged in already"
            else:
                if len(arguments)<4:
                    to_send="Too few arguments!\nSyntax: register <username> <password> <email>"
                elif len(arguments)>4:
                    to_send="Too many arguments!\nSyntax: register <username> <password> <email>"
                else:
                    db = MySQLdb.connect(host="localhost", user="******", passwd="", db="aplicatiebd")
                    cur = db.cursor()
                    stringalau="SELECT id FROM USERS WHERE username ='******'"
                    cur.execute(stringalau)
                    if len(cur.fetchall())>0:
                        to_send="There is already someone called "+arguments[1]
                    else:
                        stringalau="INSERT INTO users(username,password,email) VALUES('"+arguments[1]+"','"+arguments[2]+"','"+arguments[3]+"');"
                        cur.execute(stringalau)
                        db.commit()
                        to_send="You`ve been registred and now you`re logged in"
                        loggedIn=True
                        username=arguments[1]
        elif arguments[0]=='logout':
            to_send="Logged out"
            loggedIn=False
                    
        
        
        
            #flag = subprocess.check_output([sys.executable, "register.py", arguments[1], arguments[2], arguments[3]])
            #if flag == "True\n":
            #    to_send = "You have been registered!"
            #else:
            #    to_send = "There is someone called " + arguments[1]
                
        elif arguments[0]=="web":
            if loggedIn==False:
                to_send="You have to be logged in to use web module."
            else:
                if len(arguments)>1:
                    if arguments[1]=='-h':
                        to_send="CoLiW Web Module\n\tinstagram API\n\tflickr API"
                    elif arguments[1]=="instagram":
                        if len(arguments)==2:
                            to_send="Invalid syntax.\nType in web instagram -h"
                        else:
                        #web instagram login username passwd
                            if arguments[2]=="login":
                                if len(arguments)>5:
                                    to_send="Too many arguments\nSyntax: web instagram login <username> <password>"
                                elif len(arguments)<5:
                                    to_send="Too few arguments\nSyntax: web instagram login <username> <password>"
                                else:
                                    userInstagram=InstagramAPI(arguments[3],arguments[4])
                                    if(userInstagram.login()):
                                        to_send="You`ve logged in through Instagram. Now you can use it as you desire"
                                        loggedInIG = True
                                    else:
                                        to_send="Wrong username/password. try again after you check them again"
                            elif arguments[2]=='logout':
                                if loggedInIG:
                                    loggedInIG=False
                                    userInstagram=None
                                    to_send="Logged out"
                                else:
                                    to_send="You cannot log out if you`re not logged in"
                                
                                

                            elif arguments[2]=="follow":
                                if loggedInIG == True :
                                    #returnID = subprocess.check_output( [sys.executable, "getIDbyUsername.py", arguments[3]])
                                    returnID=getIDbyUsername(arguments[3])
                                    if returnID[len(returnID)-1]=='"':
                                        returnID=returnID[:-1]
                                    userInstagram.follow(returnID)
                                    to_send="Now following "+arguments[3]
                                else:
                                    to_send="You have to be logged in with instagram\nUse web instagram -h for more info"
                                    
                            elif arguments[2] == "unfollow":
                                if loggedInIG==True:
                                    #returnID = subprocess.check_output( [sys.executable, "getIDbyUsername.py", arguments[3]])
                                    returnID=getIDbyUsername(arguments[3])
                                    if returnID[len(returnID)-1]=='"':
                                        returnID=returnID[:-1]
                                    userInstagram.unfollow(returnID)
                                    to_send="Now not following "+arguments[3]+" anymore"
                                else:
                                    to_send="You have to be logged in with instagram\nUse web instagram -h for more info"
                            elif arguments[2] == 'block':
                                if loggedInIG==True:
                                    returnID=getIDbyUsername(arguments[3])
                                    if returnID[len(returnID)-1]=='"':
                                        returnID=returnID[:-1]
                                    userInstagram.block(returnID)
                                    to_send=+arguments[3]+" been blocked"
                                else:
                                    to_send="You have to be logged in with instagram\nUse web instagram -h for more info"
                            elif arguments[2] == 'unblock':
                                if loggedInIG==True:
                                    returnID=getIDbyUsername(arguments[3])
                                    if returnID[len(returnID)-1]=='"':
                                        returnID=returnID[:-1]
                                    userInstagram.unblock(returnID)
                                    to_send=+arguments[3]+" been unblocked"
                                else:
                                    to_send="You have to be logged in with instagram\nUse web instagram -h for more info"
                                    
                            elif arguments[2]=="upload":
                                if loggedInIG == True:
                                    if arguments[3]=="photo":
                                        caption=""
                                        for i in arguments[4:]:
                                            caption+=str(i)+" "
                                        uploadPhoto(arguments[4], caption)
                            elif arguments[2]=='-h':
                                to_send="Instagram API in Coliw\n\n\tsyntax: web instagram <follow/unfollow/login/block/unblock> <username>"
                    elif arguments[1] == "flickr":
                        continueT=True
                        index_to_start=0
                        number_of_photos=0
                        #web flickr
                        if len(arguments)==2:
                            to_send="no arguments given!"
                        #web flickr <tag>
                        elif len(arguments)==3:
                            if arguments[2]=='-h':
                                to_send="\nFlickr api\nSyntax: web flickr <keyword> <options>\n\n\t-i start index ( 0 as default )\n\t-n number of photos ( 1 as default )"
                                continueT=False
                            else:
                                index_to_start=1
                                number_of_photos=1
                            
                        elif len(arguments)==5:
                            if arguments[3]=='-i':
                                if arguments[4].isdigit():
                                    index_to_start=int(arguments[4])
                                else:
                                    continueT=False
                                    to_send=argument[4]+" is not a number"
                        
                            elif arguments[3]=='-n':
                                if arguments[4].isdigit():
                                    number_of_photos=int(arguments[4])
                                else:
                                    continueT=False
                                    to_send=argument[4]+" is not a number"
                        
                        
                            
                        elif len(arguments)==6:
                            if arguments[3]=='-in':
                                
                                if arguments[4].isdigit():
                                    index_to_start=int(arguments[4])
                                else:
                                    continueT=False
                                    to_send=arguments[4]+" is not a number"
                                     
                                if arguments[5].isdigit():
                                    number_of_photos=int(arguments[5])
                                else:
                                    continueT=False
                                    to_send=arguments[5]+" is not a number"
                                    
                            elif arguments[3]=='-ni':
                                    
                                if arguments[4].isdigit():
                                    number_of_photos=int(arguments[4])
                                else:
                                    continueT=False
                                    to_send=arguments[4]+" is not a number"
                                        
                                if arguments[5].isdigit():
                                    index_to_start=int(arguments[5])
                                else:
                                    continueT=False
                                    to_send=arguments[5]+" is not a number"                                    
                        elif len(arguments)==7:
                            if arguments[3]=='-i' and arguments[5]=='-n':
                                if arguments[4].isdigit():
                                    if arguments[6].isdigit():
                                        index_to_start=int(arguments[4])
                                        number_of_photos=int(arguments[6])
                                    else:
                                        continueT=False
                                        to_send=arguments[6]+" is not a number"
                                else:
                                    continueT=False
                                    to_send=arguments[4]+" is not a number"
                            
                            elif arguments[3]=='-n' and arguments[5]=='-i':
                                if arguments[4].isdigit():
                                    if arguments[6].isdigit():
                                        number_of_photos=int(arguments[4])
                                        index_to_start=int(arguments[6])
                                    else:
                                        continueT=False
                                        to_send=arguments[6]+" is not a number"
                                else:
                                    continueT=False
                                    to_send=arguments[4]+" is not a number"
                            elif arguments[3]==arguments[5]:
                                continueT=False
                                to_send="3rd and 5th argument cannot be even"
                            else:
                                continueT=False
                                to_send="Wrong syntax, expected -i or -n on the 3rd or 5th"
                        
                        
                        else:
                            to_send="Too many arguments given/wrong syntax"
                            continueT=False
                        if continueT:
                            #to_send="Right syntax/ you wanna search "+arguments[2]+" index="+str(index_to_start)+" no="+str(number_of_photos)
                            startUP=0
                            startDOWN=0
                            if number_of_photos==0:
                                number_of_photos=1
                            if number_of_photos==1 and index_to_start==1:
                                startUP=0
                                startDOWN=1
                            elif index_to_start==0 and number_of_photos>1:
                                startUP=0
                                startDOWN=number_of_photos
                            elif index_to_start>1 and number_of_photos==1:
                                startUP=index_to_start
                                startDOWN=index_to_start+1
                            elif index_to_start>1 and number_of_photos>1:
                                startUP=index_to_start
                                startDOWN=startUP+number_of_photos
                            elif index_to_start==1 and number_of_photos>1:
                                startUP=index_to_start
                                startDOWN=number_of_photos+1
                            elif index_to_start==0 and number_of_photos==1:
                                startUP=0
                                startDOWN=1
                                
                            
                                
                            
                            
                                
                            flickr = flickrapi.FlickrAPI('e57cfa37f00d7a9a5d7fac7e37ebcbb5', '00751b0c7b65ba7a',format='parsed-json')
                            extras = 'url_sq,url_t,url_s,url_q,url_m,url_n,url_z,url_c,url_l,url_o'
                            links = ""
                            cats = flickr.photos.search(text=arguments[2], per_page=startDOWN+startUP, extras=extras)
                                
                            for i in range(startUP, startDOWN):
                                photos = cats['photos']['photo'][i]['url_m']
                                links =links+photos + '\n'
                            links=links[:-1] 
                            to_send=links
                            
                    else:
                        to_send="unknown web command"
                else:
                    to_send="too few arguments known"
                 
        else:
            to_send=arguments[0]+" is not recognized"
        if loggedIn:
            print subprocess.check_output( [sys.executable, "addCMD.py", username,data, to_send])
        reply = to_send
        conn.send(reply.encode('ascii'))
    conn.close()
예제 #26
0
def main():
    global root_dir

    dirs = extract_dict("dirs.txt")
    if dirs is None or "data" not in dirs:
        print(
            "Error: You must create a file in this directory ({}) called `dirs.txt`. "
            .format(os.path.dirname(os.path.realpath(__file__))) +
            "This must contain a dictionary, in the form `{'logins': '/path/to/logins.txt', 'data': '/path/to/instagram-data/'}`."
        )
        return

    if "logins" not in dirs:
        logins = None
    else:
        logins = extract_dict(dirs["logins"])

    username, args = get_username()
    if username == "*":
        ## use all logins
        if (logins is None):
            print("No login data found.")
            return
    elif logins is not None and username in logins:
        password = logins[username]
        logins = {username: password}
    else:
        password = get_password()
        logins = {username: password}

    for username in logins:
        password = logins[username]
        print("\nLoading {}.".format(username))
        api = InstagramAPI(username, password)
        api.login()

        try:
            user_id = api.username_id
            ##print("Loaded", user_id)

        except AttributeError:
            try:
                if (api.__dict__['LastJson']['invalid_credentials']):
                    print(
                        "Sorry, that username/password combination is invalid. Please try again.\n"
                    )
                else:
                    print("Error 41. Please try again.\n")
            except KeyError:
                try:
                    if (api.__dict__['LastJson']['error_type'] ==
                            'missing_parameters'):
                        print("Please enter a username and a password.\n")
                    else:
                        print("Error 39. Please try again.\n")
                except:
                    print("Error 40. Please try again.\n")
            return

        root_dir = dirs["data"]
        create_files(username)
        ##print("Files created.")

        followersRaw = api.getTotalFollowers(user_id)
        ##print("Got total followers.")

        followers = generate_followers(followersRaw)
        text_report = generate_text_report(followers, username)
        html_report = generate_html_report(followers, username)
        ##print("Generated report.")

        save_followers(followers, username)
        save_report(text_report, username, 'txt')
        html_filename = save_report(html_report, username, 'html')
        ##print("Saved report.")

        print(
            "\n==================================== Report ====================================\n"
        )
        print(text_report)
        print(
            "================================================================================"
        )
        webbrowser.open('file://' + html_filename)
        print(html_filename)

    input("\nPress return to exit.")
예제 #27
0
import time
import urllib.request as req
from InstagramAPI import InstagramAPI
from Instahandler import get_image_path
from image_access import image_aspect_change
from pathlib import Path

InstagramAPI = InstagramAPI('straighthalal','jibneh82')
InstagramAPI.login()
my_id = InstagramAPI.username_id


def image_upload():
    photo_path = get_image_path()
    caption = 'Testing 1 2 3'
    InstagramAPI.uploadPhoto(photo_path,caption)
    print('Done')


def following():
    #List of all followers
    my_follower_list = [i['pk'] for i in InstagramAPI.getTotalFollowers(my_id)]
    for id in my_follower_list:
        their_followers = [i['pk'] for i in InstagramAPI.getTotalFollowers(id)]
        for person_to_follow in their_followers:
            InstagramAPI.follow(person_to_follow)
            time.sleep(5)
            print('Followed!')

        print()
    """

    followers = []
    next_max_id = True
    while next_max_id:
        # first iteration hack
        if next_max_id is True:
            next_max_id = ''

        _ = api.getUserFollowers(user_id, maxid=next_max_id)
        followers.extend(api.LastJson.get('users', []))
        next_max_id = api.LastJson.get('next_max_id', '')
    return followers


if __name__ == "__main__":
    api = InstagramAPI("username", "password")
    api.login()

    # user_id = '1461295173'
    user_id = api.username_id

    # List of all followers
    followers = getTotalFollowers(api, user_id)
    print('Number of followers:', len(followers))

    # Alternatively, use the code below
    # (check evaluation.evaluate_user_followers for further details).
    followers = api.getTotalFollowers(user_id)
    print('Number of followers:', len(followers))
import os
import time
import random
from os import listdir
from os.path import isfile, join
from random import randint
from InstagramAPI import InstagramAPI

PhotoPath = "~/igphoto/"  # Change Directory to Folder with Pics that you want to upload
# Change to your Photo Hashtag
IGCaption = "Your Caption Here #hashtag"

os.chdir(PhotoPath)
ListFiles = [f for f in listdir(PhotoPath) if isfile(join(PhotoPath, f))]
print("Total Photo in this folder:" + str(len(ListFiles)))

# Start Login and Uploading Photo
igapi = InstagramAPI("login", "password")
igapi.login()  # login

for i in range(len(ListFiles)):
    photo = ListFiles[i]
    print("Progress :" + str([i + 1]) + " of " + str(len(ListFiles)))
    print("Now Uploading this photo to instagram: " + photo)
    igapi.uploadPhoto(photo, caption=IGCaption, upload_id=None)
    # sleep for random between 600 - 1200s
    n = randint(600, 1200)
    print("Sleep upload for seconds: " + str(n))
    time.sleep(n)
    def add_users(self, users):
        for user in users:
            self._add_user(user)

    def _add_user(self, user):
        self.users[user['pk']] = {'full_name': user['pk'], 'username': user['username']}

    def download(self):
        if not self._request():
            print("Failed!\n")

        data = self.client.LastJson.get('thread')
        self.add_users(data['users'])
        self._save()

    def save(self):
        dump = json.dumps(self.conversation)
        with open('back.txt', 'w') as f:
            f.write(dump)


if __name__ == "__main__":
    thread_id = ''  # id thread for download

    InstagramAPI = InstagramAPI("login", "password")
    InstagramAPI.login()

    inst = DownloadThread(InstagramAPI, thread_id)
    inst.download()
    inst.save()
from InstagramAPI import InstagramAPI #pip install PythonInstagram
import sys
import json
import requests
try:
	username = sys.argv[1]
except:
	pass
API = InstagramAPI("REPLACE THIS WITH YOUR USERNAME", "REPLACE THIS WITH YOUR PASSWORD")
API.login()
def getID(username):
	API.searchUsername(username)
	return API.LastJson['user']['pk']
def getJson(id):
	url = "https://i.instagram.com/api/v1/users/" + str(id) + "/info/"
	request = requests.get(url)
	return request.json()
def getPicture(json):
	return json["user"]["hd_profile_pic_url_info"]["url"]
ID = getID(username)
json = getJson(ID)
picture = getPicture(json)
print(picture)
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Use text editor to edit the script and type in valid Instagram username/password

from InstagramAPI import InstagramAPI
from examples.evaluation.evaluation_log import EvaluationLog
from examples.user_followers import getTotalFollowers


def evaluate_method(function, parameters, function_name=None):
    evaluation_log = EvaluationLog()
    evaluation_log.start_log(function_name)
    response = function(*parameters)
    evaluation_log.end_log(function_name)

    print('response size:', len(response))
    print('number of unique users:', len(set([user['username'] for user in response])))
    print()


if __name__ == "__main__":
    api = InstagramAPI("username", "password")
    api.login()

    # For a user with over 22k followers, use: user_id = '1461295173'
    user_id = api.username_id

    evaluate_method(api.getTotalFollowers, [user_id], 'api.getTotalFollowers')
    evaluate_method(getTotalFollowers, [api, user_id], 'getTotalFollowers')
예제 #33
0
파일: server.py 프로젝트: qxZap/Coliw
                elif arguments[2]=="follow":
                    if sockethelper.loggedInIG == True :
                        returnID = subprocess.check_output( [sys.executable, "getIDbyUsername.py", arguments[3]])
                        sockethelper.userInstagram.follow(returnID)
                elif arguments[2] == "unfollow":
                    if sockethelper.loggedInIG==True:
                        returnID = subprocess.check_output( [sys.executable, "getIDbyUsername.py", arguments[3]])
                        sockethelper.userInstagram.unfollow(returnID)
                elif arguments[2]=="upload":
                    if sockethelper.loggedInIG == True:
                        if arguments[3]=="photo":
                            caption=""
                            for i in arguments[4:]:
                                caption+=str(i)+" "
                            InstagramAPI.uploadPhoto(arguments[4], caption)

	if arguments[0]=="exit" & len(arguments)==1:
		sockethelper.close_socket
		print("[!] Socket closed.\n")
		
	sockethelper.send_data(to_send)

#	copie dupa diploma de bac
#	copie dupa dcert de nastere

# original:	adeverinta medicala de angajare
# original: cazier  judiciar
# copie legalaizata dupa diploma de bac
# 11 iunie ora 3
# regina maria control de medicina muncii <fisa aptitudini>
예제 #34
0
import time
import random
from os import listdir
from os.path import isfile, join
from random import randint
from InstagramAPI import InstagramAPI
from PIL import Image
import config

path = config.finalpath
IGCaption = config.caption
username = config.instagram_username
password = config.instagram_password
sleeptime = config.sleeptime_post

igapi = InstagramAPI(username, password)
igapi.login()  # login


def run_bot(POSTED):
    files = [f for f in listdir(path) if isfile(join(path, f))]
    for i in range(len(files)):
        for name in files:
            try:
                filesize = os.path.getsize(path + name)

                if filesize < 55000:
                    os.remove(path + name)
                else:
                    if name not in POSTED:
                        photo = path + name
예제 #35
0
파일: favorite.py 프로젝트: sanxiyn/sandbox
from InstagramAPI import InstagramAPI

with open('username') as f:
    username = f.read()

with open('password') as f:
    password = f.read()

api = InstagramAPI(username, password)
api.login()
followings = api.getTotalSelfFollowings()
favorites = [user for user in followings if user['is_favorite']]
for username in sorted(user['username'] for user in favorites):
    print username
import json
import datetime
import time
import random
from random import randint, shuffle

timemark = datetime.datetime.now()
print("Sunray IG Bot started at " + str(timemark))

my_username = ""  #your username
my_password = ""  #your password

userid = 0  #your userid
mediaid = 0

API = InstagramAPI(my_username, my_password)  #your username and password
print("Logging into %s" % my_username)
API.login()

accounts = {
    'set1': {

        #key:user ID
        "key1": 409064094,
        "key2": 480466954
    },
    'set2': {
        'key3': 284341891,
        'key4': 22963539,
        'key5': 259394152
    }
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Use text editor to edit the script and type in valid Instagram username/password

from InstagramAPI import InstagramAPI
import time
from datetime import datetime

media_id = '1477006830906870775_19343908'

# stop conditions, the script will end when first of them will be true
until_date = '2017-03-31'
count = 100

API = InstagramAPI("login", "password")
API.login()
API.getUsernameInfo()
has_more_comments = True
max_id = ''
comments = []

while has_more_comments:
    _ = API.getMediaComments(media_id, max_id=max_id)
    # comments' page come from older to newer, lets preserve desc order in full list
    for c in reversed(API.LastJson['comments']):
        comments.append(c)
    has_more_comments = API.LastJson.get('has_more_comments', False)
    # evaluate stop conditions
    if count and len(comments) >= count:
        comments = comments[:count]
예제 #38
0
파일: test.py 프로젝트: thetomcraig/EROS
#!/usr/bin/env python
# -*- coding: utf-8 -*-

from InstagramAPI import InstagramAPI

InstagramAPI = InstagramAPI("login", "password")
InstagramAPI.login() # login
InstagramAPI.tagFeed("cat") # get media list by tag #cat
media_id = InstagramAPI.LastJson # last response JSON
InstagramAPI.like(media_id["ranked_items"][0]["pk"]) # like first media
InstagramAPI.getUserFollowers(media_id["ranked_items"][0]["user"]["pk"]) # get first media owner followers
예제 #39
0
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import getpass
from InstagramAPI import InstagramAPI
from nicetwo import RealFriends

login = raw_input("Enter login or just press 'Enter' to use admin account: ")
if login != '':
    print('Do not worry, your password is safe. It is invisible right now for safety measures so keep entering it')
    psw = getpass.getpass('Password: '******'jogryn'
    psw = '511999'
InstagramAPI = InstagramAPI(login, psw)

f = RealFriends(InstagramAPI)
print('Program from nicetwo.py RealFriends. \nFinds all users who liked selected media of entered user')
cont = ''
while cont != 'no':
    err = False
    user = raw_input('Enter the name of the user whose account likers you want to check'
                     '\nor just press "Enter" to check account with which you have logged in ')
    how = raw_input('If you want to check likers of all pictures of selected user press "Enter"\n'
                    'else if you want to add pictures that were uploaded later than some date enter that date like in '
                    'example: "01/06/2017"\nelse if you want to add some chosen pictures by yourself print "1" ')
    if how == '':
        f.likers_stats(user)
    elif '/' in how:
        f.likers_stats(user, timer=how)
    elif how == '1':
        f.handmade_stats(user)
# encoding: utf-8

import json
import os
import time
from InstagramAPI import InstagramAPI

##### CONFIGURATION TO USE #####
login = "******"
password = "******"
message = "Type your message here"
##### CONFIGURATION TO USE #####

api = InstagramAPI(login, password)

if (api.login()):
    
    user_id = api.username_id

    #getting total followers function
    def getTotalFollowers(api, user_id):
        """
        Returns the list of followers of the user.
        It should be equivalent of calling api.getTotalFollowers from InstagramAPI
        """
        followers = []
        next_max_id = True
        while next_max_id:
            # first iteration hack
            if next_max_id is True:
                next_max_id = ''
예제 #41
0

def GetAllFollowers(bot, user_id):
    followers = []
    next_max_id = True
    while next_max_id:
        if next_max_id is True:
            next_max_id = ''
        _ = bot.getUserFollowers(user_id, maxid=next_max_id)
        followers.extend(bot.LastJson.get('users', []))
        next_max_id = bot.LastJson.get('next_max_id', '')
    #followers = set([_['pk'] for _ in followers])
    return followers


ig = InstagramAPI(credentials.username, credentials.password)

while (1):
    if not ig.login():
        print('Check Credentials')
        sys.exit()

    print(credentials.username + ' Login ' + 'Successful!')

    ig.getSelfUsernameInfo()
    self_id = ig.LastJson['user']['pk']

    # get current time
    location = pytz.timezone('America/Los_Angeles')
    current_time = datetime.datetime.now(tz=location)
    current_time = current_time.replace(second=0, microsecond=0, tzinfo=None)
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Use text editor to edit the script and type in valid Instagram username/password

from InstagramAPI import InstagramAPI
import time
from datetime import datetime

user_id = ''

API = InstagramAPI("login", "password")
API.login()

API.getUsernameInfo(user_id)
API.LastJson
following = []
next_max_id = True
while next_max_id:
    print next_max_id
    # first iteration hack
    if next_max_id is True:
        next_max_id = ''
    _ = API.getUserFollowings(user_id, maxid=next_max_id)
    following.extend(API.LastJson.get('users', []))
    next_max_id = API.LastJson.get('next_max_id', '')

len(following)
unique_following = {
    f['pk']: f
    for f in following
예제 #43
0
from InstagramAPI import InstagramAPI
from credentials import*
import datetime
import time
import json
import pprint

api = InstagramAPI(username, password)
if api.login():
    print(str(datetime.datetime.now()) + " Login success!")
else:
    print(str(datetime.datetime.now()) + " Can't login!")

api.getTotalFollowers('2217541870')
selfFollowing = api.LastJson

followers = {}

for user in selfFollowing['users']:
    username = user['username']
    pk = user['pk']
    followers[str(pk)] = 'follow'

pprint.pprint(followers)

self_followers_json = {}
self_following_json = {}
users_interacted_json = {}
users_to_unfollow_json = {}
users_to_follow_json = followers
예제 #44
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Use text editor to edit the script and type in valid Instagram username/password

from InstagramAPI import InstagramAPI

InstagramAPI = InstagramAPI("login", "password")
InstagramAPI.login()  # login

photo_path = '/path/to/photo.jpg'
caption = "Sample photo"
InstagramAPI.uploadPhoto(photo_path, caption=caption)
예제 #45
0
def image_upload():
    photo_path = get_image_path()
    caption = 'Testing 1 2 3'
    InstagramAPI.uploadPhoto(photo_path,caption)
    print('Done')
예제 #46
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Use text editor to edit the script and type in valid Instagram username/password

from InstagramAPI import InstagramAPI
import urllib

video_url = 'https://instagram.fmad3-2.fna.fbcdn.net/t50.2886-16/17157217_1660580944235536_866261046376005632_n.mp4'  # a valid instagram video
video_local_path = video_url.split("/")[-1]
thumbnail_url = "https://instagram.fmad3-2.fna.fbcdn.net/t51.2885-15/e15/17075853_1759410394387536_3927726791665385472_n.jpg"
thumbnail_local_path = thumbnail_url.split("/")[-1]

urllib.urlretrieve(video_url, video_local_path)
urllib.urlretrieve(thumbnail_url, thumbnail_local_path)

InstagramAPI = InstagramAPI("login", "password")
InstagramAPI.login()  # login
InstagramAPI.uploadVideo(video_local_path, thumbnail_local_path, caption="Tortuguero")
예제 #47
0
            nostop = 0

            while True:
                accounts = input(
                    "Put your Instagram accounts list here (if there is no file just press ENTER): "
                )
                if not accounts:
                    username = input("Put your IG Username then press ENTER: ")
                    try:
                        password = getpass.getpass(
                            prompt="Put your IG Password then press ENTER: ")
                    except Exception as error:
                        print("Error:", error)
                    else:
                        print("Got Password. Attempting to login.")
                    api = InstagramAPI(username, password)
                    api.login()
                    break

                else:
                    try:
                        line = random.choice(open(accounts).readlines())
                        username, password = line.split(':')
                        print("Username found: ", username)
                        print("Password found: ", password)
                        api = InstagramAPI(username, password)
                        api.login()
                        break

                    except:
                        print("Wrong file")
예제 #48
0
Lifestream = lifestream.Lifestream()

logger = logging.getLogger('Instagram')


lifestream.arguments.add_argument(
    '--all',
    required=False,
    help="Get all items",
    default=False,
    action='store_true')

args = lifestream.arguments.parse_args()

api = InstagramAPI(lifestream.config.get(
    "instagram", "username"), lifestream.config.get("instagram", "password"))
if (api.login()):
    if args.all:
        feed = api.getTotalSelfUserFeed()  # get self user feed
    else:
        feed = api.getSelfUserFeed()  # get self user feed

    if not feed:
        logger.error('Failed to get feed')
        sys.exit(5)

    if feed == True:
        feed = api.LastJson['items']

    for item in feed: