1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.

Little Twitter Mass Unfollow/Tweet/Keyword Retweet/Keyword Follow Python Script

Discussion in 'BlackHat Lounge' started by @Cody, Nov 5, 2012.

  1. @Cody

    @Cody Newbie

    Joined:
    Jan 31, 2012
    Messages:
    12
    Likes Received:
    8
    Occupation:
    Student/PHP Progamming Intern
    Location:
    United States
    Home Page:
    Hi BHW... I was toying around with the Tweepy python module and came up with a very simple script that all runs from the interpreter/command line... It will let you send tweets, unfollow people who aren't following you (only 350/hr because of rate limiting), search for keywords and then retweet those people who tweeted the keyword, or follow them... Not a whole lot of functionality, but it was written in about an hour and a half, mainly to learn the library. It's not the prettiest, or the ugliest code I've ever written. Feel free to do with it what you wish. Hopefully it'll help someone out!

    Dependencies are:
    Python and Tweepy

    Code:
    import tweepy
    import webbrowser
    
    
    # Make constants to hold values of our keys
    CONSUMER_KEY = "GET YOUR OWN CONSUMER KEY"
    CONSUMER_SECRET = "GET YOUR OWN CONSUMER SECRET"
    ACCESS_TOKEN = "GET YOUR OWN ACCESS TOKEN"
    ACCESS_SECRET = "GET YOUR OWN ACCESS SECRET"
    
    
    # set auth variables
    auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
    auth.set_access_token(ACCESS_TOKEN, ACCESS_SECRET)
    
    
    # create a new api
    api = tweepy.API(auth)
    
    
    # create an instance of the twitter api class
    auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
    auth_url = auth.get_authorization_url()
    
    
    # open the window for authorization, twitter will generate the pin
    webbrowser.open(auth_url)
    print "Copy PIN from the window that opens"
    
    
    # get the pin number from the user
    verifier = raw_input('PIN: ').strip()
    auth.get_access_token(verifier)
    
    
    # get the access key and secret returned from twitter
    access_key = auth.access_token.key
    access_secret = auth.access_token.secret
    
    
    # set authorization token
    auth.set_access_token(access_key, access_secret)
    api = tweepy.API(auth)
    
    
    # make a tweet
    def send_tweet():
        to_tweet = True
        tweet_text = raw_input("Enter your tweet content below... Only the first 140 characters will be used.\n>>> ")
        api.update_status(tweet_text[0:140])
        print "You tweeted \n'" + tweet_text[0:140] + "'"
        restart = raw_input("Do you want to tweet again? (Y/N)\n>>> ")
        if restart.lower() == "y":
            send_tweet()
        else:
            print "Returning to the Main Menu...\n"
    
    
    # search twitter
    def keyword_follow():
        search_phrase = raw_input("What do you want to search for?\n>>> ").strip()
        search_number = raw_input("How many results do you want to return?\n>>> ")
        search_result = api.search(search_phrase, rpp=search_number)
        for i in search_result:
            print i.from_user + " said " + i.text + "\n"
            to_follow = raw_input("Do you want to follow " + i.from_user + "? (Y/N)\n>>> ")
            if to_follow.lower() == "n":
                print i.from_user + " was not followed!"
            else:
                api.create_friendship(i.from_user)
                print "You followed " + i.from_user + "!\n"
                
        # check if the user wants to search again
        restart = raw_input("Do you want to search again? (Y/N)\n>>> ")
        if restart.lower() == "n":
            print "Returning to the Main Menu...\n"
        else:
            return keyword_follow()
        
    def keyword_retweet():
        search_phrase = raw_input("What do you want to search for?\n>>> ").strip()
        search_number = raw_input("How many results do you want to return?\n>>> ")
        search_result = api.search(search_phrase, rpp=search_number)
        for i in search_result:
            print i.from_user + " said " + i.text + "\n"
            to_retweet = raw_input("Do you want to retweet" + i.from_user + "? (Y/N)\n>>> ")
            if to_retweet.lower() == "n":
                print i.from_user + " was not retweeted!"
            else:
                api.retweet(i.id)
                print "Retweeted!\n"
                again = raw_input("See more? (Y/N)\n>>> ")
                if again.lower() == "n":
                    break       
        # check if the user wants to search again
        restart = raw_input("Do you want to search again? (Y/N)\n>>> ")
        if restart.lower() == "n":
            print "Returning to the Main Menu...\n"
        else:
            return keyword_retweet()
    
    
    def mass_unfollow():
        hits_left = api.rate_limit_status()['remaining_hits']
        print "You can unfollow " + str(hits_left) + " people this hour...\n"
        print "Checking who doesn't follow you back. This will take a minute.\n"
        # first, create some lists to hold the followers
        followers = []
        friends = []
        
        # we have to use a Cursor for pagination purposes
        for follower in tweepy.Cursor(api.followers).items():
            followers.append(follower)
    
    
        for friend in tweepy.Cursor(api.friends).items():
            friends.append(friend)
            
        # create a non_reciprocals list, these are non-followers (set - set)
        non_reciprocal = list(set(friends) - set(followers))
        print str(len(non_reciprocal)) + " non-reciprocal followers.\n"
    
    
        # first, double check that we want to unfollow
        double_check = raw_input("Unfollow them? (Y/N) ***WARNING, THIS ACTION CANNOT BE UNDONE***\n>>> " )
    
    
        if double_check.lower() == "y":
            # count the number of people we unfollow, just for fun
            counter = 0
            for i in non_reciprocal:
                if hits_left > 0:
                    api.destroy_friendship(i.screen_name)
                    print "Successfully unfollowed " + i.screen_name
                    hits_left -= 1
                else:
                    print "You ran out of hits! Try again in an hour!"
                    break
                counter += 1
            print "You unfollowed " + str(counter) + " people!\n"
            print "Now returning to the Main Menu."
        else:
            print "Returning to the Main Menu...\n"
                  
    # create the menu
    keep_running = True
    while keep_running:
        print "Main Menu"
        print "---------\n"
        selection = raw_input("(1)Tweet | (2)Keyword Follow | (3)Keyword Retweet | (4)Mass Unfollow | (5)End\n\n>>> ")
        if selection == "1":
            print "New Tweet"
            print "---------\n"
            send_tweet()
        elif selection == "2":
            print "Keyword Follow"
            print "--------------\n"
            keyword_follow()
        elif selection == "3":
            print "Keyword Retweet"
            print "---------------\n"
            keyword_retweet()
        elif selection == "4":
            print "Mass Unfollow"
            print "-------------\n"
            print "WARNING: MASS UNFOLLOW IS AGAINST THE TOS OF TWITTER. YOU'VE BEEN WARNED\n"
            mass_unfollow()
        else:
            print "BYE!\n\n"
            keep_running = False
    
    In order to make this work, you'll have to change the constants that I defined in the first part of the script. To get your keys, visit dev.twitter.com/apps/new and create a new app with a name of your choice. Then copy-paste the keys into place. You should now be able to run it! Let me know if there are any questions.

    EDIT: I tried to post links to Tweepy and the twitter dev site, but I get an error that I'm too new to post links... So here they are in non-link format... replace the * with a . (duh)

    For Tweepy:
    github*com/tweepy/tweepy

    For Your Keys:
    dev*twitter*com/apps/new

    EDIT 2: Didn't even realize there was a downloads section here... I suppose that would have been a better place for this thread. Move it as you see fit please.
     
    • Thanks Thanks x 1
    Last edited: Nov 5, 2012