def ageOffSubscriptions(p, collHandle, ageOff, protectedSubs): ''' Deletes subscriptions from the Instagram server based on the age and protection level in the subs collection. If protect=True, then it must be manually deleted''' out = [] # Get the client and secret keys api = InstagramAPI(client_id=p.client, client_secret=p.secret) # Get the expired non-protected subscriptions subs, ids = getExpiredSubs(collHandle, ageOff, protectedSubs) # Delete the subscriptions from the instagram server for sub in subs: print sub deleted = api.delete_subscriptions(id=int(sub)) print deleted out.append(deleted) if deleted['meta']['code'] != 200: print 'Failed to delete subscription %s' % (sub) # Delete the nextUrl object files (kept in the config directory) for objId in ids: f = os.path.join(os.path.dirname(p.configFile), objId) try: os.remove(f) except: print 'Failed to delete the subscription next URL file: \n %s\n' % ( f) return out
def getMyId(self): try: api = InstagramAPI(access_token=self._accessToken) self.myId = api.user().id except: return None return self.myId
def get_api(self): if not hasattr(self, '_api'): self._api = InstagramAPI( client_id=settings.CONNECTED_ACCOUNTS_INSTAGRAM_CONSUMER_KEY, client_secret=settings.CONNECTED_ACCOUNTS_INSTAGRAM_CONSUMER_SECRET, access_token=self.account.get_token()) return self._api
def isfollow(uid, api=None): if not api: api = InstagramAPI(access_token=session.get('access_token', '')) data = api.user_relationship(user_id=uid) if data.outgoing_status == 'follows': return True return False
def get(self): if has_login(): return redirect(url_for('views.home')) redirect_url = url_for('views.home') code = request.args.get('code', '') redirect_uri = INSTAGRAM_REDIRECT_URI if request.args.get('uri', ''): redirect_url = request.args.get('uri') redirect_uri += '?uri=' + redirect_url api = InstagramAPI(client_id=INSTAGRAM_CLIENT_ID, client_secret=INSTAGRAM_CLIENT_SECRET, redirect_uri=redirect_uri) try: access_token = api.exchange_code_for_access_token(code) print access_token except: return InternalServerError(u'InternalServerError') user = (User.query .filter_by(id=access_token[1]['id']).first()) if user: user.update(access_token=access_token[0], name=access_token[1]['username'], avatar=access_token[1]['profile_picture']) else: user = User.create(id=access_token[1]['id'], name=access_token[1]['username'], avatar=access_token[1]['profile_picture'], access_token=access_token[0]) redirect_url = url_for('views.welcome') session.permanent = True session['uid'] = user.id session['username'] = user.name session['access_token'] = user.access_token return redirect(redirect_url)
def main(configFile=None): ''' Deletes all subscriptions from the Instagram server. Typically called on a new dotcloud push just to make sure its all clear.''' print "----------->", configFile # Get the config information into a single object p = getConfigParameters(configFile) # Get the client and secret keys api = InstagramAPI(client_id=p.client, client_secret=p.secret) # Get all current subs subs = api.list_subscriptions() # For each active sub, delete it if subs['meta']['code'] == 200: for sub in subs['data']: if sub['type'] == 'subscription': deleted = api.delete_subscriptions(id=int(sub['id'])) # Final check - make sure they're definitely all gone subs = api.list_subscriptions() if len(subs['data']) == 0: success = True else: success = False else: success = False
def get(self, id): api = InstagramAPI(access_token=request.access_token) media, likes = self._get_meida(id, api) errors = self._get_errors(media, likes, id) if errors: return errors uid = media.user.id is_follow = False if request.uid: try: is_follow = isfollow(uid, api) except InstagramAPIError: return InternalServerError('Internal server error') media_user = self._get_media_user(uid, api) if not media_user: return InternalServerError('Internal server error') is_star = False for i in likes: if request.uid and request.uid == i.id: is_star = True return render_template('media.html', media=media, isfollow=is_follow, media_user=media_user, likes=likes[:5], is_star=is_star)
def list(tag): api = InstagramAPI(client_id=CLIENT_ID) items, next = api.tag_recent_media(count=12, tag_name=tag) if is_nonmobile(request.environ): return render_template("_item.html", items=items) else: return render_template("_mitem.html", items=items)
def get_posts(user_social_auth, last_updated_time): api = InstagramAPI( access_token=user_social_auth.extra_data['access_token']) formatted_time = helper.datetime_to_timestamp( last_updated_time) if last_updated_time else None recent_media, next_ = api.user_recent_media( user_id=user_social_auth.uid, min_timestamp=formatted_time) return recent_media
def get_api(self, request): if not hasattr(self, '_api'): rel_to = self.model._meta.get_field('account').rel.to connected_account = get_object_or_404(rel_to, pk=request.GET.get('account')) self._api = InstagramAPI( client_id=settings.CONNECTED_ACCOUNTS_INSTAGRAM_CONSUMER_KEY, client_secret=settings.CONNECTED_ACCOUNTS_INSTAGRAM_CONSUMER_SECRET, access_token=connected_account.get_token()) return self._api
def get_user(uid, access_token): try: api = InstagramAPI(access_token=access_token) user = api.user(uid) return user except InstagramAPIError, e: if e.error_type in ['APINotAllowedError-you', 'APINotFoundError-this']: delete_worker(uid) print e.error_type return e
def _authenticate(self, user): try: social_auth = user.social_auth.get(provider='instagram') token_key = social_auth.extra_data['access_token'] except (ObjectDoesNotExist, KeyError): raise CredentialsNotFound('instagram', user) return InstagramAPI( client_secret=settings.SOCIAL_AUTH_INSTAGRAM_SECRET, access_token=token_key)
def isTokenValid(self): try: api = InstagramAPI(access_token=self._accessToken) api.user() except InstagramAPIError as e: return ErrorCode.E_INVALID_TOKEN except: self._logger.exception('InstaBase::isTokenValid() exception') return ErrorCode.E_FAILED else: return ErrorCode.S_OK
def get(self): if has_login(): return redirect(url_for('views.welcome')) redirect_uri = INSTAGRAM_REDIRECT_URI if request.args.get('uri', ''): redirect_uri += '?uri=' + request.args.get('uri') api = InstagramAPI(client_id=INSTAGRAM_CLIENT_ID, client_secret=INSTAGRAM_CLIENT_SECRET, redirect_uri=redirect_uri) try: redirect_uri = api.get_authorize_login_url(scope=INSTAGRAM_SCOPE) except InstagramAPIError: return InternalServerError(u'Server Error') return redirect(redirect_uri)
def get_instub_feed(access_token, min_id=None): print min_id try: api = InstagramAPI(access_token=access_token) medias_list = [] next_ = True while next_: next_url = None if next_ is True else next_ medias, next_ = api.user_media_feed(with_next_url=next_url, min_id=min_id) medias_list.extend(medias) return medias_list except InstagramAPIError, e: if e.error_type in ['APINotAllowedError-you', 'APINotFoundError-this']: pass return []
def __init__(self, token, ip, secret, tag_list, log=None, pause=None): """ :param token: Access_token of account :param ip: Machines IP :param secret: Client secret :param tag_list: List of hastags to interact with :param log: Where to save info. Default "instabot.log" :param pause: Time to wait before interacting again. Default 1 second" """ super(InstaBot, self).__init__() self.api = InstagramAPI(access_token=token, client_ips=ip, client_secret=secret) self.tag_list = tag_list self.log = "instabot.log" if log is None else log self.pause = 1 if pause is None else pause self.db = DB() self.__count = 0
class MuslimahGalau(Instapy): instagram = InstagramAPI(access_token=ACCESS_TOKEN, client_secret=CLIENT_SECRET) insta_post = InstagramSession( username=USERNAME, password=PASSWORD, guid='3efc0996-85bd-11e5-857d-74de2b6b05c3', device_id='android-3efc0996-85bd-11e5-857d-74de2b6b05c3', user_agent= 'Instagram 4.2.2 Android (10/1.5.2; 120; 480x800; samsung; GT-N7000; GT-N7000; smdkc210; en_US)' ) user_followed = USERS tags = [ '#muslimahgalau', '#muslimah', '#galau', '#akhowat', '#akhwat', '#tausiyah' ] IMAGES_PATH = '/home/ramdani/projects/auto-repost/muslimah_images/'
def get_medias(uid, access_token, min_id=None): print uid, access_token, min_id try: api = InstagramAPI(access_token=access_token) medias_list = [] next_ = True while next_: next_url = None if next_ is True else next_ medias, next_ = api.user_recent_media(user_id=uid, with_next_url=next_url, min_id=min_id) medias_list.extend(medias) print len(medias_list) return medias_list except InstagramAPIError, e: if e.error_type in ['APINotAllowedError-you', 'APINotFoundError-this']: delete_worker(uid) print e.error_type return e
def get(self, uid=None): next_url = request.args.get('next_url', None) if next_url and 'instagram' not in next_url: next_url = signer.loads(next_url) api = InstagramAPI(access_token=request.access_token) user = gevent.spawn(wrap_errors(InstagramAPIError, api.user), user_id=uid) feeds = gevent.spawn(wrap_errors(InstagramAPIError, api.user_recent_media), user_id=uid, with_next_url=next_url) if request.uid: isfollows = spawn(isfollow, uid, api) else: isfollows = spawn(lambda x: False, uid) gevent.joinall([user, feeds, isfollows]) user, feeds, isfollows = user.get(), feeds.get(), isfollows.get() errors = [ e for e in (user, feeds, isfollows) if isinstance(e, InstagramAPIError) ] if errors: if any([e.error_type == 'APINotAllowedError' for e in errors]): return render_template('profile-noauth.html', uid=uid) if any([e.error_type == 'APINotFoundError' for e in errors]): return NotFound(u'User Not Found') return InternalServerError('Internal Server Error') next_url = feeds[1] if feeds else None next_url = signer.dumps(next_url) if next_url else next_url feeds = feeds[0] if feeds else [] isme = False if request.uid and uid == request.uid: isme = True return render_template('profile.html', user=user, feeds=feeds, isme=isme, isfollow=isfollows, next_url=next_url)
def get(self, name): next_url = request.args.get('next_url', None) api = InstagramAPI(access_token=request.access_token) tag = api.tag(name) media = api.tag_recent_media(tag_name=name, with_next_url=next_url) tag = gevent.spawn(api.tag, name) media = gevent.spawn(api.tag_recent_media, tag_name=name, with_next_url=next_url) gevent.joinall([tag, media]) try: tag, media = tag.get(), media.get() except InstagramAPIError: return InternalServerError('Internal server error') next_url = media[1] media = media[0] pager = Pager(tag.media_count) return render_template('tag.html', tag=tag, pager=pager, media=media, next_url=next_url)
def _get_users(self, uid, user_type='followed'): next_url = request.args.get('next_url', None) if next_url and 'instagram' not in next_url: next_url = signer.loads(next_url) api = InstagramAPI(access_token=request.access_token) user = spawn(api.user, uid) if user_type == 'following': users = spawn(api.user_follows, uid, with_next_url=next_url) else: users = spawn(api.user_followed_by, uid, with_next_url=next_url) isfollows = False if request.uid: isfollows = spawn(isfollow, uid, api) else: isfollows = spawn(lambda x: False, uid) gevent.joinall([user, users, isfollows]) user, users, isfollows = user.get(), users.get(), isfollows.get() errors = get_errors(user, users, isfollows) if errors: return InternalServerError('Internal Server Error') next_url = users[1] next_url = signer.dumps(next_url) if next_url else next_url users = users[0] isme = False if request.uid and uid == request.uid: isme = True context = { 'user': user, 'users': users, 'next_url': next_url, 'isfollows': isfollows, 'isme': isme, } return context
def getData(self, since=None, until=None): """ Get data from Instagram feed In: since -- The start time to get data given None means current time or given python's datetime instance as input until -- The end time to get date given None means yesterday or given python's datetime instance as input Example: (Please note that the direction to retrieve data is backward) Now ---> 2012/04/01 ---> 2012/01/01 You can specify since=None and until=<datetime of 2012/01/01> or since=<datetime of 2012/04/01> until=<datetime of 2012/01/01> Out: Return a python dict object { 'data': { # List of data 'id': { 'id': 'postId', 'message': 'Text', 'photos': [ '/path/to/file' ], 'createdTime': <datetime object>, 'place': { # *optional* 'id': 'locationId', 'name': 'locationName', 'latitude': nnn.nnn, 'longitude' mmm.mmm } }, ... }, 'count': 30, # count in data dic 'retCode': ErrorCode.S_OK, # returned code which is instance of ErrorCode } """ retDict = { 'retCode': ErrorCode.E_FAILED, 'count': 0, 'data': {}, } if not until: until = datetime.now() - timedelta(1) tokenValidRet = self.isTokenValid() if ErrorCode.IS_FAILED(tokenValidRet): retDict['retCode'] = tokenValidRet return retDict if not self.myId: return retDict sinceTimestamp = self._datetime2Timestamp(since) + 1 if since else None untilTimestamp = self._datetime2Timestamp(until) - 1 if until else None api = InstagramAPI(access_token=self._accessToken) for media in api.user_recent_media(max_pages=999, min_timestamp=untilTimestamp, max_timestamp=sinceTimestamp): if not media: break for data in media: data = self._transformFormat(data) self._dumpData(data) retDict['data'][data['id']] = data retDict['count'] = len(retDict['data']) retDict['retCode'] = ErrorCode.S_OK return retDict
def init_instagram(access_token=None, redirect_url=None): return InstagramAPI(client_id=config.Instagram.client_id, client_secret=config.Instagram.client_secret, access_token=access_token, redirect_uri=redirect_url)
import matplotlib.patches as mpatches import mpld3 import pandas as pd # Sets how many post to get post_count = 40 # Creates a threshold for neutral post neutral_min = 0.04 neutral_max = 0.215 min_subjectivity = 0.3 # Sets hashtag to be analyze (do no include the hashtag symbol) hash_tag = 'cats' # Set up Instagram API client_id = '' # Replace with your key client_secret = '' # Replace with your key api = InstagramAPI(client_id=client_id, client_secret=client_secret) def get_ids(): # Get all ids for all post ids, next = api.tag_recent_media(tag_name=hash_tag, count=post_count) temp, max_tag = next.split('max_tag_id=') max_tag = str(max_tag) while next and len(ids) < post_count: more_ids, next = api.tag_recent_media(tag_name=hash_tag, count=max_tag) temp, max_tag = next.split('max_tag_id=') max_tag = str(max_tag) for id in more_ids: if len(ids) < post_count: ids.append(id)
from __future__ import print_function from __future__ import division from instagram import client, subscriptions, InstagramAPI import sys from datetime import date, timedelta import json import time import datetime import shutil import operator from pylab import * #access_token='1529897738.f4dfaeb.53403a45baed421ca216921b2f136c97' #access_token='1529897738.2d6fe64.87556684de0d4ce1aa6afbf423a8cada' access_token = '1546646729.2d6fe64.91d6953b286d467ea889016903648d96' api = InstagramAPI(access_token=access_token) print_all_users = 0 def is_empty(any_structure): if any_structure: #print('Structure is not empty.') return False else: #print('Structure is empty.') return True #open source and results files print("*** Remaining API Calls = %s/%s" % (api.x_ratelimit_remaining, api.x_ratelimit))
from instagram import InstagramAPI api = InstagramAPI("login", "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!")
def mlist(tag): app.logger.debug("tag=" + tag) api = InstagramAPI(client_id=CLIENT_ID) items, next = api.tag_recent_media(count=12, tag_name=tag) return render_template("_mitem.html", items=items)
bridge.twitter_last_id = new_tweets[0].id bridge.updated = datetime.now() new_tweets.reverse() # # Instagram # new_instas = [] if bridge.instagram_access_code: l.debug(f"-- INSTAGRAM: {bridge.instagram_handle} --") api = InstagramAPI(access_token=bridge.instagram_access_code, client_secret=c.INSTAGRAM_SECRET) try: recent_media, _ = api.user_recent_media(user_id=bridge.instagram_account_id) except Exception as e: l.error(e) continue for media in recent_media: ts = datetime_to_timestamp(media.created_time) if ts > bridge.instagram_last_id: new_instas.append(media) if c.SEND and len(new_instas) != 0:
def item(id): api = InstagramAPI(client_id=CLIENT_ID) item = api.media(media_id=id) return render_template("_mimage.html", item=item)
from instagram import InstagramAPI import io api = InstagramAPI(client_id='CLIENT_ID', client_secret='CLIENT_SECRET') log = io.open(r'InstagramFolder/instagram.txt', 'wb') hashtags = ['pizza', 'cheese'] #add as many search terms you need here lat = 38.907192 long = -77.036871 dist = 1000 #in meters # Search location by long+lat def search_by_lat_long(latitude, longitude, distance): media_search = api.media_search(lat=latitude, lng=longitude, distance=distance) for media in media_search: log.write(u'\n--&&&***--') log.write(media.user.username + ' ') if (media.caption): log.write(media.caption.text.encode('utf8') + '---') if (media.location): log.write(media.location.name + ' ') if (media.images): log.write(media.images['standard_resolution'].url) elif (media.videos): log.write(media.videos['standard_resolution'].url)