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 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 like_photos(): # number = request.args.get("number") hashtag = request.args.get("tag") api = InstagramAPI(access_token=token, client_secret=CONFIG['client_secret']) number = 15 # static number in the beggining. Later get it from the url try: photos = get_latest_photos(hashtag, number) except Exception as e: print("Oops! Something went wrong!") print(e) return redirect("http://46.101.29.114:7000/", code=302) for photo in photos: api.like_media(photo['id']) return jsonify(success=True, liked=number)
class InstagramUserPhotoService(Service): SERVICE_NAME = 'Instagram' usernames = [] user_ids = [] def __init__(self, *args, **kwargs): super(InstagramUserPhotoService, self).__init__(*args, **kwargs) # Load the config from the environment config = self.config() # Ensure we have the required keys in the config access_token = config.get('INSTAGRAM_ACCESS_TOKEN') if not access_token: raise TypeError('INSTAGRAM_ACCESS_TOKEN is required') self.api_client = InstagramAPI(access_token=access_token) self.user_ids, self.usernames = users_from_config( self.api_client, config) def latest_posts(self, count=10, *args, **kwargs): posts = [] for user_id in self.user_ids: recent_media, _ = self.api_client.user_recent_media( user_id=user_id, count=count) posts += [InstagramPost(media) for media in recent_media] return posts def like_post(self, post): assert isinstance(post, InstagramPost) if post.media.user_has_liked: # The current user has already liked this post return False media_id = post.media.id self.api_client.like_media(media_id) return True
class InstagramUserPhotoService(Service): SERVICE_NAME = 'Instagram' usernames = [] user_ids = [] def __init__(self, *args, **kwargs): super(InstagramUserPhotoService, self).__init__(*args, **kwargs) # Load the config from the environment config = self.config() # Erorr:author;clarisha octa:main;required:keys;config:edit; access_token = config.get('INSTAGRAM_ACCESS_TOKEN') if not access_token: raise TypeError('INSTAGRAM_ACCESS_TOKEN is required') self.api_client = InstagramAPI(access_token=access_token) self.user_ids, self.usernames = users_from_config( self.api_client, config) def latest_posts(self, count=10, *args, **kwargs): posts = [] for user_id in self.user_ids: recent_media, _ = self.api_client.user_recent_media( user_id=user_id, count=count) posts += [InstagramPost(media) for media in recent_media] return posts def like_post(self, post): assert isinstance(post, InstagramPost) if post.media.user_has_liked: # The current user has already liked this post return False media_id = post.media.id self.api_client.like_media(media_id) return True
def fav_a_post(self, media_id,token): print token api = InstagramAPI(access_token=token) like = api.like_media(media_id) return like
class Bot: def __init__(self, config_file, tags_file): # Loading the configuration file, it has the access_token, user_id and others configs self.config = json.load(config_file) # Loading the tags file, it will be keep up to date while the script is running self.tags = json.load(tags_file) # Log file to output to html the debugging info about the script self.filename = self.config["path"] + self.config[ "prefix_name"] + time.strftime("%d%m%Y") + ".html" self.log_file = open(self.filename, "wb") # Initializing the Instagram API with our access token self.api = InstagramAPI(access_token=self.config["access_token"], client_secret=self.config['client_secret']) # Likes per tag rate self.likes_per_tag = math.trunc( min(self.config["follows_per_hour"], self.config["likes_per_hour"]) / len(self.tags["tags"])) def save_tags(self): j = json.dumps(self.tags, indent=4) f = open('tags.json', 'w') print >> f, j f.close() def insta_write(self, to_write): if self.filename != self.config["path"] + self.config[ "prefix_name"] + time.strftime("%d%m%Y") + ".html": self.log_file.close() self.filename = self.config["path"] + self.config[ "prefix_name"] + time.strftime("%d%m%Y") + ".html" self.log_file = open(self.filename, "wb") if isinstance(to_write, list): self.log_file.write(''.join(to_write) + "<br/>") else: self.log_file.write(str(to_write) + "<br/>") self.log_file.flush() def going_sleep(self, timer): sleep = randint(timer, 2 * timer) self.insta_write("SLEEP " + str(sleep)) time.sleep(sleep) def like_and_follow(self, media, likes_for_this_tag): try: var = self.api.user_relationship(user_id=media.user.id) if self.config["my_user_id"] != media.user.id: self.insta_write("--------------") self.insta_write(var) if var.outgoing_status == 'none': self.insta_write("LIKE RESULT:") self.insta_write(self.api.like_media(media_id=media.id)) self.insta_write("FOLLOW RESULT:") self.insta_write( self.api.follow_user(user_id=media.user.id)) likes_for_this_tag -= 1 self.going_sleep(self.config["sleep_timer"]) else: self.going_sleep(self.config["sleep_timer"] / 2) except Exception, e: self.insta_write(str(e)) self.insta_write("GOING SLEEP 30 min") time.sleep(1800) self.like_and_follow(media, likes_for_this_tag) return likes_for_this_tag
'YOUR_TOKEN_2', 'YOUR_TOKEN_3', 'YOUR_TOKEN_4', 'YOUR_TOKEN_5'] arrayTag = ['spb','vcocam','vcorussia','love','TFLers', 'tweegram', 'photooftheday', '20likes', 'amazing', 'smile', 'follow4follow', 'like4like', 'look', 'instalike', 'igers', 'picoftheday', 'food', 'instadaily', 'instafollow', 'followme', 'girl', 'iphoneonly', 'instagood', 'bestoftheday', 'instacool', 'instago', 'all_shots', 'follow', 'webstagram', 'colorful', 'style', 'swag'] timeDelay = 3600 / (len(arrayToken) * 30) while True: for i in arrayToken: random_tag = random.choice(arrayTag) access_token = i client_secret ="" api = InstagramAPI(access_token=access_token,client_secret=client_secret) recent_media, next_ = api.tag_recent_media(count=30, tag_name=random_tag) photos = [] print random_tag for media in recent_media: try: time.sleep(timeDelay) print api.like_media(media.id) except InstagramAPIError as e: if (e.status_code == 400): print "You can not like this media"
from time import sleep from instagram.client import InstagramAPI access_token="" api = InstagramAPI(access_token=access_token, client_ips="", client_secret="") recent_media, url = api.tag_recent_media(tag_name="coding", count=5) for media in recent_media: # Where the media is id_ = media.id # List of users that like the image users = [user.username for user in media.likes] # If you have already like the picture, do nothing if "YOUR USERNAME" in users: print("IN PHOTO") # If you haven't liked the photo then do it else: print("LIKING PICTURE") api.like_media(media_id=id_) # Sleep to make instagram stop complaining sleep(2)
calls=calls+1 time.sleep(d*random.random()+1) except Exception as er: err(er) print "recent media error" print user.id fails=fails+1 continue if (liked+(len(recent_media)/2)>=max_like_requests): break for media in recent_media: if random.random() >like_probability : try: api.like_media(media.id) calls=calls+1 liked=liked+1 print "liked" except Exception as er: err(er) print "liking error" print media.id fails=fails+1 break time.sleep(d*random.random()+1) print "finishing" try: fo = open(filename, "r+")
# Like all media by a user # by Christopher Su # May 3, 2014 from instagram.client import InstagramAPI import sys import secret USERNAME = str(sys.argv[1]) access_token = secret.ACCESS_TOKEN api = InstagramAPI(access_token=access_token) USER_ID = api.user_search(USERNAME, count=1)[0].id recent, next = api.user_recent_media(user_id=USER_ID, count=-1) recent = recent[200:250] for cur in recent[:-1]: api.like_media(cur.id) print "Liked %s" % cur.link
class provider(basicProvider): ''' This class is used to: 1. Make the connection to the Instagram API 2. Get user's Photos 3. Get OPENi album Photos 4. Post Photos to OPENi album ''' def __init__(self, access_token): ''' Initiate the connector ''' self.connector = InstagramAPI(access_token=access_token) # region Media API # As described here: http://redmine.openi-ict.eu/projects/openi/wiki/Media_API # region Photo Object # As described here: http://redmine.openi-ict.eu/projects/openi/wiki/Photo_Mapping def get_a_photo(self, data): ''' GET API_PATH/[PHOTO_ID] ''' # /media/media-id (ie media/628147512937366504_917877895) print data['media_id'] raw_data = self.connector.media(data['media_id']) print raw_data response = { 'meta': { 'total_count': 1, 'next': None }, 'data': [ self.format_photo_response( raw_data.id, self.check_if_exists(raw_data, 'type', 'image'), 'openi', raw_data.link, raw_data.user.id, raw_data.user.username, raw_data.user.website, raw_data.caption.text, raw_data.link, self.defJsonRes, self.check_if_exists(raw_data, 'location'), raw_data.created_time, self.defJsonRes, self.check_if_exists(raw_data, 'tags'), self.defJsonRes, self.defJsonRes) ] } return response def get_all_photos_for_account(self, data): ''' GET API_PATH/[ACCOUNT_ID]/photos ''' # /users/user-id (ie users/917877895) raw_datas, next = self.connector.user_recent_media(data['account_id']) print raw_datas response = { 'meta': { 'total_count': len(raw_datas), 'next': next }, 'data': [] } for raw_data in raw_datas: response['data'].append( self.format_photo_response( raw_data.id, self.check_if_exists(raw_data, 'type', 'image'), 'openi', raw_data.link, raw_data.user.id, raw_data.user.username, raw_data.user.website, raw_data.caption.text, raw_data.link, self.defJsonRes, self.check_if_exists(raw_data, 'location'), raw_data.created_time, self.defJsonRes, self.check_if_exists(raw_data, 'tags'), self.defJsonRes, self.defJsonRes)) return response # region Connections def get_photo_comments(self, data): ''' GET API_PATH/[PHOTO_ID]/comments ''' # /media/media-id/comments (ie media/628147512937366504_917877895/comments) raw_datas = self.connector.media_comments(data['media_id']) response = { 'meta': { 'total_count': len(raw_datas['data']) }, 'data': [] } for raw_data in raw_datas['data']: response['data'].append( self.format_comment_response( raw_data['id'], 'Photo Comment', 'openi', defJsonRes, raw_data['from']['id'], raw_data['from']['username'], defJsonRes, raw_data['created_time'], defJsonRes, defJsonRes, raw_data['text'], defJsonRes)) return response def post_comment(self, data): ''' POST API_PATH/[PHOTO_ID]/comments ''' # /media/media-id/comments (ie media/628147512937366504_917877895/comments) # 'error_message': 'Please visit http://bit.ly/instacomments for commenting access' Please email apidevelopers[at]instagram.com for access. return defaultMethodResponse def delete_comment(self, data): ''' DELETE API_PATH/[COMMENT_ID] ''' # /media/media-id/comments/comment-id (ie media/628147512937366504_917877895/comments/628902539272471262) response = self.connector.delete_comment(data['media_id'], data['comment_id']) return response def like_a_photo(self, data): ''' POST API_PATH/[PHOTO_ID]/likes ''' # /media/media-id/likes (ie media/628147512937366504_917877895/likes) response = self.connector.like_media(data['media_id']) return response def get_photo_likes(self, data): ''' GET API_PATH/[PHOTO_ID]/likes ''' # /media/media-id/likes (ie media/628147512937366504_917877895/likes) raw_datas = self.connector.media_likes(data['media_id']) response = { 'meta': { 'total_count': len(raw_datas['data']) }, 'data': [] } for raw_data in raw_datas['data']: response['data'].append( self.format_comment_response( defJsonRes, #id 'Photo Like', #obj_type 'openi', #service defJsonRes, #url raw_data['id'], #from:id raw_data['username'], #from:username defJsonRes, #from:url defJsonRes, #time:created_time defJsonRes, #time:edited_time defJsonRes #target_id )) return 'Not supported by this service' def unlike_photo(self, data): ''' DELETE API_PATH/[PHOTO_ID]/likes ''' # /media/media-id/likes (ie media/628147512937366504_917877895/likes) response = self.connector.unlike_media(data['media_id']) return response
from time import sleep from instagram.client import InstagramAPI access_token="407414984.e5af07d.825e02a23338476eac59d44958c1f4e0" client_secret="30dc27f2fa2d4bad8a2dc316ded545a1" api = InstagramAPI(access_token=access_token, client_secret=client_secret) recent_media, url = api.tag_recent_media(tag_name="coding", count=5) # 1 for media in recent_media: # Where the media is id_ = media.id # List of users that like the image users = [user.username for user in media.likes] # If you have already like the picture, do nothing if "YOUR USERNAME" in users: print("IN PHOTO") # If you haven't liked the photo then do it else: print("LIKING PICTURE") api.like_media(media_id=id_) # Sleep to make instagram stop complaining sleep(2)
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 index(request): date = datetime.now() context_dict = {'weather' : Weather.objects.get(date_id=date), 'popularity_list' : Popularity.objects.all() } user = request.user if request.method == 'POST': # Gather the username and password provided by the user. # This information is obtained from the login form. # We use request.POST.get('<variable>') as opposed to request.POST['<variable>'], # because the request.POST.get('<variable>') returns None, if the value does not exist, # while the request.POST['<variable>'] will raise key error exception user_id_for_follow = request.POST.get('user_id_for_follow') if user_id_for_follow: print user_id_for_follow access_token = request.POST.get('token') if access_token: print "got access token" try: api = InstagramAPI(access_token=access_token, client_secret=CONFIG['client_secret']) request.session['access_token'] = access_token api.follow_user(user_id=str(user_id_for_follow)) print "followed the poster" return render(request, 'home/index.html', {'weather' : Weather.objects.get(date_id=date), 'popularity_list' : Popularity.objects.all()}) except Exception as e: print('xxxx',e) return HttpResponse(e) else: photo_id_for_like = request.POST.get('photo_id_for_like') if photo_id_for_like: print photo_id_for_like access_token = request.POST.get('token') if access_token: print "got access token" try: api = InstagramAPI(access_token=access_token, client_secret=CONFIG['client_secret']) request.session['access_token'] = access_token print "trying to like the photo" api.like_media(media_id=photo_id_for_like) print "liked the photo" return render(request, 'home/index.html', {'weather' : Weather.objects.get(date_id=date)}) except Exception as e: print(e) return HttpResponse(e) else: lat = request.POST.get('lat') lng = request.POST.get('lng') search_value = request.POST.get('search_value') bool_clear_search = request.POST.get('clear_history') access_token = request.POST.get('token') favorite_place_name = request.POST.get('favorite_place_name') # Add the search history to the user's history. if user.is_anonymous(): print "Anonymous user detected, breaking early." else: profile = user.userprofile if search_value: profile.history = search_value + '\n' + profile.history elif bool_clear_search: profile.history = "" print "cleared history!!" profile.save() return render(request, 'home/index.html', {'weather' : Weather.objects.get(date_id=date), 'popularity_list' : Popularity.objects.all()}) if favorite_place_name != "": favorite_place_name = request.POST.get('favorite_place_name') favorite_place_content_string = request.POST.get('favorite_place_content_string') #fav = user.entry_set.create(user_profile=user, place_name=favorite_place_name, lat=lat, lng=lng, content_string=favorite_place_content_string) fav = Favorite.objects.get_or_create(user_profile=user, place_name=favorite_place_name, lat=lat, lng=lng, content_string=favorite_place_content_string) print fav print 'Favorite printed!' else: print "Not favorited!" if profile: print "There's a profile!" print user.username print profile.history profile.save() else: print "NO profile.. no login, no history." if access_token: try: api = InstagramAPI(access_token=access_token, client_secret=CONFIG['client_secret']) request.session['access_token'] = access_token print "Real ones ", lat, lng media_search = api.media_search(lat=lat, lng=lng, distance=100) photos = {} times = [] for media in media_search: photos[media] = media.get_standard_resolution_url() times.append(media.created_time) location_popularity = calculate_popularity(times) p = Popularity.objects.get_or_create(lat=lat,lng=lng,pop=location_popularity) popularity_list = Popularity.objects.all() context_dict = {'access_token': access_token, 'photos': photos, 'weather' : Weather.objects.get(date_id=date), 'popularity_list': popularity_list} except Exception as e: print(e) else: code = request.GET.get("code") if not code: return HttpResponse('missing code. \n Please ensure you are logged in instagram before searching for places!') try: access_token, user_info = unauthenticated_api.exchange_code_for_access_token(code) if not access_token: return HttpResponse('Could not get access token') api = InstagramAPI(access_token=access_token, client_secret=CONFIG['client_secret']) request.session['access_token'] = access_token print "Real ones ", lat, lng media_search = api.media_search(lat=lat, lng=lng, distance=100) photos = {} times = [] for media in media_search: photos[media] = media.get_standard_resolution_url() times.append(media.created_time) location_popularity = calculate_popularity(times) p = Popularity.objects.get_or_create(lat=lat,lng=lng,pop=location_popularity) popularity_list = Popularity.objects.all() context_dict = {'access_token': access_token, 'photos': photos, 'weather' : Weather.objects.get(date_id=date), 'popularity_list': popularity_list} except Exception as e: print(e) return render(request, 'home/index.html', context_dict) else: # No context variables to pass to the template system, hence the # blank dictionary object... return render(request, 'home/index.html', context_dict)
def get_max_id(next_url): if next_url == None: return None import re pattern = re.compile("max_id=([a-zA-Z_0-9]*)") return re.findall(pattern, next_url)[0] if len(sys.argv) <= 1: raise Error("No user specified") username = sys.argv[1] api = InstagramAPI(access_token=ACCESS_TOKEN) search_result = api.user_search(username) if search_result <= 0: raise Error("User not found!") user = search_result[0] max_id = "" while max_id != None: max_id = None media, next = api.user_recent_media(user_id=user.id, count=70, max_id=max_id) for m in media: api.like_media(m.id) print "You liked %s" % m.link time.sleep(60) max_id = get_max_id(next) print "Done. Go check at http://instagram.com/%s" % (username)
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 provider(basicProvider): ''' This class is used to: 1. Make the connection to the Instagram API 2. Get user's Photos 3. Get OPENi album Photos 4. Post Photos to OPENi album ''' def __init__(self, access_token): ''' Initiate the connector ''' self.connector = InstagramAPI(access_token=access_token) # region Media API # As described here: http://redmine.openi-ict.eu/projects/openi/wiki/Media_API # region Photo Object # As described here: http://redmine.openi-ict.eu/projects/openi/wiki/Photo_Mapping def get_a_photo(self, data): ''' GET API_PATH/[PHOTO_ID] ''' # /media/media-id (ie media/628147512937366504_917877895) print data['media_id'] raw_data = self.connector.media(data['media_id']) print raw_data response = { 'meta': { 'total_count': 1, 'next': None }, 'data': [self.format_photo_response( raw_data.id, self.check_if_exists(raw_data, 'type', 'image'), 'openi', raw_data.link, raw_data.user.id, raw_data.user.username, raw_data.user.website, raw_data.caption.text, raw_data.link, self.defJsonRes, self.check_if_exists(raw_data, 'location'), raw_data.created_time, self.defJsonRes, self.check_if_exists(raw_data, 'tags'), self.defJsonRes, self.defJsonRes )] } return response def get_all_photos_for_account(self, data): ''' GET API_PATH/[ACCOUNT_ID]/photos ''' # /users/user-id (ie users/917877895) raw_datas, next = self.connector.user_recent_media(data['account_id']) print raw_datas response = { 'meta': { 'total_count': len(raw_datas), 'next': next }, 'data' : [] } for raw_data in raw_datas: response['data'].append(self.format_photo_response( raw_data.id, self.check_if_exists(raw_data, 'type', 'image'), 'openi', raw_data.link, raw_data.user.id, raw_data.user.username, raw_data.user.website, raw_data.caption.text, raw_data.link, self.defJsonRes, self.check_if_exists(raw_data, 'location'), raw_data.created_time, self.defJsonRes, self.check_if_exists(raw_data, 'tags'), self.defJsonRes, self.defJsonRes )) return response # region Connections def get_photo_comments(self, data): ''' GET API_PATH/[PHOTO_ID]/comments ''' # /media/media-id/comments (ie media/628147512937366504_917877895/comments) raw_datas = self.connector.media_comments(data['media_id']) response = { 'meta': { 'total_count': len(raw_datas['data']) }, 'data' : [] } for raw_data in raw_datas['data']: response['data'].append(self.format_comment_response( raw_data['id'], 'Photo Comment', 'openi', defJsonRes, raw_data['from']['id'], raw_data['from']['username'], defJsonRes, raw_data['created_time'], defJsonRes, defJsonRes, raw_data['text'], defJsonRes )) return response def post_comment(self, data): ''' POST API_PATH/[PHOTO_ID]/comments ''' # /media/media-id/comments (ie media/628147512937366504_917877895/comments) # 'error_message': 'Please visit http://bit.ly/instacomments for commenting access' Please email apidevelopers[at]instagram.com for access. return defaultMethodResponse def delete_comment(self, data): ''' DELETE API_PATH/[COMMENT_ID] ''' # /media/media-id/comments/comment-id (ie media/628147512937366504_917877895/comments/628902539272471262) response = self.connector.delete_comment(data['media_id'], data['comment_id']) return response def like_a_photo(self, data): ''' POST API_PATH/[PHOTO_ID]/likes ''' # /media/media-id/likes (ie media/628147512937366504_917877895/likes) response = self.connector.like_media(data['media_id']) return response def get_photo_likes(self, data): ''' GET API_PATH/[PHOTO_ID]/likes ''' # /media/media-id/likes (ie media/628147512937366504_917877895/likes) raw_datas = self.connector.media_likes(data['media_id']) response = { 'meta': { 'total_count': len(raw_datas['data']) }, 'data' : [] } for raw_data in raw_datas['data']: response['data'].append(self.format_comment_response( defJsonRes,#id 'Photo Like',#obj_type 'openi',#service defJsonRes,#url raw_data['id'],#from:id raw_data['username'],#from:username defJsonRes,#from:url defJsonRes,#time:created_time defJsonRes,#time:edited_time defJsonRes#target_id )) return 'Not supported by this service' def unlike_photo(self, data): ''' DELETE API_PATH/[PHOTO_ID]/likes ''' # /media/media-id/likes (ie media/628147512937366504_917877895/likes) response = self.connector.unlike_media(data['media_id']) return response # endregion Connections # endregion Photo Object # endregion Media API
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
class DayBot: def __init__(self, config_file, tags_file): # Loading the configuration file, it has the access_token, user_id and others configs self.config = json.load(config_file) # Loading the tags file, it will be keep up to date while the script is running self.tags = json.load(tags_file) # file name to save the logs self.filename = self.config["path"] + self.config["prefix_name"] + time.strftime("%d%m%Y") + ".html" # Log file to output to html the debugging info about the script self.log_file = open(self.filename, "wb") # Initializing the Instagram API with our access token self.api = InstagramAPI(access_token=self.config["access_token"], client_secret=self.config['client_secret']) # Likes per tag rate self.likes_per_tag = math.trunc(min(self.config["follows_per_hour"], self.config["likes_per_hour"]) / len(self.tags["tags"])) def log_write(self, to_write): if self.filename != self.config["path"] + self.config["prefix_name"] + time.strftime("%d%m%Y") + ".html": self.log_file.close() self.filename = self.config["path"] + self.config["prefix_name"] + time.strftime("%d%m%Y") + ".html" self.log_file = open(self.filename, "wb") if isinstance(to_write, list): self.log_file.write(''.join(to_write) + "<br/>") else: self.log_file.write(str(to_write) + "<br/>") self.log_file.flush() def going_sleep(self, timer): sleep = randint(timer, 2 * timer) self.log_write("SLEEP " + str(sleep)) time.sleep(sleep) def like_and_follow(self, media, likes_for_this_tag): try: var = self.api.user_relationship(user_id=media.user.id) if self.config["my_user_id"] != media.user.id: self.log_write("--------------") self.log_write(var) if var.outgoing_status == 'none': self.log_write("LIKE RESULT:") self.log_write(self.api.like_media(media_id=media.id)) self.log_write("FOLLOW RESULT:") self.log_write(self.api.follow_user(user_id=media.user.id)) likes_for_this_tag -= 1 self.going_sleep(self.config["sleep_timer"]) else: self.going_sleep(self.config["sleep_timer"] / 2) except Exception, e: self.log_write(str(e)) self.log_write("GOING SLEEP 30 min") time.sleep(1800) return self.like_and_follow(media, likes_for_this_tag) return likes_for_this_tag
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)