class AutoDirectMsg: # Message DIRECTMESSAGE = "Hey there, thanks for following Present! Check our app at http://bit.ly/19dJ9D6 and let us know what you think! Cheers, Present Team" # Text file that will contain all sent message user USERNAMEFILE = 'followerUser.txt' # Count of all sent message user UFFollowerCount = 0 DMFollowerCount = 0 # Buffer time before sending message InBetweenTime = 60 # Direct message log DMLog = Logging.TimedLogging("DMLog", 1) DMLog.start() # User follow Present UFLog = Logging.TimedLogging("UFLog", 1) UFLog.start() # Check if message was sent to follower # It will read from the text file and compare names and see whether to send the message # It will only send the message once to each follower even if the user unfollows and follows back def CheckFollower(self, userName): if os.path.isfile(self.USERNAMEFILE) == False: open(self.USERNAMEFILE, 'w').close() # Only goes in once on 1st follower if len(open(self.USERNAMEFILE, 'r').read().splitlines()) == 0: return False else: for name in open(self.USERNAMEFILE, 'r').read().splitlines(): if userName == name: return True return False # Writes new follower name into the text file def WriteFollowerToFile(self, followerName): followerFile = open(self.USERNAMEFILE, 'a') followerFile.write(followerName) followerFile.write('\n') followerFile.close() # Sends message and store user name into the list def SendDirectMessage(self, userName): api.send_direct_message(screen_name=userName, text=self.DIRECTMESSAGE) def ResetFollower(self, followerName): self.WriteFollowerToFile(followerName) # Function that does the follower checking and sending of message def AutoMessage(self, doRealMssage): # Gets all follower of PresentAppCo for AllFollowers in tweepy.Cursor(api.followers, screen_name="PresentAppCo").items(): # Check if user exist in text file if self.CheckFollower(AllFollowers.screen_name) == True: print("Already sent to " + AllFollowers.screen_name) continue print("Waiting " + str(self.InBetweenTime) + " seconds before continuing") time.sleep(self.InBetweenTime) print("Finished waiting, continuing") #self.ResetFollower(AllFollowers.screen_name) # Logging of user that has followed Present self.UFFollowerCount += 1 self.UFLog.create_timed_log(AllFollowers.screen_name) if self.UFLog.timesup == True: self.UFLog.create_timed_log(str(self.UFFollowerCount)) self.UFLog.endtime = True self.UFFollowerCount = 0 # True = real message, False = test message # Real message user if doRealMssage == True: self.SendDirectMessage(AllFollowers.screen_name) print("Real sent msg to %s" % AllFollowers.screen_name) # Test message user else: print("Test sent msg to %s" % AllFollowers.screen_name) self.WriteFollowerToFile(AllFollowers.screen_name) # Logging of user that has been sent direct message self.DMFollowerCount += 1 self.DMLog.create_timed_log(AllFollowers.screen_name) if self.DMLog.timesup == True: self.DMLog.create_timed_log(str(self.DMFollowerCount)) self.DMLog.endtime = True self.DMFollowerCount = 0 break # Main function with limit checking # If there is a rate limit error, it will wait 15 minutes before continuing (Twitter API rate limits, 15 mins) def DoAutoMsg(self): try: self.AutoMessage(False) except tweepy.error.TweepError: print( "AutoMsg - Rate limit exceeded, waiting 15 minutes before continuing" ) time.sleep(15 * 60) print("AutoMsg - Finished waiting, continuing...") self.AutoMessage(False) def AutoMsgMain(self): while True: self.DoAutoMsg()
class AutoLovePost: USERNAMEFILE = "likedPostUser.txt" CurrentMediaID = "" FollowerCount = 0 LoveLog = Logging.TimedLogging("LLog", 1) LoveLog.start() # Writes liked user name into a file (likedUser.txt) def WriteNameToFile(self, userInfo): userFile = open(self.USERNAMEFILE, 'a') userFile.write(userInfo) userFile.write('\n') userFile.close() # Checks for duplicated user to ensure only 1 user is loved def CheckUserDuplicates(self, username): try: userFile = open(self.USERNAMEFILE, 'r') for name in userFile.read().splitlines(): if username == name: userFile.close() return True userFile.close() return False except IOError: open(self.USERNAMEFILE, 'w').close() return False # Convert URL to JSON data def DecodeJSONData(self, url): response = urllib2.urlopen(url) reader = codecs.getreader("utf-8") decodedData = json.load(reader(response)) return decodedData # Gets username from a single line (e.g. User: Jason) def GetUserName(self, data): usernameStr = str(data) name = usernameStr[usernameStr.find("'username': "******"https://api.instagram.com/v1/media/%s/likes?access_token=" + access_token userDataList = [] if ownPostData['data'][0]['likes']['count'] == 0: return 0 decodedData = self.DecodeJSONData(POSTLIKEURL % ownPostData['data'][0]['id']) for user in decodedData['data']: if self.CheckUserDuplicates(user['username']) == True: if user == decodedData['data'][-1]: return 0 continue POSTURL = "https://api.instagram.com/v1/users/%s/media/recent/?access_token=%s&count=%d" % ( user['id'], access_token, count) try: decodedData = self.DecodeJSONData(POSTURL) except urllib.error.HTTPError: continue for post in decodedData['data']: try: captiontext = post['caption']['text'] except TypeError: captiontext = "Can't get status text" userDataList.append( UserInfo(post['user']['username'], post['user']['id'], captiontext, post['id'], post['link'])) return userDataList # Main function def DoAutoLove(self, doRealLove): POSTURL = "https://api.instagram.com/v1/users/%s/media/recent/?access_token=" + access_token + "&count=1" inBetweenTime = 90 EndBufferTime = 900 likePost = False # Gets own user id ownID = access_token[:access_token.find('.')] # Gets own latest post ownPostData = self.DecodeJSONData(POSTURL % (ownID)) # Gets all user that loves own latest post # Returns a UserInfo list likersData = self.GetUserPostData(ownPostData, 2) # Check if there is user that has like own latest post if likersData != 0: # Loops through all user data for user in likersData: print("AutoLovePost - Waiting " + str(inBetweenTime) + " seconds before continuing") time.sleep(inBetweenTime) print("AutoLovePost - Done waiting, continuing...") # True = real love, False = test love # Real love post if doRealLove == True: # if likePost = False, it means the current post hasn't been loved yet # It will loop through until the post has been loved while likePost == False: # Try catch statement to catch api rate limits try: api.like_media(user.MediaID) likePost = True except InstagramAPIError: print( "AutoLovePost - Rate limit exceeded, waiting %s seconds before continuing" % EndBufferTime) time.sleep(EndBufferTime) print( "AutoLovePost - Finished waiting, continuing..." ) # Resetting likePost likePost = False # Try catch statement to catch strings that has the error UnicodeEncodeError when printing out try: print("AutoLovePost - Real Loved: " + user.Username + "-" + user.MediaText + "\n") except UnicodeEncodeError: print("AutoLovePost - Real Loved \n") # Test love post else: try: print("AutoLovePost - Test Loved: " + user.Username + "-" + user.MediaText + "\n") except UnicodeEncodeError: print("AutoLovePost - Test Loved \n") # Checking of current own post id with text file # Is to write the current own post id into a file if self.CheckUserDuplicates( ownPostData['data'][0]['id']) == False: userFile = open(self.USERNAMEFILE, 'w') userFile.write(ownPostData['data'][0]['id']) userFile.write('\n') userFile.close() # Is to write the current own post id into a log self.LoveLog.create_timed_log( ownPostData['data'][0]['link']) self.FollowerCount += 1 # Logging of users that has been loved self.LoveLog.create_timed_log(user.Username + ": " + user.MediaURL) if self.LoveLog.timesup == True: self.LoveLog.create_timed_log(str(self.FollowerCount)) self.LoveLog.endtime = True self.FollowerCount = 0 # try catch statement to check if it's the last post by a user try: if likersData[likersData.index(user) + 1].Username != user.Username: print("AutoLovePost - Last post by " + user.Username + ", continuing next user\n") self.WriteNameToFile(user.Username) except IndexError: print("AutoLovePost - Last post by " + user.Username + ", continuing next user\n") self.WriteNameToFile(user.Username) # No user has liked yet else: print("AutoLovePost - No new user liked yet") def DoAutoLoveMain(self): while True: self.DoAutoLove(True) # Main function def TryAutoLove(self): self.DoAutoLoveMain()
class FollowingUser(threading.Thread): FOLLOWINGFILE = "followingUser.txt" FollowingCount = 0 InBetweenTime = 60 # Present follow user PFLog = Logging.TimedLogging("PFLog", 1) PFLog.start() # Writes new following name into the text file def WriteFollowingToFile(self, followingName): followingFile = open(self.FOLLOWINGFILE, 'a') followingFile.write(followingName) followingFile.write('\n') followingFile.close() # Check if following user exist in text file def CheckExistingFollowing(self, screenName): try: userFile = open(self.FOLLOWINGFILE, 'r') for name in userFile.read().splitlines(): if screenName == name: return True return False except IOError: open(self.FOLLOWINGFILE, 'w').close() return False def GetFollowing(self): for friend in tweepy.Cursor(api.friends).items(): if self.CheckExistingFollowing(friend.screen_name) == True: print(friend.screen_name + " already exist in text file") continue print("FollowingUser - Waiting " + str(self.InBetweenTime) + " seconds before continuing") time.sleep(self.InBetweenTime) print("FollowingUser - Finished waiting, continuing") self.FollowingCount += 1 self.WriteFollowingToFile(friend.screen_name) self.PFLog.create_timed_log(friend.screen_name) if self.PFLog.timesup == True: self.PFLog.create_timed_log(str(self.FollowingCount)) self.PFLog.endtime = True self.FollowingCount = 0 def DoGetFollowing(self): try: self.GetFollowing() except tweepy.TweepError: print( "FollowingUser - Rate limit exceeded, waiting 15 minutes before continuing" ) time.sleep(15 * 60) print("FollowingUser - Finished waiting, continuing...") self.GetFollowing() def run(self): while True: self.DoGetFollowing()
class AutoFollow: USERNAMEFILE = "followedUser.txt" InBetweenTime = 180 FollowerCount = 0 UFLog = Logging.TimedLogging("UFLog", 1) UFLog.start() # Writes followed user name into a file (followedUser.txt) def WriteNameToFile(self, username): userFile = open(self.USERNAMEFILE, 'a') userFile.write(username) userFile.write('\n') userFile.close() # Check if already followed user def CheckFollowedStatus(self, username): try: userFile = open(self.USERNAMEFILE, 'r') for name in userFile.read().splitlines(): if username == name: userFile.close() return True userFile.close() return False except IOError: open(self.USERNAMEFILE, 'w').close() return False # Convert URL to JSON data def DecodeJSONData(self, url): response = urllib2.urlopen(url) reader = codecs.getreader("utf-8") decodedData = json.load(reader(response)) return decodedData # Main auto follow function def DoAutoFollow(self, doRealFollow): # To authorize of basic, liking, following and commenting #webbrowser.open('https://instagram.com/oauth/authorize/?client_id=%s&redirect_uri=%s&response_type=token&scope=likes+relationships+comments+basic' % (client_id, redirect_uri)) #USERURL = "https://api.instagram.com/v1/users/search?q=%s&access_token=" + access_token USERURL = "https://api.instagram.com/v1/users/%s?access_token=" + access_token FOLLOWERURL = "https://api.instagram.com/v1/users/%s/followed-by?count=%s&access_token=" + access_token # Gets own user id ownID = access_token[:access_token.find('.')] ownProfile = self.DecodeJSONData(USERURL % ownID) ownFollowerCount = ownProfile['data']['counts']['followed_by'] # Gets list of user that has followed you followerData = self.DecodeJSONData(FOLLOWERURL % (ownID, ownFollowerCount)) # Looping through each user data from the list for user in followerData['data']: # Gets username from user data username = user['username'] userID = user['id'] # Check if user exist in the text file # If it exist, it will loop to next user # If it doesn't exist, continue if self.CheckFollowedStatus(username) == True: print("AutoFollow - Already followed " + username) continue print("AutoFollow - Waiting %s seconds before continuing." % self.InBetweenTime) time.sleep(self.InBetweenTime) print("AutoFollow - Done waiting, continuing...") # True = real follow, False = test follow # Real follow user if doRealFollow == True: api.follow_user(user_id=userID) print("AutoFollow - Real Followed " + username) # Test follow user else: print("AutoFollow - Test Followed " + username) self.FollowerCount += 1 self.WriteNameToFile(username) self.UFLog.create_timed_log(username) if self.UFLog.timesup == True: self.UFLog.create_timed_log(str(self.FollowerCount)) self.UFLog.endtime = True self.FollowerCount = 0 def AutoFollowMain(self): while True: self.DoAutoFollow(False) def TryAutoLove(self): EndBufferTime = 60 * 60 try: self.AutoFollowMain() except InstagramAPIError: print( "AutoFollow - Rate limit exceeded, waiting %s seconds before continuing" % EndBufferTime) time.sleep(EndBufferTime) print("AutoFollow - Finished waiting, continuing...") self.AutoFollowMain()
class FollowingUser(threading.Thread): FOLLOWINGFILE = "followingUser.txt" FollowingCount = 0 InBetweenTime = 60 # Present follow user PFLog = Logging.TimedLogging("PFLog", 1) PFLog.start() # Writes new following name into the text file def WriteFollowingToFile(self, followingName): followingFile = open(self.FOLLOWINGFILE, 'a') followingFile.write(followingName) followingFile.write('\n') followingFile.close() # Check if following user exist in text file def CheckExistingFollowing(self, screenName): try: userFile = open(self.FOLLOWINGFILE, 'r') for name in userFile.read().splitlines(): if screenName == name: return True return False except IOError: open(self.FOLLOWINGFILE, 'w').close() return False # Convert URL to JSON data def DecodeJSONData(self, url): response = urllib2.urlopen(url) reader = codecs.getreader("utf-8") decodedData = json.load(reader(response)) return decodedData def GetFollowing(self): #USERURL = "https://api.instagram.com/v1/users/search?q=%s&access_token=" + access_token # Gets own user id USERURL = "https://api.instagram.com/v1/users/%s?access_token=" + access_token FOLLOWINGURL = "https://api.instagram.com/v1/users/%s/follows?count=%s&access_token=" + access_token ownID = access_token[:access_token.find('.')] ownProfile = self.DecodeJSONData(USERURL % ownID) ownFollowingCount = ownProfile['data']['counts']['follows'] # Gets list of user that has followed you followingData = self.DecodeJSONData(FOLLOWINGURL % (ownID, ownFollowingCount)) # Looping through each user data from the list for user in followingData['data']: # Gets username from user data username = user['username'] # Check if user exist in the text file # If it exist, it will loop to next user # If it doesn't exist, continue if self.CheckExistingFollowing(username) == True: print("AutoFollow - User already exist!") continue self.FollowingCount += 1 self.WriteFollowingToFile(username) self.PFLog.create_timed_log(username) if self.PFLog.timesup == True: self.PFLog.create_timed_log(str(self.FollowingCount)) self.PFLog.endtime = True self.FollowingCount = 0 def DoGetFollowing(self): try: self.GetFollowing() except InstagramAPIError: print( "FollowingUser - Rate limit exceeded, waiting 15 minutes before continuing" ) time.sleep(15 * 60) print("FollowingUser - Finished waiting, continuing...") self.GetFollowing() def run(self): while True: self.DoGetFollowing()
class AutoFav: USERNAMEFILE = 'favoriteUser.txt' maxTweetCount = 20 FavCount = 0 keywords = Keywords() FavLog = Logging.TimedLogging("FLog", 1) FavLog.start() # Writes favorited user name into a file (favoritedUser.txt) def WriteNameToFile(self, userInfo): userFile = open(self.USERNAMEFILE, 'a') userFile.write(userInfo.Screen_Name) userFile.write('\n') userFile.close() # Checks for duplicated user to ensure only 1 user is favorited def CheckUserDuplicates(self, screenName): try: userFile = open(self.USERNAMEFILE, 'r') for name in userFile.read().splitlines(): if screenName == name: return True return False except IOError: open(self.USERNAMEFILE, 'w').close() return False # Actual function to automate favorite tweet def DoAutoFav(self, doRealFav): while True: # Looping through tweets with specific keyword for tweet in tweepy.Cursor(api.search, q=self.keywords.IDToWords( self.keywords.RandomWordsID(), True), count=self.maxTweetCount, result_type="recent").items(): # Check if user exist in text file if self.CheckUserDuplicates(tweet.user.screen_name) == True: continue # Setting user data into UserInfo userInfo = UserInfo(tweet.user.screen_name, tweet.user.name, tweet.user.id, tweet.id, tweet.text) # True = real favorite, False = test favorite # Real favorite tweet if doRealFav == True: # Try catch statement to catch api rate limits try: api.create_favorite(tweet.id) try: print("AutoFav - Real Favorited " + userInfo.Screen_Name + "-" + userInfo.Status_Text) except UnicodeEncodeError: print("AutoFav - Real Favorited") except tweepy.error.TweepError: print( "AutoFav - Rate exceeded, waiting 15 minutes before continuing" ) time.sleep(15 * 60) print("AutoFav - Done waiting, continuing...") continue self.WriteNameToFile(userInfo) self.FavLog.create_timed_log(self.keywords.keywords) # Test favorite tweet else: self.WriteNameToFile(userInfo) self.keywords.AddKeywordsToDict(self.keywords.keywords, 1) self.FavLog.reset_log() for key, value in self.keywords.keywordsDict.items(): self.FavLog.create_timed_log(key + ": " + str(value)) try: print("AutoFav - Test Favorited " + userInfo.Screen_Name + "-" + userInfo.Status_Text) except UnicodeEncodeError: print("AutoFav - Test Favorited") # Increment favorite count if there's such tweet self.FavCount += 1 break # Check if there's any favorite # If not, refind tweet if self.FavCount != 0: self.FavCount = 0 break print("AutoFav - Refinding keyword...") # Clears data from favoritedUser text file def ResetData(self): open(self.USERNAMEFILE, 'w').close() def AutoFavMain(self): currentTime = 0 # 40 favorites MaxFavorite = 40 # Per hour MaxTimeLimit = 3600 # After an hour buffer time before restarting EndBufferTime = 60 # Buffer time between each favorite InBetweenTime = MaxTimeLimit / MaxFavorite # Infinite loop while True: if currentTime < MaxTimeLimit: currentTime += InBetweenTime else: #Clear favorited user names from text file (favoritedUser.txt) self.ResetData() #Real-time waiting time.sleep(EndBufferTime) currentTime = 0 #False for test favorite, True for real favorite self.DoAutoFav(False) print("AutoFav - Waiting %s seconds before continuing" % InBetweenTime) #Real-time waiting time.sleep(InBetweenTime) if self.FavLog.timesup == True: self.FavLog.timesup = False self.keywords.ResetKeywordsDict() print("AutoFav - Finished waiting, continuing\n")
class AutoLove: TAGURL = 'https://api.instagram.com/v1/media/%s?access_token=%s' USERNAMEFILE = "likedHashTagUser.txt" ENDBUFFERTIME = 15 * 60 keywords = Keywords() TagLog = Logging.TimedLogging("TLog", 1) TagLog.start() # Writes liked user name into a file (likedUser.txt) def WriteNameToFile(self, username): userFile = open(self.USERNAMEFILE, 'a') userFile.write(username) userFile.write('\n') userFile.close() # Convert URL to JSON data def DecodeJSONData(self, url): response = urllib2.urlopen(url) reader = codecs.getreader("utf-8") decodedData = json.load(reader(response)) return decodedData # Gets media ID from a single line (e.g. Media: 918328349) def GetMediaID(self, recent_media): mediaStr = str(recent_media) ID = mediaStr[mediaStr.find('Media: ')+7:] return ID # Gets username from JSON data def GetUsername(self, decodedData): try: return decodedData['data']['user']['username'] except TypeError: return "Can't get username" # Gets caption text from JSON data def GetCaptionText(self, decodedData): try: return decodedData['data']['caption']['text'] except TypeError: return "Can't get caption text" # Checks for duplicated user to ensure only 1 user is loved def CheckUserDuplicates(self, username): try: userFile = open(self.USERNAMEFILE, 'r') for name in userFile.read().splitlines(): if username == name: return True return False except IOError: open(self.USERNAMEFILE, 'w').close() return False # Gets media data from JSON data def GetMediaDataRaw(self, data): mediaID = self.GetMediaID(data) decodedData = self.DecodeJSONData(self.TAGURL % (mediaID, access_token)) return decodedData # Main function def DoAutoLove(self, doRealLove): while True: # Gets random keywords to search tag_name = self.keywords.RandomWords() # Gets the media with the keyword in it recent_media = api.tag_recent_media(count = 1, tag_name = tag_name) # Gets the data from the media data = self.GetMediaDataRaw(recent_media[0][0]) # Gets username from the data username = self.GetUsername(data) # Check id user exist in text file if self.CheckUserDuplicates(username) == True or username == "presentappco": print("AutoLoveTag - Same username, finding new user") continue print("AutoLoveTag - Found user!") # Gets the media id mediaID = self.GetMediaID(recent_media[0][0]) # Gets the caption text of the media caption = self.GetCaptionText(data) # True = real love, False = test love # Real love post if doRealLove == True: # Try catch statement to catch api rate limits try: api.like_media(mediaID) except InstagramAPIError: print("AutoLoveTag - Rate limit exceeded, waiting %s seconds before continuing" % self.ENDBUFFERTIME) time.sleep(self.ENDBUFFERTIME) print("AutoLoveTag - Finished waiting, continuing...") continue # Try catch statement to catch strings that has the error UnicodeEncodeError when printing out try: print("AutoLoveTag - Real Liked " + username + "-" + caption + "\n") except UnicodeEncodeError: print("AutoLoveTag - Real Liked \n") # Test love post else: try: print("AutoLoveTag - Test Liked " + username + "-" + caption + "\n") except UnicodeEncodeError: print("AutoLoveTag - Test Liked \n") self.WriteNameToFile(username) self.keywords.AddKeywordsToDict(tag_name, 1) self.TagLog.reset_log() for key, value in self.keywords.keywordsDict.items(): self.TagLog.create_timed_log(key + ": " + str(value)) break # Clears data from likedUser text file def ResetData(self): open(self.USERNAMEFILE, 'w').close() def AutoLoveMain(self): currentTime = 0 # 50 loves MaxLove = 30 # Per hour MaxTimeLimit = 3600 # After an hour buffer time before restarting EndBufferTime = 60 # Buffer time between each favorite InBetweenTime = MaxTimeLimit / MaxLove # Infinite loop while True: if currentTime < MaxTimeLimit: currentTime += InBetweenTime else: print("AutoLoveTag - " + str(MaxTimeLimit) + " seconds up, waiting " + str(EndBufferTime) + " seconds before continuing") #Real-time waiting time.sleep(EndBufferTime) print ("AutoLoveTag - Resetting data...") #Clear liked user names from text file (likedUser.txt) self.ResetData() currentTime = 0 print ("AutoLoveTag - Resetting done, continuing...") #False for test like, True for real like self.DoAutoLove(False) print ("AutoLoveTag - Waiting " + str(InBetweenTime) + " seconds before continuing") #Real-time waiting time.sleep(InBetweenTime) if self.TagLog.timesup == True: self.TagLog.timesup = False self.keywords.ResetKeywordsDict() print ("AutoLoveTag - Waiting done, continuing... \n")