def get_instagram(): api = SocialSetting.objects.filter(api_type='IN')[0] secret = api.api_client_secret token = api.api_access_token req = InstagramAPI(access_token=token, client_secret=secret) if api: if api.api_last_id: recent_tags, next_ = req.tag_recent_media( tag_name=api.instagram_hashtag, count=10, max_tag_id=api.api_last_id ) #accepts_parameters=['count', 'max_tag_id', 'tag_name'], else: recent_tags, next_ = req.tag_recent_media( tag_name=api.instagram_hashtag, count=10 ) #accepts_parameters=['count', 'max_tag_id', 'tag_name'], #recent_tags, next_ = api.tag_recent_media(tag_name="tgif", count=10, max_tag_id="1051706417356389558_318480430") #accepts_parameters=['count', 'max_tag_id', 'tag_name'], if len(recent_tags) > 0: api.api_last_id = recent_tags[0].id api.save() processInstas(recent_tags) return "Success, processing" else: return "Nothing to process" else: return "No Instgram API"
def run(self): # Instantiates an Instagram API object using the python-instagram library api = InstagramAPI(client_secret=self.client_secret,access_token=self.access_token) # Get the recent #capitalone tags recent_tags, next = api.tag_recent_media(tag_name="CapitalOne", count=MAX_COUNT) nextCounter = math.ceil(MAX_COUNT/20.0)+1 temp, max_tag = next.split("max_tag_id=") # Initialize variables to track number of positive, negative, and neutral posts # that load recent posts return positivePosts = 0 negativePosts = 0 neutralPosts = 0 counter = 1 while next and counter < nextCounter: # First run through the recent tags if counter == 1: self.loadRecentPosts(recent_tags,api) # Use pagination to run through more than 20 tags else: recent_tags, next = api.tag_recent_media(tag_name='CapitalOne', max_tag_id=max_tag) temp, max_tag = next.split('max_tag_id=') self.loadRecentPosts(recent_tags,api) counter+=1 self.calculateCaptionAndImageSentimentAverage() self.makeGraphs()
def searchPopularVideos(self, tag, count): videos = [] if count == 0: return videos tag = self.searchstring(tag) api = InstagramAPI(client_id= '7d428aff533f40e1b3d5f919882576d2', client_secret= 'bfbe419a758141fbaf352c89b579a0a5') recent_media, next_ = api.tag_recent_media(count=50, tag_name=tag) for media in recent_media: if media.type == 'video': videos.append(Post(media.videos['standard_resolution'], media.type, media.like_count, media.comment_count)) if len(videos) >= count: popularvideos = sorted(videos, key=methodcaller('weighted_popularity'),reverse=True) return popularvideos i=0 if len(videos) >= count: popularvideos = sorted(videos, key=methodcaller('weighted_popularity'),reverse=True) return popularvideos else: while i<10 and next_: recent_media, next_ = api.tag_recent_media(count=50, tag_name=self.searchstring(tag), with_next_url=next_) for media in recent_media: if media.type == 'video': videos.append(Post(media.videos['standard_resolution'], media.type, media.like_count, media.comment_count)) if len(videos) >= count: popularvideos = sorted(videos, key=methodcaller('weighted_popularity'),reverse=True) return popularvideos i += 1 popularvideos= sorted(videos, key=methodcaller('weighted_popularity'),reverse=True) return popularvideos
def Tag_Search(page=1): if request.method == "POST": query = request.form["query"] if not query: e = "Please Enter something." return render_template("search.html", error=e, title="Tag Search") u = InstagramAPI(access_token=session['access_token'], client_secret=secrets['client_secret']) tag_search, next_tag = u.tag_search(q=query) tag_recent_media, next_ = u.tag_recent_media(tag_name=tag_search[0] .name) for i in range(1, page): tag_recent_media, next_ = u.tag_recent_media(tag_name=tag_search[0] .name, with_next_url=next_) tags = [] imgs = [] title = "Tag Search-Page " + str(page) prev_page = False next_page = False if next_: prev_page = True if page != 1: next_page = True # for media in tag_recent_media: # tags.append("{}".format(media.get_thumbnail_url())) # tags.append("{}".format(media.get_standard_url())) return render_template("search.html", tags=tags, imgs=imgs, prev=prev_page, next=next_page, page=page, title=title) return render_template("search.html")
def index(): # TODO: Move to environment variable access_token = "995294683.26174be.94f2626419534650812cf5ed542d5a9d" api = InstagramAPI(access_token=access_token) # Get 30 pickles starting at a random page num = 30 page = random.randint(0, 10) pickles, next = api.tag_recent_media(num, page, "pickle") choice_pickle = choice(pickles) # Truncate long captions pickle_caption = choice_pickle.caption.text.lower() if choice_pickle.caption else '' pickle_caption = (pickle_caption[:110] + "...") if len(pickle_caption) > 110 else pickle_caption pickle_link = choice_pickle.link pickle_user = choice_pickle.user.username if hasattr(choice_pickle, "images"): pickle_image_link = choice_pickle.images["standard_resolution"].url elif hasattr(choice_pickle, "videos"): # FIXME: Update template pickle_image_link = choice_pickle.videos["standard_resolution"].url # TODO: Download generated image with canvas # TODO: Post the best ones to a an instagram account or tweet them. return render_template('index.html', caption=pickle_caption, username=pickle_user, link=pickle_link, image=pickle_image_link)
def handle(self, *args, **options): while True: now = datetime.datetime.utcnow().replace(tzinfo=utc) api = InstagramAPI(client_id=settings.INSTAGRAM_CLIENT_ID) tags = Tag.objects.filter(semaphore=False, last_processed_date__lte=now - datetime.timedelta(seconds=900)) for tag in tags: tag.last_processed_date = now tag.semaphore = True tag.save() try: insta_result = api.tag_recent_media(100, None, tag.tag) except: self.update_tag(tag) continue for media in insta_result[0]: try: Image.objects.get(tag=tag, instagram_id=media.id) break except Image.DoesNotExist: image = Image( tag=tag, instagram_id=media.id, link=media.link, thumbnail_url=media.images["thumbnail"].url ) image.save() self.update_tag(tag) self.close_db_connection() time.sleep(300)
def _init(self, *args, **kwargs): """ start the ball a rolling with a request to instagram API open a csv file and output the headers and rows based on results """ api = InstagramAPI(client_id=INSTAGRAM_CLIENT_ID, client_secret=INSTAGRAM_CLIENT_SECRET) instagram_media = api.tag_recent_media(IMAGE_COUNT, 0, IMAGE_HASHTAG) # open the csv file with open(CSV_FILENAME, "wb") as csv_file: csv_output = csvkit.py2.CSVKitWriter(csv_file, delimiter=",", encoding="utf-8") # write the header row to the csv file csv_output.writerow([ "hashtag", "local_date_time", "user_name", "image_link", "image_caption", "like_count", "comment_count", "post_link", "post_type", "post_tags", "post_likes", "utc_date_time" ]) # loop through the results for item in instagram_media[0]: # build a new csv row csv_row = self.build_csv_row_from(item) # write the new csv row csv_output.writerow(csv_row)
def run(self, query, next_url = None, token="", cli_id='', cli_secret='', results_amount = 100): # 1. Call Instagram and get list of media for this query if ( next_url == None ): print "Calling API for a first time..." api = InstagramAPI(client_id=cli_id, client_secret=cli_secret, access_token=token ) media = api.tag_recent_media(results_amount, 0, query ) print media # Dirtiest hack ever! Expect this gets broken someday! media[-1] is a hidden internal representation of instagram request, suitable for pagination # But how to make this pagination using current stable API is unclear r = urllib2.urlopen(media[-1]) else: print "Calling NextURL =" + next_url r = urllib2.urlopen( next_url ) pictures_data = json.loads( r.read() ) #print "data size=%d" % pictures_data['data'].__len__() urls = [] # TODO: serialize this to Mongo for pic in pictures_data['data']: urls.append( pic['images']['standard_resolution']['url'] ) GetURL().delay( pic['images']['standard_resolution']['url'], tags=pic['tags'] ) # Output to paginator pagination_struct = { 'urls' : urls, 'next_url' : pictures_data['pagination']['next_url']} print "pagination:" print pagination_struct return pagination_struct
def get_ig_photo(self): api = InstagramAPI(access_token=settings.INSTAGRAM_ACCESS_TOKEN) photos, next = api.tag_recent_media(count=20, tag_name="shibainu") for photo in photos: print photo.caption.text print photo.tags print "\n"
def load_photos(request): """ Loads photos from Insagram (not yet other,like G+) and insert in database. """ api = InstagramAPI(client_id=settings.INSTAGRAM_CLIENT_ID, client_secret=settings.INSTAGRAM_CLIENT_SECRET) search_result = api.tag_recent_media(MEDIA_COUNT, LARGE_MEDIA_MAX_ID, MEDIA_TAG) info_photo = '' for m in search_result[0]: photo, is_created = Photo.objects.get_or_create( photo_id=m.id, username=m.user.username) is_like_count_updated = False if not photo.like_count == m.like_count: photo.username = m.user.username photo.user_avatar_url = m.user.profile_picture photo.photo_url = m.images['standard_resolution'].url photo.created_time = m.created_time photo.like_count = m.like_count photo.save() is_like_count_updated = True info_photo += '<li>{} {} {} {} {} {} {} {}</li>'.format( m.id, m.user.username, '<img src="{}"/>'.format(m.user.profile_picture), '<img src="{}"/>'.format(m.images['standard_resolution'].url), m.created_time, m.like_count, is_created, is_like_count_updated) html = "<html><body><ul>{}</ul></body></html>".format(info_photo) return HttpResponse(html)
class MediaServer: def __init__(self, media_repository): self.client_id = client_id = os.environ["INSTAGRAM_CLIENT_ID"] self.client_secret = os.environ["INSTAGRAM_CLIENT_SECRET"] self.hashtag = os.environ["INSTAGRAM_HASHTAG"] self.api = InstagramAPI(client_id=self.client_id, client_secret=self.client_secret) self.media_repository = media_repository @timeout(30) def fetch(self): SupportTeam.notify("polling for new media #%s..." % self.hashtag) latest_media_id = self.media_repository.latest_media_id() recent_media = self.api.tag_recent_media(5, latest_media_id, self.hashtag) for instagram_media in recent_media[0]: if not self.media_repository.has_media_with_id(instagram_media.id): media = Media( id=instagram_media.id, url=str(instagram_media.images['standard_resolution'].url), status="new") SupportTeam.notify("%s - new media %s" % (media.id, media.url)) self.media_repository.create(media) def next(self): if not self.media_repository.has_available_media(): self.fetch() if self.media_repository.has_available_media(): return self.media_repository.peek_available_media() return None
def load_photos(request): """ Loads photos from Instagram and populates database. """ api = InstagramAPI(client_id=settings.INSTAGRAM_CLIENT_ID, client_secret=settings.INSTAGRAM_CLIENT_SECRET) search_result = api.tag_recent_media(MEDIA_COUNT, LARGE_MEDIA_MAX_ID, MEDIA_TAG) info = "" # list of media is in the first element of the tuple for m in search_result[0]: p, is_created = Photo.objects.get_or_create(id=m.id, username=m.user.username) is_like_count_updated = False if not p.like_count == m.like_count: p.username = m.user.username p.user_avatar_url = m.user.profile_picture p.photo_url = m.images["standard_resolution"].url p.created_time = m.created_time p.like_count = m.like_count p.save() is_like_count_updated = True info += "<li>{} {} {} {} {} {} {} {}</li>".format( m.id, m.user.username, _img_tag(m.user.profile_picture), _img_tag(m.images["standard_resolution"].url), m.created_time, m.like_count, is_created, is_like_count_updated, ) html = "<html><body><ul>{}</ul></body></html>".format(info) return HttpResponse(html)
def get_tag_media(tag_name, from_time, to_time): config = ConfigParser.ConfigParser() config.read('insta-stalker.cfg') access_token = config.get('insta-stalker', 'access_token') api = InstagramAPI(access_token=access_token) count = 20 print 'from_time: ' + str(timestamp_to_datetime(from_time / 1000)) print 'to_time: ' + str(timestamp_to_datetime(to_time / 1000)) max_id = to_time while max_id > from_time: recent_media, next = api.tag_recent_media(count, max_id, tag_name) # print 'count: ' + str(len(recent_media)) for media in recent_media: # print 'username: '******'link: ' + media.link print 'time: ' + str(media.created_time) # print 'id: ' + media.id # print 'url: ' + media.images['standard_resolution'].url parsednext = urlparse.urlparse(next) max_id = int(urlparse.parse_qs(parsednext.query)['max_tag_id'][0]) print 'max_tag_id: ' + str(max_id) + ' (' + str(timestamp_to_datetime(max_id / 1000)) + ')'
def suck(save_item, handle_error, source): api = InstagramAPI(client_id=settings.INSTAGRAM['client_id'], client_secret=settings.INSTAGRAM['client_secret']) if 'lastRetrieved' not in source: source['lastRetrieved'] = {} if 'thaicoup' in source['lastRetrieved']: last_id = source['lastRetrieved']['thaicoup'] else: last_id = 0 tag_media, next = api.tag_recent_media(50, last_id, 'thaicoup') source['lastRetrieved'] = { 'thaicoup': 0 } source['lastRetrieved']['thaicoup'] = str(tag_media[0].id) for media in tag_media: item = transform(media) save_item(item) return source['lastRetrieved']
def get_instagram_result(search): search_pattern = [search.replace(" ",""),search.split()[0]] instagram_result = [] MAX_PHOTO = 6 counts = MAX_PHOTO CLIENT_ID = 'SECRET' CLIENT_SECRET = 'SECRET' api = InstagramAPI(client_id=CLIENT_ID, client_secret=CLIENT_SECRET) for pattern in search_pattern: recent_media = 0 try: recent_media, mynext = api.tag_recent_media(count=counts, tag_name=pattern) except: pass if recent_media: for item in recent_media: if item.user.username not in list_banned('instagram'): instagram_result.append([item.images['standard_resolution'].url, item.user.username]) else: print 'some item banned' if len(instagram_result) > MAX_PHOTO-1: return instagram_result[:MAX_PHOTO] break else: counts = MAX_PHOTO - len(instagram_result) return instagram_result
def handle(self, *args, **options): settings.use_editable() api = InstagramAPI(client_id=settings.INSTAGRAM_CLIENT_ID, client_secret=settings.INSTAGRAM_CLIENT_SECRET) logger.debug(api) # use dict to remove duplicates from list data = {} tags = Tag.objects.values_list('tag', flat=True) logger.debug(tags) for tag in tags: for g in api.tag_recent_media(tag_name=tag, as_generator=True, count=20, max_pages=3): items, next_page = g for item in items: data[item.id] = item logger.debug(item) Media.objects.get_or_create(media_id=item.id, defaults={'allowed': False}) # sort by date tagged data = data.values() final_items = sorted(data, key=lambda k: k.created_time, reverse=True) cache.set('INSTAGRAM_TAGS_STREAM', final_items, 60 * 60)
def book(book_id): form = SearchForm() book = Book.query.filter_by(id = book_id).first() pics = Picture.query.filter_by(book_id = book_id).order_by(Picture.order) if book == None: flash('Book not found') return redirect(url_for('index')) if form.validate_on_submit(): api = InstagramAPI(client_id=app.config['INSTAGRAM_ID'], client_secret = app.config['INSTAGRAM_SECRET']) # if max_tag_id > 0: # if request.args['query']: # tag_name = request.args['query'] # tag_media, next = api.tag_recent_media(count = 20, max_id = max_tag_id, tag_name = request.args['query']) # else: tag_media, next = api.tag_recent_media(count = 20, tag_name = form.query.data) instagram_results = [] for media in tag_media: instagram_results.append(media.images['thumbnail'].url) try: max_tag_id = next.split('&')[2].split('max_tag_id=')[1] except: max_tag_id = None return render_template('book.html', query = form.query.data, instagram_results = tag_media, pics = pics, form = form, next = max_tag_id, book = book) return render_template('book.html', book = book, pics = pics, form = form)
def update_moment_tag(update): print update hashtag = update["object_id"] #Give the id of concerned Moment if hashtag == "paietamoustache" or hashtag=="payetamoustache": moment = models.Moment.query.get(8364) else: print "HASHTAG : "+hashtag.lower() moment = models.Moment.query.filter(func.lower(models.Moment.hashtag) == hashtag).first() #Instagram API api = InstagramAPI(client_id=constants.INSTAGRAM_CLIENT_ID, client_secret=constants.INSTAGRAM_CLIENT_SECRET) medias = api.tag_recent_media(count =1, tag_name = hashtag) #On créé une nouvelle photo photo = models.Photo() for media in medias[0]: photo.save_instagram_photo(media) db.session.add(photo) db.session.commit() moment.photos.append(photo) db.session.commit()
class Aggregator(GenericAggregator): ACCESS_TOKEN = settings.EDSA_INSTAGRAM_ACCESS_TOKEN def init_connector(self): self.connector = InstagramAPI(access_token=self.ACCESS_TOKEN) def search(self, query): if query.startswith('#'): query = query.lstrip('#') res = self.connector.tag_recent_media(tag_name=query)[0] datas = [] for media in res: if media.caption: text = media.caption.text else: text = "" data = { 'social_id': media.id, 'name': 'instagram %s' % media.id, 'slug': 'instagram_%s' % media.id, 'ressource_date': media.created_time, 'description': text, 'media_url': media.get_standard_resolution_url(), 'media_url_type': 'image', 'author': media.user.username, } datas.append(data) return datas
def load_photos(request): """ Loads photos from Insagram (not yet other,like G+) and insert in database. """ api = InstagramAPI(client_id=settings.INSTAGRAM_CLIENT_ID, client_secret=settings.INSTAGRAM_CLIENT_SECRET) search_result = api.tag_recent_media(MEDIA_COUNT, LARGE_MEDIA_MAX_ID, MEDIA_TAG) info_photo = "" for m in search_result[0]: photo, is_created = Photo.objects.get_or_create(photo_id=m.id, username=m.user.username) is_like_count_updated = False if not photo.like_count == m.like_count: photo.username = m.user.username photo.user_avatar_url = m.user.profile_picture photo.photo_url = m.images["standard_resolution"].url photo.created_time = m.created_time photo.like_count = m.like_count photo.save() is_like_count_updated = True info_photo += "<li>{} {} {} {} {} {} {} {}</li>".format( m.id, m.user.username, '<img src="{}"/>'.format(m.user.profile_picture), '<img src="{}"/>'.format(m.images["standard_resolution"].url), m.created_time, m.like_count, is_created, is_like_count_updated, ) html = "<html><body><ul>{}</ul></body></html>".format(info_photo) return HttpResponse(html)
def load_photos(request): """ Loads photos from Instagram and populates database. """ api = InstagramAPI(client_id=settings.INSTAGRAM_CLIENT_ID, client_secret=settings.INSTAGRAM_CLIENT_SECRET) search_result = api.tag_recent_media(MEDIA_COUNT, LARGE_MEDIA_MAX_ID, MEDIA_TAG) info = '' # list of media is in the first element of the tuple for m in search_result[0]: p, is_created = Photo.objects.get_or_create(id=m.id, username=m.user.username) is_like_count_updated = False if not p.like_count == m.like_count: p.username = m.user.username p.user_avatar_url = m.user.profile_picture p.photo_url = m.images['standard_resolution'].url p.created_time = m.created_time p.like_count = m.like_count p.save() is_like_count_updated = True info += '<li>{} {} {} {} {} {} {} {}</li>'.format( m.id, m.user.username, _img_tag(m.user.profile_picture), _img_tag(m.images['standard_resolution'].url), m.created_time, m.like_count, is_created, is_like_count_updated) html = "<html><body><ul>{}</ul></body></html>".format(info) return HttpResponse(html)
class Aggregator(GenericAggregator): ACCESS_TOKEN = settings.EDSA_INSTAGRAM_ACCESS_TOKEN def init_connector(self): self.connector = InstagramAPI(access_token=self.ACCESS_TOKEN) def search(self, query): if query.startswith('#'): query = query.lstrip('#') res = self.connector.tag_recent_media(tag_name=query)[0] tz = timezone.get_current_timezone() datas = [] for media in res: if media.caption: text = media.caption.text else: text = "" data = {'social_id': media.id, 'name': 'instagram %s' % media.id, 'slug': 'instagram_%s' % media.id, 'ressource_date': tz.localize(media.created_time), 'description': text, 'media_url': media.get_standard_resolution_url(), 'media_url_type': 'image', 'author': media.user.username, } datas.append(data) return datas
def tag_search(): api = InstagramAPI(client_id='b64f54dc4fb3486f87b55d92381e2625', client_secret='b5fa80c366b94cc980c882855630fe92') tag_search, next_tag = api.tag_search(q="thefuturepark") tag_recent_media, next = api.tag_recent_media(count=1000,tag_name="thefuturepark") photos = [] content = "<h2>Media Search</h2>" for tag_media in reversed(tag_recent_media): # print tag_media res = tag_media.caption.text retweet = 0 favorites = tag_media.like_count name = tag_media.user.username real = tag_media.user.full_name pic = tag_media.user.profile_picture followers = 0 # date = unicode(tag_media.created_time.replace(microsecond=0)) date = tag_media.created_time print date embed = tag_media.get_standard_resolution_url() enable = True photos.append('<img src="%s"/>' % tag_media.get_standard_resolution_url()) photos.append(tag_media.caption.text) data = models.Trace.query.filter(models.Trace.key==res, models.Trace.name ==name) if data.count() > 0: print "kaparehas" else: print "wala" t = models.Trace(tweet='thefuturepark', key=res, retweet=retweet, favorites=favorites, name=name, real=real, pic=pic, followers=followers, date=date,embed=embed,enable=enable) db.session.add(t) db.session.commit() content += ''.join(photos) return content
class MediaServer: def __init__(self, media_repository): self.client_id = client_id = os.environ["INSTAGRAM_CLIENT_ID"] self.client_secret = os.environ["INSTAGRAM_CLIENT_SECRET"] self.hashtag = os.environ["INSTAGRAM_HASHTAG"] self.api = InstagramAPI(client_id=self.client_id, client_secret=self.client_secret) self.media_repository = media_repository @timeout(30) def fetch(self): SupportTeam.notify("polling for new media #%s..." % self.hashtag) latest_media_id = self.media_repository.latest_media_id() recent_media = self.api.tag_recent_media(5, latest_media_id, self.hashtag) for instagram_media in recent_media[0]: if not self.media_repository.has_media_with_id(instagram_media.id): media = Media( id=instagram_media.id, url=str(instagram_media.images["standard_resolution"].url), status="new" ) SupportTeam.notify("%s - new media %s" % (media.id, media.url)) self.media_repository.create(media) def next(self): if not self.media_repository.has_available_media(): self.fetch() if self.media_repository.has_available_media(): return self.media_repository.peek_available_media() return None
def handle(self, *args, **options): # raise CommandError('Some error.') api = InstagramAPI(client_id=settings.INSTAGRAM_CLIENT_ID, client_secret=settings.INSTAGRAM_CLIENT_SECRET) search_result = api.tag_recent_media(MEDIA_COUNT, LARGE_MEDIA_MAX_ID, MEDIA_TAG) info = '' # list of media is in the first element of the tuple for m in search_result[0]: photo, is_created = Photo.objects.get_or_create( photo_id=m.id, username=m.user.username) is_like_count_updated = False if not photo.like_count == m.like_count: photo.username = m.user.username photo.user_avatar_url = m.user.profile_picture photo.photo_url = m.images['standard_resolution'].url photo.created_time = m.created_time.replace(tzinfo=utc) photo.like_count = m.like_count photo.save() is_like_count_updated = True info = '' info += '{id}\n{username}\n{avatar_url}\n{photo_url}\n'.format( id=m.id, username=m.user.username, avatar_url=m.user.profile_picture, photo_url=m.images['standard_resolution'].url) info += '{created}\n{like}\n{is_created}\n{is_updated}\n'.format( created=m.created_time, like=m.like_count, is_created=is_created, is_updated=is_like_count_updated) info += 40 * '-' self.stdout.write(info)
def slideshow(request, timeout=4, speed=1, tag='nofilter'): show_message = True if request.GET.get('message') == 'false': show_message = False if not request.session.get('token'): return redirect('totem.views.auth') token = request.session.get('token') output = {} api = InstagramAPI(access_token=token) medias, pagination = api.tag_recent_media(count=30, tag_name=tag) refresh_time = (speed + timeout) * len(medias) output['medias'] = medias output['timeout'] = timeout output['speed'] = speed output['tag'] = tag output['refresh_time'] = refresh_time output['show_message'] = show_message return render_to_response('totem/slideshow.html', output, context_instance=RequestContext(request))
class Setup: def __init__(self, tag_name): #system vars self.cur = os.getcwd() # import keys config = SafeConfigParser() config.read(self.cur + '/app/settings.ini') client_id = config.get('Instagram', 'client_id') # IG client id (settings.ini) client_secret = config.get('Instagram', 'client_secret') # IG client secret (^) self.api = InstagramAPI(client_id=client_id, client_secret=client_secret) self.images = self.cur + '/app/static/images/' self.housekeeping() self.tag_name=tag_name pprint("looking for \'%s\'..." % self.tag_name) # download 5, but only one image is used at a time self.recent = self.api.tag_recent_media(5, 1000000000, self.tag_name) # recent[0] is list of returned media for media in self.recent[0]: self.keep(media.images['standard_resolution'].url) pprint("Downloaded %s images" % len(self.recent[0])) def housekeeping(self): filelist = [ f for f in os.listdir(self.images + ".") if f.endswith(".jpg") ] pprint("Removing old image files.") for f in filelist: os.remove(self.images + f) def keep(self, img): name = str(img)[-20:] # create new file for img with open(self.images + name, 'w'): urllib.urlretrieve(img, self.images + name)
def tag(request, tag): api = InstagramAPI(client_id='53ff568efcd6492eb9b88c7b92a615b4', client_secret='3649d3a0675647b1839a5aa580a10dbc') photos = [] tag_m, next = api.tag_recent_media(tag_name=tag.encode('utf-8'), count=16) photos = photos + tag_m pages = [] next_url = [] if next != None: ind = next.find('max_tag_id=') ind += 11 nm = next[ind:] pages.append(nm) next_url = "http://" + str(request.META['HTTP_HOST']) + "/tag/" + tag.encode('utf-8') + "/" + max(pages) for photo in photos: photo.created_time = photo.created_time + timedelta(hours=2) likes = api.media_likes(photo.id) photo.l = len(likes) return render_to_response( 'tag.html', {'photos': photos, 'next_url': next_url}, context_instance=RequestContext(request))
def _init(self, *args, **kwargs): """ start the ball a rolling with a request to instagram API open a csv file and output the headers and rows based on results """ api = InstagramAPI( client_id = INSTAGRAM_CLIENT_ID, client_secret = INSTAGRAM_CLIENT_SECRET ) instagram_media = api.tag_recent_media(IMAGE_COUNT, 0, IMAGE_HASHTAG) # open the csv file with open(CSV_FILENAME, "wb") as csv_file: csv_output = csvkit.py2.CSVKitWriter(csv_file, delimiter=",", encoding="utf-8") # write the header row to the csv file csv_output.writerow(["hashtag", "local_date_time", "user_name", "image_link", "image_caption", "like_count", "comment_count", "post_link", "post_type", "post_tags", "post_likes", "utc_date_time"]) # loop through the results for item in instagram_media[0]: # build a new csv row csv_row = self.build_csv_row_from(item) # write the new csv row csv_output.writerow(csv_row)
def instagram(): COUNT = 30 TAG_NAME = "dirty30ak" #TAG_NAME = "mtconness" INSTAGRAM_API_KEY = request.environ.get('INSTAGRAM_API_KEY') api = InstagramAPI(access_token=INSTAGRAM_API_KEY) photos, next = api.tag_recent_media(COUNT, None, TAG_NAME) return render_template("instagram.html", photos=photos)
def searchPicturesByTag(self,count,tag): api = InstagramAPI(client_id=self._client_id, client_secret=self._s_client_id) recent_media, next = api.tag_recent_media(count=count,tag_name=tag) for media in recent_media: self.instagram_user = media.user.username self.standard_resolution_pictures.append(media.images['standard_resolution'].url) self.low_resolution_pictures.append(media.images['low_resolution'].url) self.thumbnail_pictures.append(media.images['thumbnail'].url)
def get_latest_photos(hashtag, num): api = InstagramAPI(access_token=token, client_secret=CONFIG['client_secret']) result, next_tag = api.tag_search(q=hashtag) tag_recent_media, next = api.tag_recent_media(count=num, tag_name=(result[0].name if len(result) > 0 else hashtag)) photos = [] for tag_media in tag_recent_media: instaphoto = instagram_photo(tag_media) photos.append(instaphoto) return photos
def _instagram(tag): access_token = "" api = InstagramAPI(access_token=access_token) tag_search, next_tag = api.tag_search(q=tag) if tag_search: tag_recent_media, next = api.tag_recent_media( tag_name=tag_search[0].name) return tag_recent_media return []
def instagram(): COUNT = 50 tag_name = app.config['TAG_NAME'] insta_api_key = app.config['INSTAGRAM_API_KEY'] insta_secret = app.config['INSTAGRAM_CLIENT_SECRET'] api = InstagramAPI(access_token=insta_api_key, client_secret=insta_secret) photos, next = api.tag_recent_media(COUNT, None, tag_name) return render_template("instagram.html", photos=photos)
def timed_job(): print("Get new data from da insta") access_token = redis.get("insta_access_token") api = InstagramAPI(access_token=access_token, client_secret=os.environ.get('INSTA_SECRET')) parse_result(api.tag_recent_media(tag_name="fitness")) #sched.start()
def search_by_hashtag(): hashtag = request.args.get('hashtag', 'gamer') count = request.args.get('count', MAX_COUNT) api = InstagramAPI(access_token=session['access_token']) recent_media, next = api.tag_recent_media(count, MAX_ID, hashtag) templateData = { 'size': request.args.get('size', 'thumb'), 'media': recent_media } return render_template('media.html', **templateData)
def downloadMedia(): # Set tag and number of pages to pull tag = u'refugeecrisis' max_num_pages = 100 # Read Access Token obtained using getToken(), get Instagram API access_token_full = pickle.load( open( "accessToken.txt", "rb" ) ) access_token = access_token_full[0] client_secret = "91c43e9262494f4c82c887a88b21068c" api = InstagramAPI(access_token=access_token, client_secret=client_secret) # Retrieve tagged images from Instagram print('Grabbing data from Instagram...') num_pages = 1 print(' - Reading page 1/' + str(max_num_pages) + '. 0 images parsed.') recent_media, next_ = api.tag_recent_media(33, None, tag) if recent_media is None: raise NameError('No data retrieved from Instagram!') while next_: num_pages = num_pages + 1 print(' - Reading page ' + str(num_pages) + '/' + str(max_num_pages) + '. ' + str(len(recent_media)) + ' images parsed.') max_tag = next_.split('max_tag_id=')[1] more_media, next_ = api.tag_recent_media(50, max_tag, tag) recent_media.extend(more_media) if num_pages >= max_num_pages: break # Filter out images that do not contain location metadata media_filtered = [] for media in recent_media: if media.caption != None: try: print(str(media.location) + ' ' + str(media.location.point.latitude) + ' ' + str(media.location.point.longitude)) # If the location isn't set, it will skip to the exception media_filtered.append(media) except AttributeError: pass print media.caption.text # Save retrieved data in pickle pickle.dump( media_filtered, open( "media_filtered.p", "wb" ) )
def get_media_list_by_tag(tag_name, count=None, max_tag_id=None): if count is None: count = 16 api = InstagramAPI(client_id=config.AUTH["client_id"]) if max_tag_id is None: original_media_list, next_url = api.tag_recent_media(tag_name=tag_name, count=count) else: original_media_list, next_url = api.tag_recent_media( tag_name=tag_name, count=count, max_tag_id=max_tag_id) # process media list media_list = list() for original_media in original_media_list: tag_list = [] for tag in original_media.tags: tag_list.append(tag.name) image_dict = dict() for key, url in original_media.images.iteritems(): image_dict[key] = str(url) video_dict = None if hasattr(original_media, "videos"): video_dict = dict() for key, url in original_media.videos.iteritems(): video_dict[key] = str(url) media = Media(id=original_media.id, type=original_media.type, caption=original_media.caption.text, user=original_media.user.username, created_time=original_media.created_time, tags=tag_list, images=image_dict, videos=video_dict) media_list.append(media) # get next_tag_id max_tag_id = None if next_url is not None: next_url_parsed = urlparse.urlparse(next_url) assert "max_tag_id" in urlparse.parse_qs(next_url_parsed.query) assert isinstance( urlparse.parse_qs(next_url_parsed.query)["max_tag_id"], list) assert len(urlparse.parse_qs(next_url_parsed.query)["max_tag_id"]) == 1 max_tag_id = urlparse.parse_qs(next_url_parsed.query)["max_tag_id"][0] return media_list, max_tag_id
def get_instagram(): api = SocialSetting.objects.filter(api_type='IN')[0] secret = api.api_client_secret token = api.api_access_token req = InstagramAPI(access_token=token, client_secret=secret) if api: if api.api_last_id: recent_tags, next_ = req.tag_recent_media(tag_name=api.instagram_hashtag, count=10, max_tag_id=api.api_last_id) #accepts_parameters=['count', 'max_tag_id', 'tag_name'], else: recent_tags, next_ = req.tag_recent_media(tag_name=api.instagram_hashtag, count=10) #accepts_parameters=['count', 'max_tag_id', 'tag_name'], #recent_tags, next_ = api.tag_recent_media(tag_name="tgif", count=10, max_tag_id="1051706417356389558_318480430") #accepts_parameters=['count', 'max_tag_id', 'tag_name'], if len(recent_tags) > 0: api.api_last_id = recent_tags[0].id api.save() processInstas(recent_tags) return "Success, processing" else: return "Nothing to process" else: return "No Instgram API"
def instagram_search(max_id="", skip=0): api = InstagramAPI(access_token=ACCESS_TOKEN, client_id=CLIENT_ID, client_secret=CLIENT_SECRET) media_ids, next = api.tag_recent_media(tag_name=TAG_NAME, count=30, max_tag_id=max_id) print next with open(OUTPUT_CSV, 'w') as csvfile: writer = csv.writer(csvfile, delimiter=str(','), quoting=csv.QUOTE_MINIMAL) writer.writerow( ['origin_url', 'file_name', 'latitude', 'longitude', 'tags']) count = 0 + skip for media_id in media_ids: thumb_url = media_id.images['thumbnail'].url thumb320_url = media_id.images['low_resolution'].url print "now %d downloading ..." % count try: r = requests.get(thumb_url) r2 = requests.get(thumb320_url) if r.status_code == 200 and r2.status_code == 200: file_name = "%04d.jpg" % count path = "{0}/{1}".format(OUTPUT_IMAGE_DIR, file_name) save_image(path, r.content) path = "{0}/{1}".format(OUTPUT_IMAGE320_DIR, file_name) save_image(path, r2.content) tags = [tag.name for tag in media_id.tags] tags = unicode(','.join(tags)).encode('utf_8') if hasattr(media_id, "location"): latitude = media_id.location.point.latitude longitude = media_id.location.point.longitude writer.writerow( [thumb_url, file_name, latitude, longitude, tags]) else: writer.writerow([thumb_url, file_name, "", "", tags]) except Exception as e: print str(type(e)) pass count += 1 temp, max_tag_id = next.split("max_tag_id=") max_tag_id = str(max_tag_id) return max_tag_id
class IGClientFacade: def __init__(self, config): self.access_token = config["access_token"] self.client_id = config["client_id"] self.client_secret = config["client_secret"] self.redirect_url = config["redirect_url"] self.api = InstagramAPI(access_token=self.access_token, client_secret=self.client_secret, client_id=self.client_id) def getMediaByTag(self, tag, count=1): return self.api.tag_recent_media(count=count, tag_name=tag)
def getMediaObjectVideos(self,tag,count): MediaObjectVideos = [] MediaObject = [] k = 0 if count == 0: return MediaObjectVideos tag = self.searchstring(tag) api = InstagramAPI(client_id=self.client_id, client_secret= self.client_secret) recent_media, next_ = api.tag_recent_media(count = 70, tag_name = tag) for media in recent_media: if media.type == 'video': MediaObjectVideos.append(Post(str(media.videos['standard_resolution']).split('Video: ')[1], str(media.videos['low_resolution']).split('Video: ')[1], str(media.videos['low_bandwidth']).split('Video: ')[1], media.type, media.like_count, media.comment_count)) if len(MediaObjectVideos) >= count: while k< len(MediaObjectVideos): MediaObject.append(json.dumps(MediaObjectVideos[k].__dict__)) k = k+1 return MediaObject i = 0 l = 0 m = 0 while i<20 and next_: recent_media, next_ = api.tag_recent_media(count=70, tag_name=self.searchstring(tag), with_next_url=next_) for media in recent_media: if media.type == 'video': MediaObjectVideos.append(Post(str(media.videos['standard_resolution']).split('Video: ')[1], str(media.videos['low_resolution']).split('Video: ')[1], str(media.videos['low_bandwidth']).split('Video: ')[1], media.type, media.like_count, media.comment_count)) if len(MediaObjectVideos) >= count: while l< len(MediaObjectVideos): MediaObject.append(json.dumps(MediaObjectVideos[l].__dict__)) l = l+1 return MediaObject i += 1 while m< len(MediaObjectVideos): MediaObject.append(json.dumps(MediaObjectVideos[m].__dict__)) m = m+1 return MediaObject
def _instagram(self, args): api = InstagramAPI(client_id=self.client_id, client_secret=self.client_secret) tags = args.keywords.split(' ') try: images = [] for tag in tags: imgs, str_next = api.tag_recent_media(tag_name=str(tag), count=args.max_results) images = list(itertools.chain(images, imgs)) except Exception, error: images = []
class IG(object): """ This class for handling Instagram API """ def __init__(self, access_token=None, client_id=None, client_secret=None, key_tag=None, seperator=None): self.access_token = access_token self.client_id = client_id self.client_secret = client_secret self.api = InstagramAPI(access_token=self.access_token, client_secret=self.client_secret) self.key_tag = key_tag or "productaddavii" self.seperator = seperator or '|' def get_recent_medias(self): return self.api_recent_media()[0] def parser(self, media): """ parsing from IG to ItemIg """ media_string = media.caption.text.split(self.seperator) title = media_string[0].strip() price = media_string[1].strip() description = media.caption.text short_description = media.caption.text categories = [116] images = [{ 'src':media.images['standard_resolution'].url, 'position':0 },{ 'src':media.images['standard_resolution'].url, 'position':1 }] tags = [31] return ItemIg(title, price, description, short_description, categories, images, tags) def search_media_by_tag(self): result = [] medias = self.api.tag_recent_media(tag_name=self.key_tag)[0] if medias != []: for media in medias: result.append(self.parser(media)) return result def download(self, with_file=False): medias = self.search_media_by_tag() objects = [] for media in medias: objects.append(self.parser(media)) return objects
def get_ig_media(tag): client_id = '0db0c30814c14ac48a58c8e27a7b4a5a' client_secret = '8681192578424d78aea183f1bf05f465' from instagram.client import InstagramAPI api = InstagramAPI(client_id=client_id, client_secret=client_secret) media, _next = api.tag_recent_media(33, 0, tag) # let's make it a bit more interesting choice = randint(0, 33) return media[choice].get_standard_resolution_url()
def Instagram_API(min_id=None): api = InstagramAPI(client_id='edf88a2a6fa94c9889e9800db8317f68', client_secret='73975e1a5b674c8e961568c463f3a8ec') bagitnyc_media = [] # Get up to 200 media for page in api.tag_recent_media(tag_name='bagitnyc', as_generator=True, max_pages=10): # Open the page and push its contents onto bagitnyc_media bagitnyc_media += page[0] # If min_id passed, only return media that came after it. # Lambda is the same as defining a new function within the filter function. If min_id is passed in the API.tag_recent_media, retrieve all media with with greater id value (photos taken since oldest photo in api call) # if min_id: # bagitnyc_media = filter(lambda m: m.id > min_id, bagitnyc_media) return bagitnyc_media
class InstagramPopularMediaNode(template.Node): """ Template node for displaying the popular media of Instagram. The API doesn't need authentication, just basic access. """ def __init__(self, count): self.count = count self.api = InstagramAPI(client_id=DJANGO_INSTAGRAM_CLIENT_ID) def render(self, context): popular_media = self.api.tag_recent_media(tag_name='test') # raise Exception(popular_media) context['popular_media'] = popular_media print popular_media return ''
def get_instagram_photos(): # É necessário configurar os campos INSTAGRAM_TOKEN e INSTAGRAM_USER # no conf.py try: access_token = conf.INSTAGRAM_TOKEN except KeyError: access_token = "" try: user_id = conf.INSTAGRAM_USER except KeyError: user_id = "" search_tag = conf.SEMINARIO_INSTAGRAM_TAG photos = [] try: api = InstagramAPI(access_token=access_token) # recent_media, next = api.user_recent_media(user_id=user_id, count=-1) recent_media, next = api.tag_recent_media(tag_name=search_tag, count=20) # print recent_media for media in recent_media: # if hasattr(media, 'tags'): # if tag in [ t.name for t in media.tags ]: print media, dir(media) content = { 'link': media.link, 'url': media.images['standard_resolution'].url, 'thumb': media.images['low_resolution'].url, 'caption': media.caption.text if media.caption else "", 'tags': media.tags, 'datetime': media.created_time } photos.append(content) except Exception as e: print "ERRO AO BUSCAR AS FOTOS DO INSTAGRAM" print e return photos
def getSellPosts(): from instagram.client import InstagramAPI api = InstagramAPI(access_token=ACCESS_TOKEN) middle = [] print SITE_TAG + "The sitetag" middle = api.tag_recent_media(tag_name=SITE_TAG) final = [] print middle[0] for item in middle[0]: for tag in item.tags: if tag.name == SITE_TAG: newelem = {} newelem['image'] = item.images['standard_resolution'] newelem['user'] = item.user.username caption = str(item.caption.text) newelem['title'] = caption[:(caption.find('#'))] newelem['description'] = item.caption newelem['time'] = item.created_time final.append(newelem) #this makes sure no post is added twice break return final
def suck(save_item, handle_error, source): api = InstagramAPI(client_id=settings.INSTAGRAM['client_id'], client_secret=settings.INSTAGRAM['client_secret']) if 'lastRetrieved' not in source: source['lastRetrieved'] = {} if 'thaicoup' in source['lastRetrieved']: last_id = source['lastRetrieved']['thaicoup'] else: last_id = 0 tag_media, next = api.tag_recent_media(50, last_id, 'thaicoup') source['lastRetrieved'] = {'thaicoup': 0} source['lastRetrieved']['thaicoup'] = str(tag_media[0].id) for media in tag_media: item = transform(media) save_item(item) return source['lastRetrieved']
def get_instagram_result(search): search_pattern = [search.replace(" ", ""), search.split()[0]] instagram_result = [] MAX_PHOTO = 6 counts = MAX_PHOTO CLIENT_ID = 'SECRET' CLIENT_SECRET = 'SECRET' api = InstagramAPI(client_id=CLIENT_ID, client_secret=CLIENT_SECRET) for pattern in search_pattern: recent_media = 0 try: recent_media, mynext = api.tag_recent_media(count=counts, tag_name=pattern) except: pass if recent_media: for item in recent_media: if item.user.username not in list_banned('instagram'): instagram_result.append([ item.images['standard_resolution'].url, item.user.username ]) else: print 'some item banned' if len(instagram_result) > MAX_PHOTO - 1: return instagram_result[:MAX_PHOTO] break else: counts = MAX_PHOTO - len(instagram_result) return instagram_result
def handle(self, *args, **options): while True: now = datetime.datetime.utcnow().replace(tzinfo=utc) api = InstagramAPI(client_id=settings.INSTAGRAM_CLIENT_ID) tags = Tag.objects.filter( semaphore=False, last_processed_date__lte=now - datetime.timedelta(seconds=900), ) for tag in tags: tag.last_processed_date = now tag.semaphore = True tag.save() try: insta_result = api.tag_recent_media(100, None, tag.tag) except: self.update_tag(tag) continue for media in insta_result[0]: try: Image.objects.get(tag=tag, instagram_id=media.id) break except Image.DoesNotExist: image = Image( tag=tag, instagram_id=media.id, link=media.link, thumbnail_url=media.images['thumbnail'].url, ) image.save() self.update_tag(tag) self.close_db_connection() time.sleep(300)
def insta_tag(): returnval='' api = InstagramAPI(access_token=ACCESS_TOKEN, client_secret=CLIENT_SECRET) try: #if ' ' in search_term: # search_term = search_term.replace(' ', '') search_term = 'selfie' if not api.tag_search(search_term, 1): print "No result found. :(" else: recent_media, next_ = api.tag_recent_media(1, 20, search_term) for media in recent_media: link = media.link returnval += ' '+link+' \n' return returnval except InstagramAPIError as e: if (e.status_code == 400): return "Cannot retrieve data. User is set to private." if (e.status_code == 404): return "Content not found."
locationID=sys.argv[1] iterations=sys.argv[2] iterations = int(iterations) locationID = int(locationID) max_tag_id = '' all_media = [] ans = api.location_recent_media(33,max_tag_id,locationID) # Get your first media items and max_tag_id from that search for m in ans[0]: all_media.append(m) parsed = urlparse(ans[1]) params = {a:b for a,b in [x.split('=') for x in parsed.query.split('&')]} # Iterate backwards through media, using max_tag_id, appending posts to the all_media array # Increase the range() number to run more iterations for more data for i in range(iterations): try: max_tag_id = params['max_id'] ans = api.tag_recent_media(33,max_tag_id, locationID) for m in ans[0]: all_media.append(m) parsed = urlparse(ans[1]) params = {a:b for a,b in [x.split('=') for x in parsed.query.split('&')]} except AttributeError: break # Save a pickle file to work off in the future pickle.dump(all_media, open('%s_locationData.p'%locationID, 'wb'))
header = '|'.join([ips, signature]) j = 0 i = 0 timestr = time.strftime("%Y%m%d-%H%M%S") tags = raw_input("Enter Tag that you want to Map: ") api = InstagramAPI(access_token=access_token, client_secret=client_secret, client_ips=ips) print api.tag(tags).media_count lats, lons = [], [] while i < 4: m = api.tag_recent_media(count=40, tag_name=tags, max_tag=j) match = re.search(r'max_tag_id=(\d+)', m[1]) j = match.group(1) for k in m[0]: try: a = str(k.location.point.latitude) + ',' + str( k.location.point.longitude) print a lats.append(k.location.point.latitude) lons.append(k.location.point.longitude) except Exception, e: continue i = i + 1 map = Basemap(projection='robin', resolution='l',
str1 = ''.join(words) hashtag = str1 filepreamble = "/export/sc/hamed/qtrhealth/instagram/foodimages/Mar2015week4/hashtag_" filepostamble = ".txt" outputfilename = filepreamble + hashtag + filepostamble outputfile = open(outputfilename, 'w') string1 = "curl https://api.instagram.com/v1/tags/" string2 = "/media/recent?access_token=XXXXXXX" print hashtag cmd = string1 + hashtag + string2 #os.system('curl "https://api.instagram.com/v1/locations/search?access_token=XXXXXXX&foursquare_v2_id="+location_id ') time.sleep(1) try: tag_search, next_tag = api.tag_search(q=hashtag) tag_recent_media, next = api.tag_recent_media( tag_name=tag_search[0].name) except bind.InstagramAPIError, ie: if ie.status_code == 400: print "protected account (400) APINotAllowedError-you cannot view this resource" continue elif ie.status_code == 503: # this should not happen, but Instagram returns this message no matter what x_ratelimit_remaining is. print "rate limit (503) Rate limited-Your client is making too many request per second" time.sleep(10) continue else: print ie time.sleep(30) continue except bind.InstagramClientError, ice:
'fitness', 'heart', 'cool', 'jj', 'like4like', 'amazing', 'doubletap', 'face', 'goodtimes', 'igdaily', 'repost', 'sea', 'friday', 'loveyou', 'drunk', 'cake' ] api = InstagramAPI(client_id="4aa0a8ef77b34a0d8e3ddf2d97523f22", client_secret="da88550123c74ddb9de9d7a3e0bb088d") total = 0 maxid = 0 try: for tag in words: maxid = 0 for x in xrange(1): sleep(5) if (maxid == 0): popular_media, pagin = api.tag_recent_media(count=100, tag_name=tag) print pagin else: print "trying page %d for tag %s" % (x, tag) api.tag_recent_media(count=200, max_id=maxid, tag_name=tag) for media in popular_media: curimg = media.images['standard_resolution'] # dont save images that aren't 612 x 612 if (curimg.width != 612 or curimg.height != 612): continue url = curimg.url maxid = media.id try: Image.open(StringIO( urllib.urlopen(url).read())).save("images/" + str(media.id) +