def get(self): ig_user_id = self.request.get("ig_user_id") if not ig_user_id: self.redirect("/connect") instagram_client = InstagramAPI(**settings.INSTAGRAM_CONFIG) access_token = instagram_client.exchange_user_id_for_access_token( ig_user_id) instagram_client = InstagramAPI(access_token=access_token) user = instagram_client.user("self") profiles = Profile.all() profiles.filter("ig_user_id = ", user.id) profile = (profiles.get() or Profile()) profile.full_name = (user.full_name or user.username) profile.ig_user_id = user.id profile.ig_username = user.username profile.ig_access_token = access_token profile.put() cookieutil = LilCookies(self, settings.COOKIE_SECRET) cookieutil.set_secure_cookie(name="ig_user_id", value=user.id, expires_days=365) self.redirect("/")
def __init__(self, client_id=None, client_secret=None, redirect_url=None, access_token=None, name=None, ty=None, **kwargs): self.client_id = client_id self.client_secret = client_secret self.redirect = redirect_url self.name = name self.ty = ty if access_token: self.access_token = access_token self.api = InstagramAPI(access_token=access_token) else: self.api = InstagramAPI(client_id=client_id, client_secret=client_secret, redirect_uri=redirect_url) url = self.api.get_authorize_login_url( scope=['basic', 'likes', 'comments', 'relationships']) print 'This account needs to be authenticated. Visit this url:' print url code = raw_input('Please enter the result code:').strip() self.access_token, user_info = self.api.exchange_code_for_access_token( code) db.instagram.update({'name': self.name}, {'$set': { 'access_token': self.access_token }}) self.api = InstagramAPI(access_token=access_token) self.uid = self._get_uid(self.name)
def instagram_oauthorized(): code = request.args.get('code', None) if code: client_id = app.config['INSTAGRAM_CLIENT_ID'] client_secret = app.config['INSTAGRAM_SECRET'] redirect_uri = url_for('instagram_oauthorized', _external=True) api = InstagramAPI(client_id=client_id, client_secret=client_secret, redirect_uri=redirect_uri) try: access_token = api.exchange_code_for_access_token(code) except OAuth2AuthExchangeError as e: flash("Instagram authorization failed") return redirect(url_for('index')) except ServerNotFoundError as e: flash("Instagram authorization failed") return redirect(url_for('index')) if 'bridge_id' in session: bridge = get_or_create_bridge(bridge_id=session['bridge_id']) if not bridge: pass # this should be an error else: bridge = get_or_create_bridge() bridge.instagram_access_code = access_token[0] data = access_token[1] bridge.instagram_account_id = data['id'] bridge.instagram_handle = data['username'] user_api = InstagramAPI(access_token=bridge.instagram_access_code, client_secret=client_secret) try: latest_media, _ = user_api.user_recent_media( user_id=bridge.instagram_account_id, count=1) except Exception: latest_media = [] if len(latest_media) > 0: bridge.instagram_last_id = datetime_to_timestamp( latest_media[0].created_time) else: bridge.instagram_last_id = 0 db.session.commit() else: flash("Instagram authorization failed") return redirect(url_for('index'))
def init_API_queue(): global API_Queue api_keys = db['api_keys'].find() for key in api_keys: if key['access_token']: api = InstagramAPI(access_token=key['access_token']) else: api = InstagramAPI(client_id=key['client_id'], client_secret=key['client_secret']) API_Queue.append(api)
def handle(token=ACCESS_TOKEN): if token: try: return InstagramAPI(access_token=token) except: pass try: token = access_token() return InstagramAPI(access_token=token) except: print '**** WARNING: NO INSTAGRAM AUTH ****' return no_auth_handle()
def instagram_oauthorized(): code = request.args.get('code', None) if 'twitter' in session and 'mastodon' in session and code: client_id = app.config['INSTAGRAM_CLIENT_ID'] client_secret = app.config['INSTAGRAM_SECRET'] redirect_uri = url_for('instagram_oauthorized', _external=True) api = InstagramAPI(client_id=client_id, client_secret=client_secret, redirect_uri=redirect_uri) try: access_token = api.exchange_code_for_access_token(code) except OAuth2AuthExchangeError as e: flash("Instagram authorization failed") return redirect(url_for('index')) # look up settings bridge = db.session.query(Bridge).filter_by( mastodon_user=session['mastodon']['username'], twitter_handle=session['twitter']['screen_name'], ).first() bridge.instagram_access_code = access_token[0] data = access_token[1] bridge.instagram_account_id = data['id'] bridge.instagram_handle = data['username'] user_api = InstagramAPI(access_token=bridge.instagram_access_code, client_secret=client_secret) try: latest_media, _ = user_api.user_recent_media( user_id=bridge.instagram_account_id, count=1) except Exception: latest_media = [] if len(latest_media) > 0: bridge.instagram_last_id = datetime_to_timestamp( latest_media[0].created_time) else: bridge.instagram_last_id = 0 db.session.commit() else: flash("Instagram authorization failed") return redirect(url_for('index'))
def user(username, page=1): u = InstagramAPI(access_token=session['access_token'], client_secret=secret.secrets['client_secret']) id = u.user_search(username)[0].id user_media, next_ = u.user_recent_media(user_id=id,count=20) for i in range(1, page): user_media, next_ = u.user_recent_media(user_id=id, count=20, with_next_url=next_) photos_thumbnail = [] photos_standard = [] title = username + " Recent Media-Page " + str(page) prev_page = False next_page = False if next_: prev_page = True if page != 1: next_page = True for media in user_media: photos_thumbnail.append("%s" % media.images['thumbnail'].url) photos_standard.append("%s" % media.images['standard_resolution'].url) return render_template("recent.html", thumb=photos_thumbnail, photos=photos_standard, prev=prev_page, next=next_page, page=page, title=title)
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 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 auth_request(): api = InstagramAPI(access_token=OTHER['access_token']) target_ids = api.user_search(OTHER['target']) target_id = None for search_hit in target_ids: if search_hit.username == OTHER['target']: target_id = search_hit.id break if target_id == None: logging.error('Did not find user, please check username') return [] my_name = api.user().username logging.debug('Starting check recent media') recent_media, url = api.user_recent_media(user_id=target_id, count = 20) liked_media = [] for media in recent_media: logging.debug('Processing media %s' % media.id) users = api.media_likes(media.id) will_like = True for user in users: if user.username == my_name: will_like = False break if will_like: logging.debug('Liking media %s' % media.id) api.like_media(media.id) liked_media.append(media) else: logging.debug('Already liked media %s, aborting like' % media.id) return liked_media
def login_instagram(request): host = request.get_host() if ':' in host: # nginx host, _ = host.split(':') instagram_url = os.environ.get('INSTAGRAM') redirect_uri = f"{host}/accounts/login_instagram/" # user authorizes app code = request.GET.get('code') if code is not None: CONFIG = { 'client_id': settings.CLIENT_ID, 'client_secret': settings.CLIENT_SECRET, 'redirect_uri': 'http://localhost:8515/oauth_callback' } unauthenticated_api = InstagramAPI(**CONFIG) oauth_token = unauthenticated_api.exchange_code_for_access_token(code) instagram_account = oauth_token['user']['username'] if not AccessToken.objects.filter(uid=instagram_account).exists(): # no access_token found XXX AccessToken.objects.create( uid=instagram_account, access_token=oauth_token['access_token']) user = authenticate(uid=instagram_account) if user is not None: auth_login(request, user) return redirect('/') client_secret = os.environ.get('CLIENT_SECRET') url = "https://" + instagram_url + \ "/oauth/authorize/?client_id=" + client_secret + "&redirect_uri=" + \ redirect_uri + "&response_type=code&scope=basic+public_content+follower_list+relationships+likes'" return redirect(url)
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 _set_up_api_dict(self, api_key_fname): """Ensure the api_key_fname is valid, set up the api_dict :param api_key_fname: file containing api key token info :return: tuple of dictionary of api's and dictionary of api access token and client secret """ cwd = os.path.dirname(__file__) #gets current directory api_tokens_path = os.path.join(cwd, 'api_key_tokens', api_key_fname) #check for validity of path input if not os.path.exists(api_tokens_path): err_msg = '%s does not exist!' % api_key_fname err_msg.format(api_key_fname) # pdb.set_trace() raise IOerror(err_msg) api_dict, api_tokens_dict = dict(), dict() #1 indexing i = 0 with open(api_tokens_path, "r") as f: for line in f: i += 1 [access_token, client_secret] = line.split(',') api_tokens_dict[i] = dict() api_tokens_dict[i]['access_token'] = access_token api_tokens_dict[i]['client_secret'] = client_secret api_dict[i] = InstagramAPI(access_token=access_token, client_secret=client_secret) return api_dict, api_tokens_dict
def instagram(): results = [] api = InstagramAPI(client_id=app.config['CLIENT_ID'], client_secret=app.config['CLIENT_SECRET']) data = json.loads(request.data.decode()) lat = data["lat"] lng = data["lng"] dist = data["dist"] min_tstmp = data["min_timestamp"] your_location = api.media_search(count=100, lat=lat, lng=lng, distance=dist, min_timestamp=min_tstmp) for media in your_location: url = media.images['standard_resolution'].url pid = media.id img_paths = detect_faces(url, pid) if not img_paths == []: for img_path in img_paths: results.append(img_path) results = json.dumps(results) print "****** RESULTS ******" print " " print results return results
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 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
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 instagram2(key): api = InstagramAPI(client_id='b64f54dc4fb3486f87b55d92381e2625', client_secret='b5fa80c366b94cc980c882855630fe92') for item in api.user_recent_media(user_id=key, count=20, max_id=100): photo = item.images print dp, username, did,web, bio lol = "text" return lol
def get_insta_user(short_link, debug=1): """ Get instagram userid from a link posted on twitter """ print "Fetching instagram user. " try: response = urllib2.urlopen( short_link) # Some shortened url, eg: http://t.co/z8P2xNzT8k url_destination_https = response.url url_destination = url_destination_https.replace('https', 'http', 1) # from link get the media_id consumer = oembed.OEmbedConsumer() endpoint = oembed.OEmbedEndpoint( 'https://api.instagram.com/oembed?url=', ['http://instagr.am/p/*']) consumer.addEndpoint(endpoint) media_id_code = re.split('/', url_destination)[-2] url_destination = 'http://instagr.am/p/' + media_id_code response = consumer.embed(url_destination) media_id = response['media_id'] api = InstagramAPI(client_id=iconf.client_id, client_secret=iconf.client_secret) except: if debug: print 'Unable to find picture from link.' return 'null' try: media = api.media(media_id) return [media.user.id, media.user.username] except: if debug: print 'Unable to fetch instagram ID - most likely private user' return 'null'
def auth_request(): api = InstagramAPI(access_token=OTHER['access_token'],client_secret=CONFIG['client_secret']) target_ids = api.user_search(OTHER['target'],1) if len(target_ids) > 1: logging.error('Found mutiple users, please check username') return target_id = target_ids[0].id my_name = api.user().username logging.debug('Starting check recent media') recent_media, url = api.user_recent_media(user_id=target_id, count = 1) liked_media = [] for media in recent_media: logging.debug('Processing media %s' % media.id) users = api.media_likes(media.id) will_like = True for user in users: if user.username == my_name: will_like = False break if will_like: logging.debug('Liking media %s' % media.id) api.like_media(media.id) liked_media.append(media) else: logging.debug('Already liked media %s, aborting like' % media.id) return liked_media
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 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 main(): try: print("start api: ", access_token) api = InstagramAPI(access_token=access_token, client_secret=client_secret) print("finish api") print(api) api.user_incoming_requests() print("user_pai") """ recent_media, next_ = api.user_recent_media(user_id="userid", count=10) for media in recent_media: print(media.caption.text) """ """ l = StreamListener() auth = OAuthHandler(consumer_key, consumer_secret) auth.set_access_token(access_token, access_token_secret) stream = Stream(auth, l) stream.filter(track=["DisneyPlus", "Disney+", "Disney +", "Disney Plus", "Disney Stream", "Disney Netflix", "Disney Hulu",\ "Disney streaming service", "Disney Apple", "Disney Roku"]) """ except Exception as e: print("EXCEPTION IN MAIN FUNCTION!!!") print(e) exit(1)
def get_medias(user_id, all=False): print('get_medias user_id=%s, all=%s' % (user_id, all)) api = InstagramAPI(access_token=ACCESS_TOKEN, client_secret=CLIENT_SECRET) medias = [] # media_urls = [] more_medias, _ = api.user_recent_media() # media_urls.extend(get_media_urls(more_medias)) if more_medias: medias.extend(more_medias) loop = 100 if all else 1 while more_medias and loop > 0: try: print('get_medias max_id=%s' % more_medias[-1].id) more_medias, _ = api.user_recent_media(max_id=more_medias[-1].id) if not more_medias: print('get_medias no more data, break') break print('get_medias new medias count: %s' % len(more_medias)) medias.extend(more_medias) # media_urls.extend(get_media_urls(more_medias)) time.sleep(3) except Exception, e: print("error:%s on get_medias:%s" % (e, loop)) time.sleep(10) loop -= 1
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 get_redirect_url(self, *args, **kwargs): code = self.request.GET.get("code") settings.use_editable() site = Site.objects.get_current() conf = { "redirect_uri": "http://{0}{1}".format(site.domain, reverse('instagram_oauth')), "client_id": settings.INSTAGRAM_CLIENT_ID, "client_secret": settings.INSTAGRAM_CLIENT_SECRET, } unauthorized_api = InstagramAPI(**conf) logger.debug(unauthorized_api) access_token = unauthorized_api.exchange_code_for_access_token(code) try: instagram = Instagram.objects.all()[0] instagram.access_token = access_token[0] instagram.user_id = int(access_token[1]['id']) instagram.full_name = access_token[1]['full_name'] instagram.username = access_token[1]['username'] instagram.save() except IndexError: Instagram.objects.create(access_token=access_token[0], user_id=int(access_token[1]['id']), full_name=access_token[1]['full_name'], username=access_token[1]['username']) return "/admin/"
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_ajax(self, request, *args, **kwargs): try: instagram = Instagram.objects.all()[0] api = InstagramAPI(access_token=instagram.access_token) media, discard = api.user_recent_media(user_id=instagram.user_id, count=24) json_dict = { "thumbnails": [{ "url": n.images.get("thumbnail").url, "width": n.images.get("thumbnail").width, "height": n.images.get("thumbnail").height, } for n in media], "low_resolution": [{ "url": n.images.get("low_resolution").url, "width": n.images.get("low_resolution").width, "height": n.images.get("low_resolution").height, } for n in media], "standard_resolution": [{ "url": n.images.get("standard_resolution").url, "width": n.images.get("standard_resolution").width, "height": n.images.get("standard_resolution").height, } for n in media], } except IndexError: json_dict = {"media": []} return self.render_json_response(json_dict)
def index(): # if instagram info is in session variables, then display user photos if 'instagram_access_token' in session and 'instagram_user' in session: userAPI = InstagramAPI(access_token=session['instagram_access_token']) follows = [] follows, next_ = userAPI.user_follows(user_id=session['instagram_user'].get('id')) while next_: more_follows, next_ = userAPI.user_follows(with_next_url=next_) follows.extend(more_follows) followed_by = [] followed_by, _ = userAPI.user_followed_by(user_id=session['instagram_user'].get('id')) while _: more_followed_by, _ = api.user_followed_by(with_next_url=_) followed_by.extend(more_followed_by) followers_names=list(map(str,follows)) followed_by_names=list(map(str,followed_by)) unique_people=list(set(followers_names) - set(followed_by_names)) clean_list=[i.replace("User: "******"") for i in unique_people] result=[i for i in follows if i.username in clean_list] resultattr = {} for i in result: resultattr[i.username]=i.profile_picture return render_template('result.html', result = resultattr) else: return render_template('index.html')
def channelback(request): if request.method == 'POST': metadata = request.POST.get('metadata', '') newState = request.POST.get('state', '') message = request.POST.get('message', '') parentId = request.POST.get('parent_id', '') recipientId = request.POST.get('recipient_id', '') metaJson = json.loads(metadata) client_id = metaJson['client_id'] client_secret = metaJson['client_secret'] access_token = metaJson['token'] name = metaJson['name'] mediaIdSplit = parentId.split('-') media_id = mediaIdSplit[2] api = InstagramAPI(access_token=access_token, client_secret=client_secret) comment = api.create_media_comment(media_id, message) mediaComments = api.media_comments(media_id) commentId = '' for mediaComment in mediaComments: if mediaComment.text == message: commentId = mediaComment.id newCommentId = "cmnt-" + commentId + '-' + media_id print(newCommentId) response_data = {} response_data['external_id'] = newCommentId response_data['allow_channelback'] = True return HttpResponse(json.dumps(response_data, ensure_ascii=False), content_type="application/json;charset=UTF-8")