class InstagramAuth(OAuthRequestHandler): scope = [ 'basic', 'comments', 'likes', 'relationships', ] def initialize(self): super(InstagramAuth, self).setProvider("instagram") consumer_key = self.application.settings['instagram_oauth']['key'] consumer_secret = \ self.application.settings['instagram_oauth']['secret'] redir_uri = "{0}/auth/instagram".format( self.application.settings['base_url']) self.api = InstagramAPI( client_id=consumer_key, client_secret=consumer_secret, redirect_uri=redir_uri, ) def startFlow(self): self.redirect(self.api.get_authorize_login_url(scope=self.scope)) @gen.coroutine def handleAuthCallBack(self, code, user_id): access_info = self.api.exchange_code_for_access_token(code) # Confirmation & Saving token yield save_token(provider="instagram", user_id=user_id, token_data=access_info)
def getToken(): if not os.path.exists('accessToken.txt'): print("The first time you run this program, it will need to obtain access to Instagram via") print("a token generated from your account. This token will only require basic (read-only)") print("access to your account in order to download images. Afterwards, the token will be") print("stored in \'accessToken.txt\'. If you ever have problems with this script, delete") print("\'accessToken.txt\' and run this script again to regenerate the token.") client_id = 'd051ace450314ccd8d86fdbff2410a87' client_secret = '91c43e9262494f4c82c887a88b21068c' redirect_uri = 'http://localhost:8515/oauth_callback' scope = ["basic"] api = InstagramAPI(client_id=client_id, client_secret=client_secret, redirect_uri=redirect_uri) redirect_uri = api.get_authorize_login_url(scope = scope) print("Python will now attempt to open the following URL in a web browser:") print(redirect_uri) print("When it loads, it will go to an invalid URL that looks like") print("http://localhost:8515/oauth_callback?code=XXXXXXXXXXXXXXXXXXX") print('Copy and paste the code from the address bar (the XXXs in the above example) below.') webbrowser.open(redirect_uri) print("Paste in code in query string after redirect: "), code = (str(raw_input().strip())) access_token = api.exchange_code_for_access_token(code) print ("access token: " ) print (access_token) pickle.dump( access_token, open( "accessToken.txt", "wb" ) )
class client_packet: def __init__(self, client_id, client_secret, redirect_uri, begin_user_id): self.client_id = client_id self.client_secret = client_secret self.redirect_uri = redirect_uri self.begin_user_id = begin_user_id print('creating new client...') def Access_token(self, flag): if flag: scope = [] self.api = InstagramAPI(client_id=self.client_id, client_secret=self.client_secret, redirect_uri=self.redirect_uri) redirect_uri = self.api.get_authorize_login_url(scope=scope) print("Visit this page and authorize access in your browser:\n", redirect_uri) code = input("Paste in code in query string after redirect: ").strip() print('client_id: ' + self.api.client_id) print('client_secret: ' + self.api.client_secret) self.access_token = self.api.exchange_code_for_access_token(code) print(self.access_token) else: self.access_token = 'Insert Your actual Client Access token to not repeath this again and again' return self.access_token
class InstagramAuth(OAuthRequestHandler): scope = [ 'basic', 'comments', 'likes', 'relationships', ] def initialize(self): super(InstagramAuth, self).setProvider("instagram") consumer_key = self.application.settings['instagram_oauth']['key'] consumer_secret = \ self.application.settings['instagram_oauth']['secret'] redir_uri = "{0}/auth/instagram".format( self.application.settings['base_url']) self.api = InstagramAPI( client_id=consumer_key, client_secret=consumer_secret, redirect_uri=redir_uri, ) def startFlow(self): self.redirect(self.api.get_authorize_login_url(scope=self.scope)) @gen.coroutine def handleAuthCallBack(self, code, user_id): access_info = self.api.exchange_code_for_access_token(code) # Confirmation & Saving token yield save_token( provider="instagram", user_id = user_id, token_data=access_info )
def get_token(creds, scope=['basic', 'comments', 'public_content']): # Fix Python 2.x. try: import __builtin__ input = getattr(__builtin__, 'raw_input') except (ImportError, AttributeError): pass client_id = creds['client_id'] client_secret = creds['client_secret'] redirect_uri = creds['redirect_uri'] print 'Connecting to InstagramAPI' api = InstagramAPI(client_id=client_id, client_secret=client_secret, redirect_uri=redirect_uri) print 'Obtaining auth url' redirect_uri = api.get_authorize_login_url(scope=scope) webbrowser.open_new_tab(redirect_uri) code = (str(input( "Login in, then paste in code in query string after redirect: " ).strip())) access_token = api.exchange_code_for_access_token(code) return access_token[0]
def runConfigWizard(self): try: api = InstagramAPI( client_id=self.options_string['hidden_client_id'], client_secret=self.options_string['hidden_client_secret'], redirect_uri=self.options_string['redirect_uri']) url = api.get_authorize_login_url() self.wizard.setWindowTitle('Instagram plugin configuration wizard') page1 = QWizardPage() layout1 = QVBoxLayout() txtArea = QLabel() txtArea.setText( 'Please copy the following link to your browser window. \n ' + 'Once you authenticate with Instagram you will be redirected to ' + 'www.geocreepy.com and get your token. Copy the token to the input field below:' ) urlArea = QLineEdit() urlArea.setObjectName('urlArea') urlArea.setText(url) inputLink = QLineEdit() inputLink.setObjectName('inputLink') labelLink = QLabel('Your token value:') openInBrowserButton = QPushButton('Open in browser') openInBrowserButton.clicked.connect( functools.partial(self.openLinkInBrowser, url)) layout1.addWidget(txtArea) layout1.addWidget(urlArea) layout1.addWidget(openInBrowserButton) layout1.addWidget(labelLink) layout1.addWidget(inputLink) page1.setLayout(layout1) self.wizard.addPage(page1) self.wizard.resize(600, 400) if self.wizard.exec_(): c = str(inputLink.text()) if c: try: access_token = api.exchange_code_for_access_token( code=c) self.options_string[ 'hidden_access_token'] = access_token[0] self.saveConfiguration(self.config) except Exception as err: logger.error(err) self.showWarning( 'Error Getting Access Token', 'Please verify that the link you pasted was correct. ' 'Try running the wizard again.') else: self.showWarning( 'Error Getting Access Token', 'Please verify that the link you pasted was correct. Try running the wizard again.' ) except Exception as err: logger.error(err) self.showWarning('Error', 'Error was {0}'.format(err))
def get_access_token_url(self): api = InstagramAPI(client_id=self.client_id, client_secret=self.client_secret, redirect_uri=self.redirect_uri) redirect_uri = api.get_authorize_login_url(scope=self.scope) # if(redirect_uri): # response = urllib2.urlopen(redirect_uri).read() return redirect_uri
def instagram_auth(): scope = ['basic', 'likes', 'comments', 'relationships'] api = InstagramAPI(client_id=settings.CLIENT_ID, client_secret=settings.CLIENT_SECRET, redirect_uri=settings.HOST + '/' + BLUEPRINT_NAME + INSTAGRAM_REDIRECT_PATH) return redirect(api.get_authorize_login_url(scope=scope), code=302)
def index(request): api = InstagramAPI(client_id=CLIENT_ID, client_secret=CLIENT_SECRET, redirect_uri="http://bestjae.com/api/getToken") # api = InstagramAPI(client_id=CLIENT_ID, client_secret=CLIENT_SECRET, redirect_uri="http://localhost:8000/api/getToken") redirect_uri = api.get_authorize_login_url(scope=["basic", "public_content", "follower_list"]) #return HttpResponse("<a href=" + redirect_uri + ">Instagram</a>") #request.session['redirect'] = redirect_uri context = {'re' : redirect_uri} #return render(request, "index.html", context) return TemplateResponse(request, "index.html", context)
def _get_access_token(): api = InstagramAPI(client_id=client_id, client_secret=client_secret, redirect_uri=REDIRECT_URL) redirect_uri = api.get_authorize_login_url(scope="") print("visit this page to get access token", redirect_uri) code = input("paste in key after redirect: ").strip() access_token, user_detail = api.exchange_code_for_access_token(code=code) return access_token
def instagram_auth(): scope = ['basic', 'likes', 'comments', 'relationships'] api = InstagramAPI( client_id=settings.CLIENT_ID, client_secret=settings.CLIENT_SECRET, redirect_uri=settings.HOST + '/' + BLUEPRINT_NAME + INSTAGRAM_REDIRECT_PATH ) return redirect(api.get_authorize_login_url(scope=scope), code=302)
def get_auth(): unauth_api = InstagramAPI(**CONFIG) redirect_uri = unauth_api.get_authorize_login_url(scope = OTHER['scope']) print "Visit this page and authorize access in your browser:\n", redirect_uri code = raw_input('Please type in the access code you got\n') OTHER['access_token'], me = unauth_api.exchange_code_for_access_token(code) with open('config', 'w') as cf: config_parser.set('Access Token', 'access_token', OTHER['access_token']) config_parser.write(cf)
def _get_access_token(): api = InstagramAPI(client_id=client_id, client_secret=client_secret, redirect_uri=REDIRECT_URL) redirect_uri = api.get_authorize_login_url(scope=SCOPE) print("Visit this page in browser and authorize access:\n", redirect_uri) code = input("Paste in code in query string after redirect: ").strip() access_token, user_info = api.exchange_code_for_access_token(code) return access_token
def instagram_activate(): client_id = app.config['INSTAGRAM_CLIENT_ID'] client_secret = app.config['INSTAGRAM_SECRET'] redirect_uri = url_for('instagram_oauthorized', _external=True) # app.logger.info(redirect_uri) scope = ["basic"] api = InstagramAPI(client_id=client_id, client_secret=client_secret, redirect_uri=redirect_uri) redirect_uri = api.get_authorize_login_url(scope=scope) return redirect(redirect_uri)
def runConfigWizard(self): try: api = InstagramAPI(client_id=self.options_string['hidden_client_id'], client_secret=self.options_string['hidden_client_secret'], redirect_uri=self.options_string['redirect_uri']) url = api.get_authorize_login_url() self.wizard.setWindowTitle('Instagram plugin configuration wizard') page1 = QWizardPage() layout1 = QVBoxLayout() txtArea = QLabel() txtArea.setText('Please copy the following link to your browser window. \n ' + 'Once you authenticate with Instagram you will be redirected to ' + 'www.geocreepy.com and get your token. Copy the token to the input field below:') urlArea = QLineEdit() urlArea.setObjectName('urlArea') urlArea.setText(url) inputLink = QLineEdit() inputLink.setObjectName('inputLink') labelLink = QLabel('Your token value:') openInBrowserButton = QPushButton('Open in browser') openInBrowserButton.clicked.connect(functools.partial(self.openLinkInBrowser, url)) layout1.addWidget(txtArea) layout1.addWidget(urlArea) layout1.addWidget(openInBrowserButton) layout1.addWidget(labelLink) layout1.addWidget(inputLink) page1.setLayout(layout1) self.wizard.addPage(page1) self.wizard.resize(600, 400) if self.wizard.exec_(): c = str(inputLink.text()) if c: try: access_token = api.exchange_code_for_access_token(code=c) self.options_string['hidden_access_token'] = access_token[0] self.saveConfiguration(self.config) except Exception, err: logger.error(err) self.showWarning('Error Getting Access Token', 'Please verify that the link you pasted was correct. ' 'Try running the wizard again.') else: self.showWarning('Error Getting Access Token', 'Please verify that the link you pasted was correct. Try running the wizard again.') except Exception, err: logger.error(err) self.showWarning('Error', 'Error was {0}'.format(err))
def auth(request): api = InstagramAPI(client_id=settings.CLIENT_ID, client_secret=settings.CLIENT_SECRET, redirect_uri=settings.REDIRECT_URI) output = {} if request.GET.get('code'): code = request.GET.get('code') access_token, user = api.exchange_code_for_access_token(code) request.session['token'] = access_token if not request.session.get('token'): redirect_uri = api.get_authorize_login_url(scope = settings.SCOPE) if not request.GET.get('code'): return redirect(redirect_uri) return HttpResponse(request.session['token'])
def instagram_activate(): client_id = app.config['INSTAGRAM_CLIENT_ID'] client_secret = app.config['INSTAGRAM_SECRET'] redirect_uri = url_for('instagram_oauthorized', _external=True) # app.logger.info(redirect_uri) scope = ["basic"] api = InstagramAPI(client_id=client_id, client_secret=client_secret, redirect_uri=redirect_uri) try: redirect_uri = api.get_authorize_login_url(scope=scope) except ServerNotFoundError as e: flash(f"There was a problem connecting to Instagram. Please try again") return redirect(url_for('index')) else: return redirect(redirect_uri)
def get_auth_tokens(stdout): stdout.write('Please enter the following Instagram client details\n\n') print('lol' + settings.INSTAGRAM_CLIENT_ID) if settings.INSTAGRAM_CLIENT_ID == '': settings.INSTAGRAM_CLIENT_ID = input('Client ID: ').strip() if settings.INSTAGRAM_CLIENT_SECRET == '': settings.INSTAGRAM_CLIENT_SECRET = input('Client Secret: ').strip() if settings.INSTAGRAM_REDIRECT_URI == '': settings.INSTAGRAM_REDIRECT_URI = input('Redirect URI: ').strip() scope = ['basic', 'public_content', 'likes'] api = InstagramAPI(client_id=settings.INSTAGRAM_CLIENT_ID, client_secret=settings.INSTAGRAM_CLIENT_SECRET, redirect_uri=settings.INSTAGRAM_REDIRECT_URI) redirect_uri = api.get_authorize_login_url(scope=scope) stdout.write('\nVisit this page and authorize access in your browser:\n\n%s\n\n' % redirect_uri) code = input('Paste in code in query string after redirect: ').strip() access_token = api.exchange_code_for_access_token(code) stdout.write('Access token:\n\n%s\n\n' % (access_token,))
def get_auth_tokens(stdout): stdout.write('Please enter the following Instagram client details\n\n') client_id = input('Client ID: ').strip() client_secret = input('Client Secret: ').strip() redirect_uri = input('Redirect URI: ').strip() raw_scope = input( 'Requested scope (separated by spaces, blank for just basic read): ').strip() scope = raw_scope.split(' ') # For basic, API seems to need to be set explicitly if not scope or scope == ['']: scope = ['basic'] api = InstagramAPI(client_id=client_id, client_secret=client_secret, redirect_uri=redirect_uri) redirect_uri = api.get_authorize_login_url(scope=scope) stdout.write('\nVisit this page and authorize access in your browser:\n\n%s\n\n' % redirect_uri) code = input('Paste in code in query string after redirect: ').strip() access_token = api.exchange_code_for_access_token(code) stdout.write('Access token:\n\n%s\n\n' % (access_token,))
class client_packet : def __init__(self, client_id, client_secret, redirect_uri, begin_user_id): self.client_id = client_id self.client_secret = client_secret self.redirect_uri = redirect_uri self.begin_user_id = begin_user_id def access_token(self,flag): if flag: scope = [] self.api = InstagramAPI(client_id = self.client_id, client_secret = self.client_secret, redirect_uri = self.redirect_uri) redirect_uri = self.api.get_authorize_login_url(scope = scope) print "Visit this page and authorize access in your browser:\n", redirect_uri code = raw_input("Paste in code in query string after redirect: ").strip() self.access_token = self.api.exchange_code_for_access_token(code) print self.access_token else: self.access_token = 'Insert Your actual Client Access token to not repeath this again and again' return self.access_token
class Instagram: def __init__(self): self.api = InstagramAPI(client_id=CLIENT_ID, client_secret=CLIENT_SECRET, redirect_uri=REDIRECT_URI) def set_access_token(self, access_token): self.api = InstagramAPI(access_token=access_token) def media_popular(self, **params): popular = memcache.get("popular_feed") if not popular: popular = self.api.media_popular(count=params["count"], max_id=params["max_id"]) memcache.add("popular_feed", popular, 300) return popular def user_media_feed(self, **params): user_id = params["user_id"] max_id = params["max_id"] count = params["count"] feed = memcache.get("user_media_feed_%s_%s" % (user_id, max_id)) if not feed: feed = self.api.user_media_feed(count=count, max_id=max_id) memcache.add("user_media_feed_%s_%s" % (user_id, max_id), feed, 300) return feed def user_liked_feed(self, **params): user_id = params["user_id"] max_id = params["max_id"] count = params["count"] feed = memcache.get("user_liked_feed_%s_%s" % (user_id, max_id)) if not feed: feed = self.api.user_liked_feed(count=count, max_like_id=max_id) memcache.add("user_liked_feed_%s_%s" % (user_id, max_id), feed, 300) return feed def user(self, user_id): user = memcache.get("user_%s" % (user_id)) if not user: user = self.api.user(user_id) user["full_name"] = escape(user["full_name"].encode("utf-8")) user["full_name"] = self._convert_emoji(user["full_name"]) memcache.add("user_%s" % (user_id), user, 300) return user def media(self, media_id): media = memcache.get("media_%s" % media_id) if not media: media = self.api.media(media_id) media.user["full_name"] = escape(media.user["full_name"].encode("utf-8")) media.user["full_name"] = self._convert_emoji(media.user["full_name"]) if media.caption: media.caption["text_original"] = media.caption["text"] media.caption["text"] = escape(media.caption["text"].encode("utf-8")) media.caption["text"] = self._convert_emoji(media.caption["text"]) media.caption["text"] = self._convert_tag_to_link(media.caption["text"]) memcache.add("media_%s" % media_id, media, 300) return media def media_comments(self, media_id): comments = memcache.get("media_comments_%s" % (media_id)) if not comments: converter = emoji.factory("softbank", "utf-8") converter.prefix = '<span class="emoji emoji_' converter.suffix = '"></span>' comments = self.api.media_comments(media_id) for comment in comments: comment["text"] = escape(comment["text"].encode("utf-8")) comment["text"] = self._convert_emoji(comment["text"]) comment["text"] = self._convert_tag_to_link(comment["text"]) memcache.add("media_comments_%s" % (media_id), comments, 300) return comments def media_likes(self, media_id): likes = memcache.get("media_likes_%s" % (media_id)) if not likes: likes = self.api.media_likes(media_id) memcache.add("media_likes_%s" % (media_id), likes, 300) return likes def user_recent_media(self, **params): user_id = params["user_id"] max_id = params["max_id"] feed = memcache.get("user_recent_media_%s_%s" % (user_id, max_id)) if not feed: feed = self.api.user_recent_media(user_id=user_id, max_id=max_id) memcache.add("user_recent_media_%s_%s" % (user_id, max_id), feed, 300) return feed def user_follows(self, **params): user_id = params["user_id"] count = params["count"] cursor = params["cursor"] follows = memcache.get("user_follows_%s_%s_%s" % (user_id, count, cursor)) if not follows: follows = self.api.user_follows(user_id=user_id, count=count, cursor=cursor) for user in follows[0]: user["full_name"] = escape(user["full_name"].encode("utf-8")) user["full_name"] = self._convert_emoji(user["full_name"]) memcache.add("user_follows_%s_%s_%s" % (user_id, count, cursor), follows, 300) return follows def user_followed_by(self, **params): user_id = params["user_id"] count = params["count"] cursor = params["cursor"] follows = memcache.get("user_followed_by_%s_%s_%s" % (user_id, count, cursor)) if not follows: follows = self.api.user_followed_by(user_id=user_id, count=count, cursor=cursor) for user in follows[0]: user["full_name"] = escape(user["full_name"].encode("utf-8")) user["full_name"] = self._convert_emoji(user["full_name"]) memcache.add("user_followed_by_%s_%s_%s" % (user_id, count, cursor), follows, 300) return follows def like_media(self, **params): user_id = params["user_id"] media_id = params["media_id"] max_id = params["max_id"] self.api.like_media(media_id) memcache.add("user_has_liked_%s_%s" % (user_id, media_id), True, 300) memcache.delete("media_likes_%s" % (media_id)) def unlike_media(self, **params): user_id = params["user_id"] media_id = params["media_id"] max_id = params["max_id"] self.api.unlike_media(media_id) memcache.delete("user_has_liked_%s_%s" % (user_id, media_id)) memcache.delete("media_likes_%s" % (media_id)) def create_media_comment(self, **params): media_id = params["media_id"] text = params["text"] self.api.create_media_comment(media_id=media_id, text=text) memcache.delete("media_%s" % media_id) memcache.delete("media_comments_%s" % media_id) def user_find_by_username(self, username): user = memcache.get("user_find_by_username_%s" % (username)) if not user: users = self.api.user_search(q=username, count=None) for u in users: if username == u["username"]: user = u memcache.add("user_find_by_username_%s" % (username), user) return user def tag_recent_media(self, **params): tag_name = params["tag_name"] count = params["count"] max_id = params["max_id"] feed = memcache.get("tag_recent_media_%s_%s" % (tag_name, max_id)) if not feed: feed = self.api.tag_recent_media(tag_name=tag_name, count=count, max_id=max_id) memcache.add("tag_recent_media_%s_%s" % (tag_name, max_id), feed, 300) return feed def get_authorize_login_url(self, **params): uri = memcache.get("authorize_login_uri") if not uri: uri = self.api.get_authorize_login_url(scope=params["scope"]) memcache.add("authorize_login_uri", uri, 300) return uri def _convert_emoji(self, text): converter = emoji.factory("softbank", "utf-8") converter.prefix = '<span class="emoji emoji_' converter.suffix = '"></span>' text = converter.convert(text) return text def _convert_tag_to_link(self, text): text = re.sub(r"#([a-zA-Z0-9\-]+)", '<a href="/tag/\g<1>">#\g<1></a>', text) return text def relationship(self, **params): owner_id = params["owner_id"] my_id = params["my_id"] relationship = memcache.get("relationship_%s_%s" % (my_id, owner_id)) if not relationship: relationship = self.api.relationship(owner_id) memcache.add("relationship_%s_%s" % (my_id, owner_id), relationship, 300) return relationship def follow_user(self, **params): owner_id = params["owner_id"] my_id = params["my_id"] relationship = self.api.follow_user(user_id=owner_id) memcache.delete("relationship_%s_%s" % (my_id, owner_id)) return relationship def unfollow_user(self, **params): owner_id = params["owner_id"] my_id = params["my_id"] relationship = self.api.unfollow_user(user_id=owner_id) memcache.delete("relationship_%s_%s" % (my_id, owner_id)) return relationship
class InstagramAccount(Account): 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 log(self, action, details): Account.log(self, 'instagram', action, details) # Pick a popular thing and like it. def like_popular(self): self.log("like-popular", str(datetime.today())) popular = self.api.media_popular(count='20') for i in xrange(8): p = random.choice(popular) self.api.like_media(p.id) # Follow someone. def follow(self, un): uid = self._get_uid(un) # Bug in the official API call for this one. Needs direct HTTP payload = {'ACCESS_TOKEN': self.access_token, 'action': 'follow'} r = requests.post('https://api.instagram.com/v1/users/' + uid + '/relationship?access_token=' + self.access_token, data=payload) return r # Follow a friend of a friend. def follow_branch(self): friends = self.api.user_follows(self.uid) f = random.choice(friends[0]) other_friends = self.api.user_follows(f.id) f2 = random.choice(other_friends[0]) self.log("follow-branch", str(datetime.today()) + ',' + f2.username) self.follow(f2.username) return f2 # make a generic comment # for now these comments are just positive def generic_comment_friend(self): #1. pick a friend friends = self.api.user_follows(self.uid)[0] f = random.choice(friends) #2. pick a dumb comment comment = random.choice(POSITIVE) #3. pick something they posted recent = self.api.user_recent_media(f.id) print recent post = random.choice(recent) self.log("generic-comment-friend", str(datetime.today()) + ',' + str(post) + ',' + str(comment)) #4. make a dumb comment on their dumb post self.api.create_media_comment(post.id, comment) return (post, comment) def generic_comment_feed(self): comment = random.choice(POSITIVE) post = random.choice(self.api.user_media_feed()[0]) self.log("generic-comment-friend", str(datetime.today()) + ',' + str(post) + ',' + str(comment)) self.api.create_media_comment(post.id, comment) # like something a friend posted recently def like_friend(self): friends = self.api.user_follows(self.uid)[0] f = random.choice(friends) recent = self.api.user_recent_media(user_id=f.id, count=20) self.log("like-friends-post", str(datetime.today()) + ',' + f.username) post = random.choice(recent[0]) self.api.like_media(post.id) return post # Helper to turn a username into a user id def _get_uid(self, un): uid = self.api.user_search(q=un) uid = uid[0] uid = uid.id return uid
def get_access_token_url(self): api = InstagramAPI(client_id=self.client_id, client_secret=self.client_secret, redirect_uri=self.redirect_uri) redirect_uri = api.get_authorize_login_url(scope = self.scope) # if(redirect_uri): # response = urllib2.urlopen(redirect_uri).read() return redirect_uri
class InstagramAccount(Account): 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 log(self,action,details): Account.log(self,'instagram',action,details) # Pick a popular thing and like it. def like_popular(self): self.log("like-popular",str(datetime.today())) popular = self.api.media_popular(count='20') for i in xrange(8): p = random.choice(popular) self.api.like_media(p.id) # Follow someone. def follow(self,un): uid = self._get_uid(un) # Bug in the official API call for this one. Needs direct HTTP payload = {'ACCESS_TOKEN':self.access_token,'action':'follow'} r = requests.post('https://api.instagram.com/v1/users/'+uid+'/relationship?access_token='+self.access_token,data=payload) return r # Follow a friend of a friend. def follow_branch(self): friends = self.api.user_follows(self.uid) f = random.choice(friends[0]) other_friends = self.api.user_follows(f.id) f2 = random.choice(other_friends[0]) self.log("follow-branch",str(datetime.today())+','+f2.username) self.follow(f2.username) return f2 # make a generic comment # for now these comments are just positive def generic_comment_friend(self): #1. pick a friend friends = self.api.user_follows(self.uid)[0] f = random.choice(friends) #2. pick a dumb comment comment = random.choice(POSITIVE) #3. pick something they posted recent = self.api.user_recent_media(f.id) print recent post = random.choice(recent) self.log("generic-comment-friend",str(datetime.today())+','+str(post)+','+str(comment)) #4. make a dumb comment on their dumb post self.api.create_media_comment(post.id,comment) return (post,comment) def generic_comment_feed(self): comment = random.choice(POSITIVE) post = random.choice(self.api.user_media_feed()[0]) self.log("generic-comment-friend",str(datetime.today())+','+str(post)+','+str(comment)) self.api.create_media_comment(post.id,comment) # like something a friend posted recently def like_friend(self): friends = self.api.user_follows(self.uid)[0] f = random.choice(friends) recent = self.api.user_recent_media(user_id=f.id,count=20) self.log("like-friends-post",str(datetime.today())+','+f.username) post = random.choice(recent[0]) self.api.like_media(post.id) return post # Helper to turn a username into a user id def _get_uid(self,un): uid = self.api.user_search(q=un) uid = uid[0] uid = uid.id return uid
# Fix Python 2.x. try: import __builtin__ input = getattr(__builtin__, 'raw_input') except (ImportError, AttributeError): pass client_id = input("Client ID: ").strip() client_secret = input("Client Secret: ").strip() redirect_uri = input("Redirect URI: ").strip() raw_scope = input("Requested scope (separated by spaces, blank for just basic read): ").strip() scope = raw_scope.split(' ') # For basic, API seems to need to be set explicitly if not scope or scope == [""]: scope = ["basic"] api = InstagramAPI(client_id=client_id, client_secret=client_secret, redirect_uri=redirect_uri) redirect_uri = api.get_authorize_login_url(scope = scope) print ("Visit this page and authorize access in your browser: "+ redirect_uri) code = (str(input("Paste in code in query string after redirect: ").strip())) access_token = api.exchange_code_for_access_token(code) with open('/var/www/feedagram/feedagram/json/access_token.json', 'w') as outputFile: json.dump(access_token, outputFile, ensure_ascii=False) print ("Access token successfully obtained.")
try: import __builtin__ input = getattr(__builtin__, 'raw_input') except (ImportError, AttributeError): pass try: from config import CLIENT_ID, CLIENT_SECRET, REDIRECT_URI except Exception, e: pass client_id = CLIENT_ID or input("Client ID: ").strip() client_secret = CLIENT_SECRET or input("Client Secret: ").strip() redirect_uri = REDIRECT_URI or input("Redirect URI: ").strip() raw_scope = input("Requested scope (separated by spaces, blank for just basic read): ").strip() scope = raw_scope.split(' ') # For basic, API seems to need to be set explicitly if not scope or scope == [""]: scope = ["basic"] api = InstagramAPI(client_id=client_id, client_secret=client_secret, redirect_uri=redirect_uri) redirect_uri = api.get_authorize_login_url(scope=scope) print("Visit this page and authorize access in your browser: " + redirect_uri) code = (str(input("Paste in code in query string after redirect: ").strip())) access_token = api.exchange_code_for_access_token(code) print("access token: ") print(access_token)
class Instagram: def __init__(self): # Stuff for the attack self.delay = 5 self.victim = None # Stuff for the API self.client_id = 'd00446a61de44643bd0d1a21d78e0f5a' self.client_secret = 'c742af13e3a04138bad288c50e005999' self.redirect_uri = 'http://localhost/hiroshima/auth/insta' self.raw_scope = 'basic likes' self.scope = self.raw_scope.split(' ') # For basic, API seems to need to be set explicitly if not self.scope or self.scope == [""]: self.scope = ["basic"] self.api = InstagramAPI(client_id=self.client_id, client_secret=self.client_secret, redirect_uri=self.redirect_uri) self.redirect_uri = self.api.get_authorize_login_url(scope=self.scope) if os.path.exists(os.path.expanduser("~/.config/hiroshima/hiroshima.cfg")): self.config = ConfigParser.ConfigParser() self.config.read(os.path.expanduser("~/.config/hiroshima/hiroshima.cfg")) self.access_token = self.config.get('insta', 'access_token') if self.access_token != "None": self.AUTH_IN_PREFS = True else: self.AUTH_IN_PREFS = False else: print "~/.config/hiroshima/hiroshima.cfg does not exist. Run install.sh or copy defautl.cfg to ~/.config/hiroshima/hiroshima.cfg" def login(self): if not self.AUTH_IN_PREFS: print "You will be redirected to an authorization page in your browser. Copy the code in the prompt and paste it below." webbrowser.open(self.redirect_uri) code = (str(input("code: ").strip())) self.access_token = self.api.exchange_code_for_access_token(code) if self.access_token != None: self.config.set('insta', 'access_token', str(self.access_token[0])) f = open(os.path.expanduser("~/.config/hiroshima/hiroshima.cfg"), 'wb') self.config.write(f) f.close() self.a_api = InstagramAPI(access_token=self.access_token[0]) print "You're account has been authorized." return True else: return False else: self.a_api = InstagramAPI(access_token=self.access_token) print "You're account has been authorized." return True def set_victim(self, user): self.victim = self.a_api.user(user.id) if self.victim.username == "cryptoc1": print "Nice f*****g try! bruh. ;)" return False if self.victim != None: return True else: return False def search_users(self, uname): return self.a_api.user(self.a_api.user_search(q=uname, count=1)[0].id) def like_attack(self, count): if str(count).lower() == "all": print "Liking " + str(count) + " photos. Due to rate-limits, this may take a while..." print "Number of photos expected to be liked: " + str(self.victim.counts['media']) eta = self.victim.counts['media'] * self.delay print self.format_eta(eta) for media in self.a_api.user_recent_media(user_id=self.victim.id, count=self.victim.counts['media'])[0]: if media.user_has_liked: print "Photo with id: " + str(media.id) + " already liked, skipping." else: self.a_api.like_media(media.id) print "Photo with id: " + str(media.id) + " liked." time.sleep(self.delay) else: count = int(count) print "Liking " + str(count) + " photos. Due to rate-limits, this may take a while..." print "Number of photos expected to be liked: " + str(count) eta = count * self.delay print self.format_eta(eta) for media in self.a_api.user_recent_media(user_id=self.victim.id, count=count)[0]: if media.user_has_liked: print "Photo with id: " + str(media.id) + " already liked, skipping." else: self.a_api.like_media(media.id) print "Photo with id: " + str(media.id) + " liked." time.sleep(self.delay) def unlike_attack(self, count): if str(count).lower() == "all": print "Unliking " + str(count) + " photos. Due to rate-limits, this may take a while..." print "Number of photos expected to be unliked: " + str(self.victim.counts['media']) eta = self.victim.counts['media'] * self.delay print self.format_eta(eta) for media in self.a_api.user_recent_media(user_id=self.victim.id, count=self.victim.counts['media'])[0]: if media.user_has_liked: self.a_api.unlike_media(media.id) print "Photo with id: " + str(media.id) + " unliked." else: print "Photo with id: " + str(media.id) + " already not liked, skipping." time.sleep(self.delay) else: count = int(count) print "Unliking " + str(count) + " photos. Due to rate-limits, this may take a while..." print "Number of photos expected to be unliked: " + str(count) eta = count * self.delay print self.format_eta(eta) for media in self.a_api.user_recent_media(user_id=self.victim.id, count=count)[0]: if media.user_has_liked: self.a_api.unlike_media(media.id) print "Photo with id: " + str(media.id) + " unliked." else: print "Photo with id: " + str(media.id) + " already not liked, skipping." time.sleep(self.delay) def get_attack_types(self): return "like, unlike" def format_eta(self, eta): if eta > 60: return "ETA: " + str(eta / 60) + "M" else: return "ETA: " + str(eta) + "S" def format_user_info(self, u): return "id: " + str(u.id) + "\nusername: "******"\nfull_name: " + unicode(u.full_name).encode('utf-8', 'ignore') + "\nprofile_picture: " + str(u.profile_picture) + "\nbio: " + unicode(u.bio).encode('utf-8', 'ignore') + "\nwebsite: " + str(u.website) + "\ncounts: " + str(u.counts)