def RT(ID, name):
    """Function that actually retweets tweet"""
    """Takes a ID and username parameter"""
    """Once tweeted log is updated in overall and to date tweetlog"""

    config = config_create()
    print("RT")
    #Tid = int(float(ID))
    Tweetusername = config.get('Auth', 'botname')
    #TweetText = 'https://twitter.com/'+Tweetusername+'/status/'+ID
    #ReTweet = 'Hi I am ComicTweetBot!('+tim+') I Retweet Comics! Use #comicretweetbot '+TweetText
    x2 = config.get('Latest_Log', 'currenttweetlog')
    x3 = config.get('Latest_Log', 'overalllog')
    CONSUMER_KEY = config.get('Auth', 'CONSUMER_KEY')
    CONSUMER_SECRET = config.get('Auth', 'CONSUMER_SECRET')
    ACCESS_KEY = config.get('Auth', 'ACCESS_KEY')
    ACCESS_SECRET = config.get('Auth', 'ACCESS_SECRET')
    api = Twython(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_KEY, ACCESS_SECRET)
    tMax = int(float(config.get('Tweet_Delay', 'Max')))
    tMin = int(float(config.get('Tweet_Delay', 'Min')))
    tStep = int(float(config.get('Tweet_Delay', 'Step')))
    Log = open(x2, 'w')
    enterlog = ID + ' ' + name + '\n'
    Log.write(enterlog)
    Log2 = open(x3, 'w')
    Log2.write(ID + '\n')
    #api.update_status(status= ReTweet)
    api.retweet(id=ID)
    api.create_favorite(id=ID, include_entities=True)
    #randomize the time for sleep 1.5mins to 5 mins
    rant = random.randrange(tMin, tMax, tStep)
    time.sleep(rant)
def lambda_handler(event, context):
    APP_KEY = ''  # Customer Key here
    APP_SECRET = ''  # Customer secret here
    OAUTH_TOKEN = ''  # Access Token here
    OAUTH_TOKEN_SECRET = ''  # Access Token Secret here

    # Instantiate an object
    twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)

    # Create our query
    query = {
        'q': '@your_twitter_handler',
        'result_type': 'recent',
        'count': 20,
        'lang': 'en',
    }

    for status in twitter.search(**query)['statuses']:
        print(status)
        timestamp = status['created_at']
        tweet = status['text']
        favourite_count = status['favorite_count']
        user = status['user']['screen_name']

        sentiment = json.loads(getSentiment(tweet))
        print('Tweet Sentiment:' + sentiment['Sentiment'])

        #If the sentiment is positive or neutral, like(favourite) the tweet
        if sentiment['Sentiment'] == 'POSITIVE' or sentiment[
                'Sentiment'] == 'NEUTRAL':
            id = status['id']
            print('Sending Like/Favourite: ' + tweet)
            twitter.create_favorite(id=id)

    return ''
Exemple #3
0
class Termeet(object):
    
    def __init__(self):
        tokens = user_info[0]['keys']
        try:
            self.api = Twython(
                consts.keys['API_KEY'],
                consts.keys['API_SECRET'],
                tokens['access_token'],
                tokens['access_token_secret'],
            )
        except:
            log("Error")
        self.tl = []
    
    def txtupdate(self, text):
        try:
            self.api.update_status(status=text)
        except twython.exceptions.TwythonError as e:
            print("Couldn't update status due to")
            print(e.msg)
    
    def gettimeline(self, n=20):
        if self.tl:
            newupdates = self.api.get_home_timeline(since_id=self.tl[0]['id'])
        else : newupdates = self.api.get_home_timeline(count=n)
        self.tl = newupdates + self.tl
        for (i,tw) in enumerate(self.tl[:n]):
            print(str(i).rjust(3)+pprinter.pptweet(tw))
    
    def fav(self,tlnumber):
        try:
            twid = self.tl[tlnumber]['id']
        except IndexError:
            print("no index")
            return
        self.api.create_favorite(id=twid)
    
    def mainloop(self):
        while True:
            body = None
            try:
                cmd = input(' > ')
            except EOFError as e:
                print()
                break
            if ' ' in cmd:
                body = cmd[cmd.find(' ')+1:]
                cmd = cmd[:cmd.find(' ')]
            print("#####{}#####".format(cmd))
            if cmd == 'tw':
                self.txtupdate(body)
            elif cmd == 'ls':
                self.gettimeline(body)
            elif cmd == 'f':
                ids = body.split(' ')
                for i in ids:
                    self.fav(int(i))
            elif cmd == ':q':
                break
def RT(ID, name):
    """Function that actually retweets tweet"""
    """Takes a ID and username parameter"""
    """Once tweeted log is updated in overall and to date tweetlog"""
    
    config = config_create()
    print("RT")
    #Tid = int(float(ID))
    Tweetusername = config.get('Auth', 'botname')
    #TweetText = 'https://twitter.com/'+Tweetusername+'/status/'+ID
    #ReTweet = 'Hi I am ComicTweetBot!('+tim+') I Retweet Comics! Use #comicretweetbot '+TweetText
    x2 = config.get('Latest_Log', 'currenttweetlog')
    x3 = config.get('Latest_Log', 'overalllog')
    CONSUMER_KEY =  config.get('Auth', 'CONSUMER_KEY') 
    CONSUMER_SECRET = config.get('Auth', 'CONSUMER_SECRET')
    ACCESS_KEY = config.get('Auth', 'ACCESS_KEY')
    ACCESS_SECRET = config.get('Auth', 'ACCESS_SECRET')
    api = Twython(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_KEY, ACCESS_SECRET)
    tMax = int(float(config.get('Tweet_Delay', 'Max')))
    tMin = int(float(config.get('Tweet_Delay', 'Min')))
    tStep = int(float(config.get('Tweet_Delay', 'Step')))
    Log = open(x2, 'w')
    enterlog = ID+' '+name+ '\n'
    Log.write(enterlog)
    Log2 = open(x3, 'w')
    Log2.write(ID+'\n')
    #api.update_status(status= ReTweet)
    api.retweet(id = ID)
    api.create_favorite(id=ID, include_entities = True)
    #randomize the time for sleep 1.5mins to 5 mins
    rant = random.randrange(tMin, tMax, tStep)
    time.sleep(rant)
class TwitterInterface:
    __instance = None

    def __init__(self):
        if TwitterInterface.__instance is not None:
            raise RuntimeError(
                'You can create only one instance of TweetCollector')
        else:
            self.twitter = Twython(os.environ["CONSUMER_KEY"],
                                   os.environ["CONSUMER_SECRET"],
                                   os.environ["ACCESS_TOKEN"],
                                   os.environ["ACCESS_TOKEN_SECRET"])
            TwitterInterface.__instance = self

    @staticmethod
    def get_instance():
        if TwitterInterface.__instance is None:
            TwitterInterface()
        return TwitterInterface.__instance

    def get_tweets(self):
        try:
            collection = self.twitter.search(q='futurehome')
        except TwythonError as err:
            print_error('Twitter API search failed. {}'.format(err))
            return {
                "status_code": err.error_code,
                "message": TWITTER_HTTP_STATUS_CODE[err.error_code]
            }
        else:
            tweets = collection['statuses']
            return tweets

    def retweet(self, tweet_id):
        try:
            self.twitter.retweet(id=tweet_id)
        except TwythonError as err:
            print_error('Twitter API retweet failed. {}'.format(err))
            return {
                "status_code": err.error_code,
                "message": TWITTER_HTTP_STATUS_CODE[err.error_code]
            }

    def favorite(self, tweet_id):
        try:
            self.twitter.create_favorite(id=tweet_id)
        except TwythonError as err:
            print_error('Twitter API favorite failed. {}'.format(err))
            return {
                "status_code": err.error_code,
                "message": TWITTER_HTTP_STATUS_CODE[err.error_code]
            }
def twitter():
    tpath = os.path.join(os.path.dirname(os.path.realpath('fiverr.exe')), 'tweets.txt')
    tweetstosend = open(tpath).readlines()
    newUsers = []
    config = ConfigParser.ConfigParser()
    config.read(path)
    current_action = config.get("Settings", "Action")
# --------------------------------Twython Authorization-----------------------------------   
    t = Twython(app_key=consumer_key, 
        app_secret=consumer_secret, 
        oauth_token=access_token_key, 
        oauth_token_secret=access_token_secret)
# --------------------------------Hashtag Parsing-----------------------------------
    actions = []
    current_hashtag = config.get("Settings", "Hashtag")
    current_action = config.get("Settings", "Action")
    current_action = current_action[1:len(current_action)-1].split(',')
    #current_action = current_action.split(',')
    for i in current_action:
        actions.append(i.lstrip())
    print actions
    search = t.search(q='#'+current_hashtag,count=100)
    tweets = search['statuses']
    for tweet in tweets:
        username = str(tweet['user']['screen_name'])
        if username not in users and username not in newUsers: #Has the user been accounted for?
                newUsers.append(username)
                print 'User added: ' + username
                print actions
                try:
                    for action in actions:
                        print action
                        if action == ("'Retweet'"):
                            t.retweet(id = tweet['id_str'])
                            print 'retweeted'
                        if action == "'Favorite'":
                            t.create_favorite(id = tweet['id_str'])
                            print 'favorited'
                        if action == "'Tweet'":
                            t.update_status(status="@{0} {1}".format(username, random.choice(tweetstosend)))
                            print 'tweeted'
                        if action == "'Follow'":
                            t.create_friendship(screen_name = username)
                            print 'followed'
                except:
                    print "NULL"
    tweetedUsers = "\n".join(newUsers)
    file = open(uLpath, 'a')
    file.write(tweetedUsers + '\n')
    file.close()
    time.sleep(1800)
Exemple #7
0
class TwitterClient:
    def __init__(self):
        self.twitter = Twython(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_TOKEN,
                               ACCESS_TOKEN_SECRET)
        super().__init__()

    def delete_tweet(self, user: User, tweet):
        twitter = Twython(CONSUMER_KEY, CONSUMER_SECRET,
                          user.twitter.access_token, user.twitter.secret)

        return twitter.destroy_status(id=tweet['id_str'])

    def get_unread_tweets(self):
        tweets = self.twitter.get_mentions_timeline(count=10)

        return list(filter(lambda t: t['favorited'] == False, tweets))

    def create_favorite(self, tweet):
        return self.twitter.create_favorite(id=tweet['id'])

    def content_format(self, tasks: List[Task], removes: List[Task] = []):
        content = ''

        for task, status in removes:
            content += task.name + ' ' + status.name.capitalize() + '\n'

        content += '#TASK334\n'
        content += '\n'.join(
            [f"{i+1}.{task.name}" for i, task in enumerate(tasks)])

        return content

    def tweet(self, user: User, content):
        latest_tweet_id = self.get_latest_tweet_id(user)

        twitter = Twython(CONSUMER_KEY, CONSUMER_SECRET,
                          user.twitter.access_token, user.twitter.secret)

        if latest_tweet_id:
            tweet = twitter.update_status(
                status=content,
                in_reply_to_status_id=latest_tweet_id,
                auto_populate_reply_metadata=True)
        else:
            tweet = twitter.update_status(status=content)

        return tweet

    def tweet_tasks(self,
                    user: User,
                    tasks: List[Task],
                    removes: List[Task] = []):
        content = self.content_format(tasks, removes)
        return self.tweet(user, content)

    def reply(self, tweet, content):
        return self.twitter.update_status(
            status=content,
            in_reply_to_status_id=tweet['id_str'],
            auto_populate_reply_metadata=True)
Exemple #8
0
def re_tweet_a_user_status(event, context):
    event_string = json.dumps(event)
    data = json.loads(event_string)
    # Reading the inputs from the event
    retweet_from_user_id = data['retweet_from_user_id']
    interested_hashtag = data['tweet_hashtag']
    time_line_count = data['time_line_count']

    # calling the method to read the twitter secret from S3
    secret_bag = read_twitter_secrets_from_s3(
        bucket_name=os.environ['AUTO_RETWEET_BUCKET'],
        file_name=os.environ['FILE_NAME'],
        region_name=os.environ['S3_REGION'])
    app_key = secret_bag['consumer_key']
    app_secret = secret_bag['consumer_secret']
    oauth_token = secret_bag['oauth_token']
    oauth_token_secret = secret_bag['oauth_token_secret']

    twitter = Twython(app_key, app_secret, oauth_token, oauth_token_secret)

    if len(interested_hashtag) != 0:
        user_timelines = twitter.get_user_timeline(
            screen_name=retweet_from_user_id,
            count=time_line_count,
            trim_user="******",
            exclude_replies="true",
            include_rts="false",
            tweet_mode="extended")
        for user_time_line in user_timelines:
            if interested_hashtag in user_time_line['full_text']:
                print(user_time_line['full_text'])
                twitter.retweet(
                    status="RETWEET FROM MY PERSONAL BOT ASSISTANT",
                    id=user_time_line['id'])
                twitter.create_favorite(id=user_time_line['id'])

    return "BOT FINISHED RE-TWEET SUCCESSFULLY"
Exemple #9
0
class TwythonEndpointsTestCase(unittest.TestCase):
    def setUp(self):

        client_args = {
            'headers': {
                'User-Agent': '__twython__ Test'
            },
            'allow_redirects': False
        }

        # This is so we can hit coverage that Twython sets
        # User-Agent for us if none is supplied
        oauth2_client_args = {
            'headers': {}
        }

        self.api = Twython(app_key, app_secret,
                           oauth_token, oauth_token_secret,
                           client_args=client_args)

        self.oauth2_api = Twython(app_key, access_token=access_token,
                                  client_args=oauth2_client_args)

    # Timelines
    @unittest.skip('skipping non-updated test')
    def test_get_mentions_timeline(self):
        """Test returning mentions timeline for authenticated user succeeds"""
        self.api.get_mentions_timeline()

    @unittest.skip('skipping non-updated test')
    def test_get_user_timeline(self):
        """Test returning timeline for authenticated user and random user
        succeeds"""
        self.api.get_user_timeline()  # Authenticated User Timeline
        self.api.get_user_timeline(screen_name='twitter')
        # Random User Timeline

    @unittest.skip('skipping non-updated test')
    def test_get_protected_user_timeline_following(self):
        """Test returning a protected user timeline who you are following
        succeeds"""
        self.api.get_user_timeline(screen_name=protected_twitter_1)

    @unittest.skip('skipping non-updated test')
    def test_get_protected_user_timeline_not_following(self):
        """Test returning a protected user timeline who you are not following
        fails and raise a TwythonAuthError"""
        self.assertRaises(TwythonAuthError, self.api.get_user_timeline,
                          screen_name=protected_twitter_2)

    @unittest.skip('skipping non-updated test')
    def test_retweeted_of_me(self):
        """Test that getting recent tweets by authenticated user that have
        been retweeted by others succeeds"""
        self.api.retweeted_of_me()

    @unittest.skip('skipping non-updated test')
    def test_get_home_timeline(self):
        """Test returning home timeline for authenticated user succeeds"""
        self.api.get_home_timeline()

    # Tweets
    @unittest.skip('skipping non-updated test')
    def test_get_retweets(self):
        """Test getting retweets of a specific tweet succeeds"""
        self.api.get_retweets(id=test_tweet_id)

    @unittest.skip('skipping non-updated test')
    def test_show_status(self):
        """Test returning a single status details succeeds"""
        self.api.show_status(id=test_tweet_id)

    @unittest.skip('skipping non-updated test')
    def test_update_and_destroy_status(self):
        """Test updating and deleting a status succeeds"""
        status = self.api.update_status(status='Test post just to get \
                    deleted :( %s' % int(time.time()))
        self.api.destroy_status(id=status['id_str'])

    @unittest.skip('skipping non-updated test')
    def test_get_oembed_tweet(self):
        """Test getting info to embed tweet on Third Party site succeeds"""
        self.api.get_oembed_tweet(id='99530515043983360')

    @unittest.skip('skipping non-updated test')
    def test_get_retweeters_ids(self):
        """Test getting ids for people who retweeted a tweet succeeds"""
        self.api.get_retweeters_ids(id='99530515043983360')

    # Search
    @unittest.skip('skipping non-updated test')
    def test_search(self):
        """Test searching tweets succeeds"""
        self.api.search(q='twitter')

    # Direct Messages
    @unittest.skip('skipping non-updated test')
    def test_get_direct_messages(self):
        """Test getting the authenticated users direct messages succeeds"""
        self.api.get_direct_messages()

    @unittest.skip('skipping non-updated test')
    def test_get_sent_messages(self):
        """Test getting the authenticated users direct messages they've
        sent succeeds"""
        self.api.get_sent_messages()

    @unittest.skip('skipping non-updated test')
    def test_send_get_and_destroy_direct_message(self):
        """Test sending, getting, then destory a direct message succeeds"""
        message = self.api.send_direct_message(screen_name=protected_twitter_1,
                                               text='Hey d00d! %s\
                                               ' % int(time.time()))

        self.api.get_direct_message(id=message['id_str'])
        self.api.destroy_direct_message(id=message['id_str'])

    @unittest.skip('skipping non-updated test')
    def test_send_direct_message_to_non_follower(self):
        """Test sending a direct message to someone who doesn't follow you
        fails"""
        self.assertRaises(TwythonError, self.api.send_direct_message,
                          screen_name=protected_twitter_2, text='Yo, man! \
                          %s' % int(time.time()))

    # Friends & Followers
    @unittest.skip('skipping non-updated test')
    def test_get_user_ids_of_blocked_retweets(self):
        """Test that collection of user_ids that the authenticated user does
        not want to receive retweets from succeeds"""
        self.api.get_user_ids_of_blocked_retweets(stringify_ids=True)

    @unittest.skip('skipping non-updated test')
    def test_get_friends_ids(self):
        """Test returning ids of users the authenticated user and then a random
        user is following succeeds"""
        self.api.get_friends_ids()
        self.api.get_friends_ids(screen_name='twitter')

    @unittest.skip('skipping non-updated test')
    def test_get_followers_ids(self):
        """Test returning ids of users the authenticated user and then a random
        user are followed by succeeds"""
        self.api.get_followers_ids()
        self.api.get_followers_ids(screen_name='twitter')

    @unittest.skip('skipping non-updated test')
    def test_lookup_friendships(self):
        """Test returning relationships of the authenticating user to the
        comma-separated list of up to 100 screen_names or user_ids provided
        succeeds"""
        self.api.lookup_friendships(screen_name='twitter,ryanmcgrath')

    @unittest.skip('skipping non-updated test')
    def test_get_incoming_friendship_ids(self):
        """Test returning incoming friendship ids succeeds"""
        self.api.get_incoming_friendship_ids()

    @unittest.skip('skipping non-updated test')
    def test_get_outgoing_friendship_ids(self):
        """Test returning outgoing friendship ids succeeds"""
        self.api.get_outgoing_friendship_ids()

    @unittest.skip('skipping non-updated test')
    def test_create_friendship(self):
        """Test creating a friendship succeeds"""
        self.api.create_friendship(screen_name='justinbieber')

    @unittest.skip('skipping non-updated test')
    def test_destroy_friendship(self):
        """Test destroying a friendship succeeds"""
        self.api.destroy_friendship(screen_name='justinbieber')

    @unittest.skip('skipping non-updated test')
    def test_update_friendship(self):
        """Test updating friendships succeeds"""
        self.api.update_friendship(screen_name=protected_twitter_1,
                                   retweets='true')

        self.api.update_friendship(screen_name=protected_twitter_1,
                                   retweets=False)

    @unittest.skip('skipping non-updated test')
    def test_show_friendships(self):
        """Test showing specific friendship succeeds"""
        self.api.show_friendship(target_screen_name=protected_twitter_1)

    @unittest.skip('skipping non-updated test')
    def test_get_friends_list(self):
        """Test getting list of users authenticated user then random user is
        following succeeds"""
        self.api.get_friends_list()
        self.api.get_friends_list(screen_name='twitter')

    @unittest.skip('skipping non-updated test')
    def test_get_followers_list(self):
        """Test getting list of users authenticated user then random user are
        followed by succeeds"""
        self.api.get_followers_list()
        self.api.get_followers_list(screen_name='twitter')

    # Users
    @unittest.skip('skipping non-updated test')
    def test_get_account_settings(self):
        """Test getting the authenticated user account settings succeeds"""
        self.api.get_account_settings()

    @unittest.skip('skipping non-updated test')
    def test_verify_credentials(self):
        """Test representation of the authenticated user call succeeds"""
        self.api.verify_credentials()

    @unittest.skip('skipping non-updated test')
    def test_update_account_settings(self):
        """Test updating a user account settings succeeds"""
        self.api.update_account_settings(lang='en')

    @unittest.skip('skipping non-updated test')
    def test_update_delivery_service(self):
        """Test updating delivery settings fails because we don't have
        a mobile number on the account"""
        self.assertRaises(TwythonError, self.api.update_delivery_service,
                          device='none')

    @unittest.skip('skipping non-updated test')
    def test_update_profile(self):
        """Test updating profile succeeds"""
        self.api.update_profile(include_entities='true')

    @unittest.skip('skipping non-updated test')
    def test_update_profile_colors(self):
        """Test updating profile colors succeeds"""
        self.api.update_profile_colors(profile_background_color='3D3D3D')

    @unittest.skip('skipping non-updated test')
    def test_list_blocks(self):
        """Test listing users who are blocked by the authenticated user
        succeeds"""
        self.api.list_blocks()

    @unittest.skip('skipping non-updated test')
    def test_list_block_ids(self):
        """Test listing user ids who are blocked by the authenticated user
        succeeds"""
        self.api.list_block_ids()

    @unittest.skip('skipping non-updated test')
    def test_create_block(self):
        """Test blocking a user succeeds"""
        self.api.create_block(screen_name='justinbieber')

    @unittest.skip('skipping non-updated test')
    def test_destroy_block(self):
        """Test unblocking a user succeeds"""
        self.api.destroy_block(screen_name='justinbieber')

    @unittest.skip('skipping non-updated test')
    def test_lookup_user(self):
        """Test listing a number of user objects succeeds"""
        self.api.lookup_user(screen_name='twitter,justinbieber')

    @unittest.skip('skipping non-updated test')
    def test_show_user(self):
        """Test showing one user works"""
        self.api.show_user(screen_name='twitter')

    @unittest.skip('skipping non-updated test')
    def test_search_users(self):
        """Test that searching for users succeeds"""
        self.api.search_users(q='Twitter API')

    @unittest.skip('skipping non-updated test')
    def test_get_contributees(self):
        """Test returning list of accounts the specified user can
        contribute to succeeds"""
        self.api.get_contributees(screen_name='TechCrunch')

    @unittest.skip('skipping non-updated test')
    def test_get_contributors(self):
        """Test returning list of accounts that contribute to the
        authenticated user fails because we are not a Contributor account"""
        self.assertRaises(TwythonError, self.api.get_contributors,
                          screen_name=screen_name)

    @unittest.skip('skipping non-updated test')
    def test_remove_profile_banner(self):
        """Test removing profile banner succeeds"""
        self.api.remove_profile_banner()

    @unittest.skip('skipping non-updated test')
    def test_get_profile_banner_sizes(self):
        """Test getting list of profile banner sizes fails because
        we have not uploaded a profile banner"""
        self.assertRaises(TwythonError, self.api.get_profile_banner_sizes)

    @unittest.skip('skipping non-updated test')
    def test_list_mutes(self):
        """Test listing users who are muted by the authenticated user
        succeeds"""
        self.api.list_mutes()

    @unittest.skip('skipping non-updated test')
    def test_list_mute_ids(self):
        """Test listing user ids who are muted by the authenticated user
        succeeds"""
        self.api.list_mute_ids()

    @unittest.skip('skipping non-updated test')
    def test_create_mute(self):
        """Test muting a user succeeds"""
        self.api.create_mute(screen_name='justinbieber')

    @unittest.skip('skipping non-updated test')
    def test_destroy_mute(self):
        """Test muting a user succeeds"""
        self.api.destroy_mute(screen_name='justinbieber')

    # Suggested Users
    @unittest.skip('skipping non-updated test')
    def test_get_user_suggestions_by_slug(self):
        """Test getting user suggestions by slug succeeds"""
        self.api.get_user_suggestions_by_slug(slug='twitter')

    @unittest.skip('skipping non-updated test')
    def test_get_user_suggestions(self):
        """Test getting user suggestions succeeds"""
        self.api.get_user_suggestions()

    @unittest.skip('skipping non-updated test')
    def test_get_user_suggestions_statuses_by_slug(self):
        """Test getting status of suggested users succeeds"""
        self.api.get_user_suggestions_statuses_by_slug(slug='funny')

    # Favorites
    @unittest.skip('skipping non-updated test')
    def test_get_favorites(self):
        """Test getting list of favorites for the authenticated
        user succeeds"""
        self.api.get_favorites()

    @unittest.skip('skipping non-updated test')
    def test_create_and_destroy_favorite(self):
        """Test creating and destroying a favorite on a tweet succeeds"""
        self.api.create_favorite(id=test_tweet_id)
        self.api.destroy_favorite(id=test_tweet_id)

    # Lists
    @unittest.skip('skipping non-updated test')
    def test_show_lists(self):
        """Test show lists for specified user"""
        self.api.show_lists(screen_name='twitter')

    @unittest.skip('skipping non-updated test')
    def test_get_list_statuses(self):
        """Test timeline of tweets authored by members of the
        specified list succeeds"""
        self.api.get_list_statuses(slug=test_list_slug,
                                   owner_screen_name=test_list_owner_screen_name)

    @unittest.skip('skipping non-updated test')
    def test_create_update_destroy_list_add_remove_list_members(self):
        """Test create a list, adding and removing members then
        deleting the list succeeds"""
        the_list = self.api.create_list(name='Stuff %s' % int(time.time()))
        list_id = the_list['id_str']

        self.api.update_list(list_id=list_id, name='Stuff Renamed \
                             %s' % int(time.time()))

        screen_names = ['johncena', 'xbox']
        # Multi add/delete members
        self.api.create_list_members(list_id=list_id,
                                     screen_name=screen_names)
        self.api.delete_list_members(list_id=list_id,
                                     screen_name=screen_names)

        # Single add/delete member
        self.api.add_list_member(list_id=list_id, screen_name='justinbieber')
        self.api.delete_list_member(list_id=list_id,
                                    screen_name='justinbieber')

        self.api.delete_list(list_id=list_id)

    @unittest.skip('skipping non-updated test')
    def test_get_list_memberships(self):
        """Test list of memberhips the authenticated user succeeds"""
        self.api.get_list_memberships()

    @unittest.skip('skipping non-updated test')
    def test_get_list_subscribers(self):
        """Test list of subscribers of a specific list succeeds"""
        self.api.get_list_subscribers(slug=test_list_slug,
                                      owner_screen_name=test_list_owner_screen_name)

    @unittest.skip('skipping non-updated test')
    def test_subscribe_is_subbed_and_unsubscribe_to_list(self):
        """Test subscribing, is a list sub and unsubbing to list succeeds"""
        self.api.subscribe_to_list(slug=test_list_slug,
                                   owner_screen_name=test_list_owner_screen_name)
        # Returns 404 if user is not a subscriber
        self.api.is_list_subscriber(slug=test_list_slug,
                                    owner_screen_name=test_list_owner_screen_name,
                                    screen_name=screen_name)
        self.api.unsubscribe_from_list(slug=test_list_slug,
                                       owner_screen_name=test_list_owner_screen_name)

    @unittest.skip('skipping non-updated test')
    def test_is_list_member(self):
        """Test returning if specified user is member of a list succeeds"""
        # Returns 404 if not list member
        self.api.is_list_member(slug=test_list_slug,
                                owner_screen_name=test_list_owner_screen_name,
                                screen_name='themattharris')

    @unittest.skip('skipping non-updated test')
    def test_get_list_members(self):
        """Test listing members of the specified list succeeds"""
        self.api.get_list_members(slug=test_list_slug,
                                  owner_screen_name=test_list_owner_screen_name)

    @unittest.skip('skipping non-updated test')
    def test_get_specific_list(self):
        """Test getting specific list succeeds"""
        self.api.get_specific_list(slug=test_list_slug,
                                   owner_screen_name=test_list_owner_screen_name)

    @unittest.skip('skipping non-updated test')
    def test_get_list_subscriptions(self):
        """Test collection of the lists the specified user is
        subscribed to succeeds"""
        self.api.get_list_subscriptions(screen_name='twitter')

    @unittest.skip('skipping non-updated test')
    def test_show_owned_lists(self):
        """Test collection of lists the specified user owns succeeds"""
        self.api.show_owned_lists(screen_name='twitter')

    # Saved Searches
    @unittest.skip('skipping non-updated test')
    def test_get_saved_searches(self):
        """Test getting list of saved searches for authenticated
        user succeeds"""
        self.api.get_saved_searches()

    @unittest.skip('skipping non-updated test')
    def test_create_get_destroy_saved_search(self):
        """Test getting list of saved searches for authenticated
        user succeeds"""
        saved_search = self.api.create_saved_search(query='#Twitter')
        saved_search_id = saved_search['id_str']

        self.api.show_saved_search(id=saved_search_id)
        self.api.destroy_saved_search(id=saved_search_id)

    # Places & Geo
    @unittest.skip('skipping non-updated test')
    def test_get_geo_info(self):
        """Test getting info about a geo location succeeds"""
        self.api.get_geo_info(place_id='df51dec6f4ee2b2c')

    @unittest.skip('skipping non-updated test')
    def test_reverse_geo_code(self):
        """Test reversing geocode succeeds"""
        self.api.reverse_geocode(lat='37.76893497', long='-122.42284884')

    @unittest.skip('skipping non-updated test')
    def test_search_geo(self):
        """Test search for places that can be attached
        to a statuses/update succeeds"""
        self.api.search_geo(query='Toronto')

    @unittest.skip('skipping non-updated test')
    def test_get_similar_places(self):
        """Test locates places near the given coordinates which
        are similar in name succeeds"""
        self.api.get_similar_places(lat='37', long='-122', name='Twitter HQ')

    # Trends
    @unittest.skip('skipping non-updated test')
    def test_get_place_trends(self):
        """Test getting the top 10 trending topics for a specific
        WOEID succeeds"""
        self.api.get_place_trends(id=1)

    @unittest.skip('skipping non-updated test')
    def test_get_available_trends(self):
        """Test returning locations that Twitter has trending
        topic information for succeeds"""
        self.api.get_available_trends()

    @unittest.skip('skipping non-updated test')
    def test_get_closest_trends(self):
        """Test getting the locations that Twitter has trending topic
        information for, closest to a specified location succeeds"""
        self.api.get_closest_trends(lat='37', long='-122')

    # Help
    @unittest.skip('skipping non-updated test')
    def test_get_twitter_configuration(self):
        """Test getting Twitter's configuration succeeds"""
        self.api.get_twitter_configuration()

    @unittest.skip('skipping non-updated test')
    def test_get_supported_languages(self):
        """Test getting languages supported by Twitter succeeds"""
        self.api.get_supported_languages()

    @unittest.skip('skipping non-updated test')
    def test_privacy_policy(self):
        """Test getting Twitter's Privacy Policy succeeds"""
        self.api.get_privacy_policy()

    @unittest.skip('skipping non-updated test')
    def test_get_tos(self):
        """Test getting the Twitter Terms of Service succeeds"""
        self.api.get_tos()

    @unittest.skip('skipping non-updated test')
    def test_get_application_rate_limit_status(self):
        """Test getting application rate limit status succeeds"""
        self.oauth2_api.get_application_rate_limit_status()
Exemple #10
0
class TwythonEndpointsTestCase(unittest.TestCase):
    def setUp(self):

        client_args = {
            'headers': {
                'User-Agent': '__twython__ Test'
            },
            'allow_redirects': False
        }

        oauth2_client_args = {
            'headers': {}  # This is so we can hit coverage that Twython sets User-Agent for us if none is supplied
        }

        self.api = Twython(app_key, app_secret,
                           oauth_token, oauth_token_secret,
                           client_args=client_args)

        self.oauth2_api = Twython(app_key, access_token=access_token,
                                  client_args=oauth2_client_args)

    # Timelines
    @unittest.skip('skipping non-updated test')
    def test_get_mentions_timeline(self):
        """Test returning mentions timeline for authenticated user succeeds"""
        self.api.get_mentions_timeline()

    @unittest.skip('skipping non-updated test')
    def test_get_user_timeline(self):
        """Test returning timeline for authenticated user and random user
        succeeds"""
        self.api.get_user_timeline()  # Authenticated User Timeline
        self.api.get_user_timeline(screen_name='twitter')  # Random User Timeline

    @unittest.skip('skipping non-updated test')
    def test_get_protected_user_timeline_following(self):
        """Test returning a protected user timeline who you are following
        succeeds"""
        self.api.get_user_timeline(screen_name=protected_twitter_1)

    @unittest.skip('skipping non-updated test')
    def test_get_protected_user_timeline_not_following(self):
        """Test returning a protected user timeline who you are not following
        fails and raise a TwythonAuthError"""
        self.assertRaises(TwythonAuthError, self.api.get_user_timeline,
                          screen_name=protected_twitter_2)

    @unittest.skip('skipping non-updated test')
    def test_retweeted_of_me(self):
        """Test that getting recent tweets by authenticated user that have
        been retweeted by others succeeds"""
        self.api.retweeted_of_me()

    @unittest.skip('skipping non-updated test')
    def test_get_home_timeline(self):
        """Test returning home timeline for authenticated user succeeds"""
        self.api.get_home_timeline()

    # Tweets
    @unittest.skip('skipping non-updated test')
    def test_get_retweets(self):
        """Test getting retweets of a specific tweet succeeds"""
        self.api.get_retweets(id=test_tweet_id)

    @unittest.skip('skipping non-updated test')
    def test_show_status(self):
        """Test returning a single status details succeeds"""
        self.api.show_status(id=test_tweet_id)

    @unittest.skip('skipping non-updated test')
    def test_update_and_destroy_status(self):
        """Test updating and deleting a status succeeds"""
        status = self.api.update_status(status='Test post just to get deleted :( %s' % int(time.time()))
        self.api.destroy_status(id=status['id_str'])

    @unittest.skip('skipping non-updated test')
    def test_get_oembed_tweet(self):
        """Test getting info to embed tweet on Third Party site succeeds"""
        self.api.get_oembed_tweet(id='99530515043983360')

    @unittest.skip('skipping non-updated test')
    def test_get_retweeters_ids(self):
        """Test getting ids for people who retweeted a tweet succeeds"""
        self.api.get_retweeters_ids(id='99530515043983360')

    # Search
    @unittest.skip('skipping non-updated test')
    def test_search(self):
        """Test searching tweets succeeds"""
        self.api.search(q='twitter')

    # Direct Messages
    @unittest.skip('skipping non-updated test')
    def test_get_direct_messages(self):
        """Test getting the authenticated users direct messages succeeds"""
        self.api.get_direct_messages()

    @unittest.skip('skipping non-updated test')
    def test_get_sent_messages(self):
        """Test getting the authenticated users direct messages they've
        sent succeeds"""
        self.api.get_sent_messages()

    @unittest.skip('skipping non-updated test')
    def test_send_get_and_destroy_direct_message(self):
        """Test sending, getting, then destory a direct message succeeds"""
        message = self.api.send_direct_message(screen_name=protected_twitter_1,
                                               text='Hey d00d! %s' % int(time.time()))

        self.api.get_direct_message(id=message['id_str'])
        self.api.destroy_direct_message(id=message['id_str'])

    @unittest.skip('skipping non-updated test')
    def test_send_direct_message_to_non_follower(self):
        """Test sending a direct message to someone who doesn't follow you
        fails"""
        self.assertRaises(TwythonError, self.api.send_direct_message,
                          screen_name=protected_twitter_2, text='Yo, man! %s' % int(time.time()))

    # Friends & Followers
    @unittest.skip('skipping non-updated test')
    def test_get_user_ids_of_blocked_retweets(self):
        """Test that collection of user_ids that the authenticated user does
        not want to receive retweets from succeeds"""
        self.api.get_user_ids_of_blocked_retweets(stringify_ids=True)

    @unittest.skip('skipping non-updated test')
    def test_get_friends_ids(self):
        """Test returning ids of users the authenticated user and then a random
        user is following succeeds"""
        self.api.get_friends_ids()
        self.api.get_friends_ids(screen_name='twitter')

    @unittest.skip('skipping non-updated test')
    def test_get_followers_ids(self):
        """Test returning ids of users the authenticated user and then a random
        user are followed by succeeds"""
        self.api.get_followers_ids()
        self.api.get_followers_ids(screen_name='twitter')

    @unittest.skip('skipping non-updated test')
    def test_lookup_friendships(self):
        """Test returning relationships of the authenticating user to the
        comma-separated list of up to 100 screen_names or user_ids provided
        succeeds"""
        self.api.lookup_friendships(screen_name='twitter,ryanmcgrath')

    @unittest.skip('skipping non-updated test')
    def test_get_incoming_friendship_ids(self):
        """Test returning incoming friendship ids succeeds"""
        self.api.get_incoming_friendship_ids()

    @unittest.skip('skipping non-updated test')
    def test_get_outgoing_friendship_ids(self):
        """Test returning outgoing friendship ids succeeds"""
        self.api.get_outgoing_friendship_ids()

    @unittest.skip('skipping non-updated test')
    def test_create_friendship(self):
        """Test creating a friendship succeeds"""
        self.api.create_friendship(screen_name='justinbieber')

    @unittest.skip('skipping non-updated test')
    def test_destroy_friendship(self):
        """Test destroying a friendship succeeds"""
        self.api.destroy_friendship(screen_name='justinbieber')

    @unittest.skip('skipping non-updated test')
    def test_update_friendship(self):
        """Test updating friendships succeeds"""
        self.api.update_friendship(screen_name=protected_twitter_1,
                                   retweets='true')

        self.api.update_friendship(screen_name=protected_twitter_1,
                                   retweets=False)

    @unittest.skip('skipping non-updated test')
    def test_show_friendships(self):
        """Test showing specific friendship succeeds"""
        self.api.show_friendship(target_screen_name=protected_twitter_1)

    @unittest.skip('skipping non-updated test')
    def test_get_friends_list(self):
        """Test getting list of users authenticated user then random user is
        following succeeds"""
        self.api.get_friends_list()
        self.api.get_friends_list(screen_name='twitter')

    @unittest.skip('skipping non-updated test')
    def test_get_followers_list(self):
        """Test getting list of users authenticated user then random user are
        followed by succeeds"""
        self.api.get_followers_list()
        self.api.get_followers_list(screen_name='twitter')

    # Users
    @unittest.skip('skipping non-updated test')
    def test_get_account_settings(self):
        """Test getting the authenticated user account settings succeeds"""
        self.api.get_account_settings()

    @unittest.skip('skipping non-updated test')
    def test_verify_credentials(self):
        """Test representation of the authenticated user call succeeds"""
        self.api.verify_credentials()

    @unittest.skip('skipping non-updated test')
    def test_update_account_settings(self):
        """Test updating a user account settings succeeds"""
        self.api.update_account_settings(lang='en')

    @unittest.skip('skipping non-updated test')
    def test_update_delivery_service(self):
        """Test updating delivery settings fails because we don't have
        a mobile number on the account"""
        self.assertRaises(TwythonError, self.api.update_delivery_service,
                          device='none')

    @unittest.skip('skipping non-updated test')
    def test_update_profile(self):
        """Test updating profile succeeds"""
        self.api.update_profile(include_entities='true')

    @unittest.skip('skipping non-updated test')
    def test_update_profile_colors(self):
        """Test updating profile colors succeeds"""
        self.api.update_profile_colors(profile_background_color='3D3D3D')

    @unittest.skip('skipping non-updated test')
    def test_list_blocks(self):
        """Test listing users who are blocked by the authenticated user
        succeeds"""
        self.api.list_blocks()

    @unittest.skip('skipping non-updated test')
    def test_list_block_ids(self):
        """Test listing user ids who are blocked by the authenticated user
        succeeds"""
        self.api.list_block_ids()

    @unittest.skip('skipping non-updated test')
    def test_create_block(self):
        """Test blocking a user succeeds"""
        self.api.create_block(screen_name='justinbieber')

    @unittest.skip('skipping non-updated test')
    def test_destroy_block(self):
        """Test unblocking a user succeeds"""
        self.api.destroy_block(screen_name='justinbieber')

    @unittest.skip('skipping non-updated test')
    def test_lookup_user(self):
        """Test listing a number of user objects succeeds"""
        self.api.lookup_user(screen_name='twitter,justinbieber')

    @unittest.skip('skipping non-updated test')
    def test_show_user(self):
        """Test showing one user works"""
        self.api.show_user(screen_name='twitter')

    @unittest.skip('skipping non-updated test')
    def test_search_users(self):
        """Test that searching for users succeeds"""
        self.api.search_users(q='Twitter API')

    @unittest.skip('skipping non-updated test')
    def test_get_contributees(self):
        """Test returning list of accounts the specified user can
        contribute to succeeds"""
        self.api.get_contributees(screen_name='TechCrunch')

    @unittest.skip('skipping non-updated test')
    def test_get_contributors(self):
        """Test returning list of accounts that contribute to the
        authenticated user fails because we are not a Contributor account"""
        self.assertRaises(TwythonError, self.api.get_contributors,
                          screen_name=screen_name)

    @unittest.skip('skipping non-updated test')
    def test_remove_profile_banner(self):
        """Test removing profile banner succeeds"""
        self.api.remove_profile_banner()

    @unittest.skip('skipping non-updated test')
    def test_get_profile_banner_sizes(self):
        """Test getting list of profile banner sizes fails because
        we have not uploaded a profile banner"""
        self.assertRaises(TwythonError, self.api.get_profile_banner_sizes)

    # Suggested Users
    @unittest.skip('skipping non-updated test')
    def test_get_user_suggestions_by_slug(self):
        """Test getting user suggestions by slug succeeds"""
        self.api.get_user_suggestions_by_slug(slug='twitter')

    @unittest.skip('skipping non-updated test')
    def test_get_user_suggestions(self):
        """Test getting user suggestions succeeds"""
        self.api.get_user_suggestions()

    @unittest.skip('skipping non-updated test')
    def test_get_user_suggestions_statuses_by_slug(self):
        """Test getting status of suggested users succeeds"""
        self.api.get_user_suggestions_statuses_by_slug(slug='funny')

    # Favorites
    @unittest.skip('skipping non-updated test')
    def test_get_favorites(self):
        """Test getting list of favorites for the authenticated
        user succeeds"""
        self.api.get_favorites()

    @unittest.skip('skipping non-updated test')
    def test_create_and_destroy_favorite(self):
        """Test creating and destroying a favorite on a tweet succeeds"""
        self.api.create_favorite(id=test_tweet_id)
        self.api.destroy_favorite(id=test_tweet_id)

    # Lists
    @unittest.skip('skipping non-updated test')
    def test_show_lists(self):
        """Test show lists for specified user"""
        self.api.show_lists(screen_name='twitter')

    @unittest.skip('skipping non-updated test')
    def test_get_list_statuses(self):
        """Test timeline of tweets authored by members of the
        specified list succeeds"""
        self.api.get_list_statuses(slug=test_list_slug,
                                   owner_screen_name=test_list_owner_screen_name)

    @unittest.skip('skipping non-updated test')
    def test_create_update_destroy_list_add_remove_list_members(self):
        """Test create a list, adding and removing members then
        deleting the list succeeds"""
        the_list = self.api.create_list(name='Stuff %s' % int(time.time()))
        list_id = the_list['id_str']

        self.api.update_list(list_id=list_id, name='Stuff Renamed %s' % int(time.time()))

        screen_names = ['johncena', 'xbox']
        # Multi add/delete members
        self.api.create_list_members(list_id=list_id,
                                     screen_name=screen_names)
        self.api.delete_list_members(list_id=list_id,
                                     screen_name=screen_names)

        # Single add/delete member
        self.api.add_list_member(list_id=list_id, screen_name='justinbieber')
        self.api.delete_list_member(list_id=list_id, screen_name='justinbieber')

        self.api.delete_list(list_id=list_id)

    @unittest.skip('skipping non-updated test')
    def test_get_list_memberships(self):
        """Test list of memberhips the authenticated user succeeds"""
        self.api.get_list_memberships()

    @unittest.skip('skipping non-updated test')
    def test_get_list_subscribers(self):
        """Test list of subscribers of a specific list succeeds"""
        self.api.get_list_subscribers(slug=test_list_slug,
                                      owner_screen_name=test_list_owner_screen_name)

    @unittest.skip('skipping non-updated test')
    def test_subscribe_is_subbed_and_unsubscribe_to_list(self):
        """Test subscribing, is a list sub and unsubbing to list succeeds"""
        self.api.subscribe_to_list(slug=test_list_slug,
                                   owner_screen_name=test_list_owner_screen_name)
        # Returns 404 if user is not a subscriber
        self.api.is_list_subscriber(slug=test_list_slug,
                                    owner_screen_name=test_list_owner_screen_name,
                                    screen_name=screen_name)
        self.api.unsubscribe_from_list(slug=test_list_slug,
                                       owner_screen_name=test_list_owner_screen_name)

    @unittest.skip('skipping non-updated test')
    def test_is_list_member(self):
        """Test returning if specified user is member of a list succeeds"""
        # Returns 404 if not list member
        self.api.is_list_member(slug=test_list_slug,
                                owner_screen_name=test_list_owner_screen_name,
                                screen_name='themattharris')

    @unittest.skip('skipping non-updated test')
    def test_get_list_members(self):
        """Test listing members of the specified list succeeds"""
        self.api.get_list_members(slug=test_list_slug,
                                  owner_screen_name=test_list_owner_screen_name)

    @unittest.skip('skipping non-updated test')
    def test_get_specific_list(self):
        """Test getting specific list succeeds"""
        self.api.get_specific_list(slug=test_list_slug,
                                   owner_screen_name=test_list_owner_screen_name)

    @unittest.skip('skipping non-updated test')
    def test_get_list_subscriptions(self):
        """Test collection of the lists the specified user is
        subscribed to succeeds"""
        self.api.get_list_subscriptions(screen_name='twitter')

    @unittest.skip('skipping non-updated test')
    def test_show_owned_lists(self):
        """Test collection of lists the specified user owns succeeds"""
        self.api.show_owned_lists(screen_name='twitter')

    # Saved Searches
    @unittest.skip('skipping non-updated test')
    def test_get_saved_searches(self):
        """Test getting list of saved searches for authenticated
        user succeeds"""
        self.api.get_saved_searches()

    @unittest.skip('skipping non-updated test')
    def test_create_get_destroy_saved_search(self):
        """Test getting list of saved searches for authenticated
        user succeeds"""
        saved_search = self.api.create_saved_search(query='#Twitter')
        saved_search_id = saved_search['id_str']

        self.api.show_saved_search(id=saved_search_id)
        self.api.destroy_saved_search(id=saved_search_id)

    # Places & Geo
    @unittest.skip('skipping non-updated test')
    def test_get_geo_info(self):
        """Test getting info about a geo location succeeds"""
        self.api.get_geo_info(place_id='df51dec6f4ee2b2c')

    @unittest.skip('skipping non-updated test')
    def test_reverse_geo_code(self):
        """Test reversing geocode succeeds"""
        self.api.reverse_geocode(lat='37.76893497', long='-122.42284884')

    @unittest.skip('skipping non-updated test')
    def test_search_geo(self):
        """Test search for places that can be attached
        to a statuses/update succeeds"""
        self.api.search_geo(query='Toronto')

    @unittest.skip('skipping non-updated test')
    def test_get_similar_places(self):
        """Test locates places near the given coordinates which
        are similar in name succeeds"""
        self.api.get_similar_places(lat='37', long='-122', name='Twitter HQ')

    # Trends
    @unittest.skip('skipping non-updated test')
    def test_get_place_trends(self):
        """Test getting the top 10 trending topics for a specific
        WOEID succeeds"""
        self.api.get_place_trends(id=1)

    @unittest.skip('skipping non-updated test')
    def test_get_available_trends(self):
        """Test returning locations that Twitter has trending
        topic information for succeeds"""
        self.api.get_available_trends()

    @unittest.skip('skipping non-updated test')
    def test_get_closest_trends(self):
        """Test getting the locations that Twitter has trending topic
        information for, closest to a specified location succeeds"""
        self.api.get_closest_trends(lat='37', long='-122')

    # Help
    @unittest.skip('skipping non-updated test')
    def test_get_twitter_configuration(self):
        """Test getting Twitter's configuration succeeds"""
        self.api.get_twitter_configuration()

    @unittest.skip('skipping non-updated test')
    def test_get_supported_languages(self):
        """Test getting languages supported by Twitter succeeds"""
        self.api.get_supported_languages()

    @unittest.skip('skipping non-updated test')
    def test_privacy_policy(self):
        """Test getting Twitter's Privacy Policy succeeds"""
        self.api.get_privacy_policy()

    @unittest.skip('skipping non-updated test')
    def test_get_tos(self):
        """Test getting the Twitter Terms of Service succeeds"""
        self.api.get_tos()

    @unittest.skip('skipping non-updated test')
    def test_get_application_rate_limit_status(self):
        """Test getting application rate limit status succeeds"""
        self.oauth2_api.get_application_rate_limit_status()
Exemple #11
0
class TwythonAPITestCase(unittest.TestCase):
    def setUp(self):

        client_args = {
            'headers': {
                'User-Agent': '__twython__ Test'
            },
            'allow_redirects': False
        }

        oauth2_client_args = {
            'headers': {
            }  # This is so we can hit coverage that Twython sets User-Agent for us if none is supplied
        }

        self.api = Twython(app_key,
                           app_secret,
                           oauth_token,
                           oauth_token_secret,
                           client_args=client_args)

        self.oauth2_api = Twython(app_key,
                                  access_token=access_token,
                                  client_args=oauth2_client_args)

    def test_construct_api_url(self):
        """Test constructing a Twitter API url works as we expect"""
        url = 'https://api.twitter.com/1.1/search/tweets.json'
        constructed_url = self.api.construct_api_url(url, q='#twitter')
        self.assertEqual(
            constructed_url,
            'https://api.twitter.com/1.1/search/tweets.json?q=%23twitter')

    def test_get(self):
        """Test Twython generic GET request works"""
        self.api.get('account/verify_credentials')

    def test_post(self):
        """Test Twython generic POST request works, with a full url and
        with just an endpoint"""
        update_url = 'https://api.twitter.com/1.1/statuses/update.json'
        status = self.api.post(
            update_url,
            params={'status': 'I love Twython! %s' % int(time.time())})
        self.api.post('statuses/destroy/%s' % status['id_str'])

    def test_get_lastfunction_header(self):
        """Test getting last specific header of the last API call works"""
        self.api.get('statuses/home_timeline')
        self.api.get_lastfunction_header('x-rate-limit-remaining')

    def test_get_lastfunction_header_not_present(self):
        """Test getting specific header that does not exist from the last call returns None"""
        self.api.get('statuses/home_timeline')
        header = self.api.get_lastfunction_header('does-not-exist')
        self.assertEqual(header, None)

    def test_get_lastfunction_header_no_last_api_call(self):
        """Test attempting to get a header when no API call was made raises a TwythonError"""
        self.assertRaises(TwythonError, self.api.get_lastfunction_header,
                          'no-api-call-was-made')

    def test_cursor(self):
        """Test looping through the generator results works, at least once that is"""
        search = self.api.cursor(self.api.search, q='twitter', count=1)
        counter = 0
        while counter < 2:
            counter += 1
            result = next(search)
            new_id_str = int(result['id_str'])
            if counter == 1:
                prev_id_str = new_id_str
                time.sleep(
                    1)  # Give time for another tweet to come into search
            if counter == 2:
                self.assertTrue(new_id_str > prev_id_str)

    def test_encode(self):
        """Test encoding UTF-8 works"""
        self.api.encode('Twython is awesome!')

    def test_html_for_tweet(self):
        """Test HTML for Tweet returns what we want"""
        tweet_text = self.api.html_for_tweet(test_tweet_object)
        self.assertEqual(test_tweet_html, tweet_text)

    def test_html_for_tweet_expanded_url(self):
        """Test using expanded url in HTML for Tweet displays full urls"""
        tweet_text = self.api.html_for_tweet(test_tweet_object,
                                             use_expanded_url=True)
        # Make sure full url is in HTML
        self.assertTrue('http://google.com' in tweet_text)

    def test_html_for_tweet_short_url(self):
        """Test using expanded url in HTML for Tweet displays full urls"""
        tweet_text = self.api.html_for_tweet(test_tweet_object, False)
        # Make sure HTML doesn't contain the display OR exapanded url
        self.assertTrue(not 'http://google.com' in tweet_text)
        self.assertTrue(not 'google.com' in tweet_text)

    def test_raise_error_on_bad_ssl_cert(self):
        """Test TwythonError is raised by a RequestException when an actual HTTP happens"""
        self.assertRaises(TwythonError, self.api.get, 'https://example.com')

    # Timelines
    def test_get_mentions_timeline(self):
        """Test returning mentions timeline for authenticated user succeeds"""
        self.api.get_mentions_timeline()

    def test_get_user_timeline(self):
        """Test returning timeline for authenticated user and random user
        succeeds"""
        self.api.get_user_timeline()  # Authenticated User Timeline
        self.api.get_user_timeline(
            screen_name='twitter')  # Random User Timeline

    def test_get_protected_user_timeline_following(self):
        """Test returning a protected user timeline who you are following
        succeeds"""
        self.api.get_user_timeline(screen_name=protected_twitter_1)

    def test_get_protected_user_timeline_not_following(self):
        """Test returning a protected user timeline who you are not following
        fails and raise a TwythonAuthError"""
        self.assertRaises(TwythonAuthError,
                          self.api.get_user_timeline,
                          screen_name=protected_twitter_2)

    def test_retweeted_of_me(self):
        """Test that getting recent tweets by authenticated user that have
        been retweeted by others succeeds"""
        self.api.retweeted_of_me()

    def test_get_home_timeline(self):
        """Test returning home timeline for authenticated user succeeds"""
        self.api.get_home_timeline()

    # Tweets
    def test_get_retweets(self):
        """Test getting retweets of a specific tweet succeeds"""
        self.api.get_retweets(id=test_tweet_id)

    def test_show_status(self):
        """Test returning a single status details succeeds"""
        self.api.show_status(id=test_tweet_id)

    def test_update_and_destroy_status(self):
        """Test updating and deleting a status succeeds"""
        status = self.api.update_status(
            status='Test post just to get deleted :( %s' % int(time.time()))
        self.api.destroy_status(id=status['id_str'])

    def test_get_oembed_tweet(self):
        """Test getting info to embed tweet on Third Party site succeeds"""
        self.api.get_oembed_tweet(id='99530515043983360')

    def test_get_retweeters_ids(self):
        """Test getting ids for people who retweeted a tweet succeeds"""
        self.api.get_retweeters_ids(id='99530515043983360')

    # Search
    def test_search(self):
        """Test searching tweets succeeds"""
        self.api.search(q='twitter')

    # Direct Messages
    def test_get_direct_messages(self):
        """Test getting the authenticated users direct messages succeeds"""
        self.api.get_direct_messages()

    def test_get_sent_messages(self):
        """Test getting the authenticated users direct messages they've
        sent succeeds"""
        self.api.get_sent_messages()

    def test_send_get_and_destroy_direct_message(self):
        """Test sending, getting, then destory a direct message succeeds"""
        message = self.api.send_direct_message(screen_name=protected_twitter_1,
                                               text='Hey d00d! %s' %
                                               int(time.time()))

        self.api.get_direct_message(id=message['id_str'])
        self.api.destroy_direct_message(id=message['id_str'])

    def test_send_direct_message_to_non_follower(self):
        """Test sending a direct message to someone who doesn't follow you
        fails"""
        self.assertRaises(TwythonError,
                          self.api.send_direct_message,
                          screen_name=protected_twitter_2,
                          text='Yo, man! %s' % int(time.time()))

    # Friends & Followers
    def test_get_user_ids_of_blocked_retweets(self):
        """Test that collection of user_ids that the authenticated user does
        not want to receive retweets from succeeds"""
        self.api.get_user_ids_of_blocked_retweets(stringify_ids=True)

    def test_get_friends_ids(self):
        """Test returning ids of users the authenticated user and then a random
        user is following succeeds"""
        self.api.get_friends_ids()
        self.api.get_friends_ids(screen_name='twitter')

    def test_get_followers_ids(self):
        """Test returning ids of users the authenticated user and then a random
        user are followed by succeeds"""
        self.api.get_followers_ids()
        self.api.get_followers_ids(screen_name='twitter')

    def test_lookup_friendships(self):
        """Test returning relationships of the authenticating user to the
        comma-separated list of up to 100 screen_names or user_ids provided
        succeeds"""
        self.api.lookup_friendships(screen_name='twitter,ryanmcgrath')

    def test_get_incoming_friendship_ids(self):
        """Test returning incoming friendship ids succeeds"""
        self.api.get_incoming_friendship_ids()

    def test_get_outgoing_friendship_ids(self):
        """Test returning outgoing friendship ids succeeds"""
        self.api.get_outgoing_friendship_ids()

    def test_create_friendship(self):
        """Test creating a friendship succeeds"""
        self.api.create_friendship(screen_name='justinbieber')

    def test_destroy_friendship(self):
        """Test destroying a friendship succeeds"""
        self.api.destroy_friendship(screen_name='justinbieber')

    def test_update_friendship(self):
        """Test updating friendships succeeds"""
        self.api.update_friendship(screen_name=protected_twitter_1,
                                   retweets='true')

        self.api.update_friendship(screen_name=protected_twitter_1,
                                   retweets=False)

    def test_show_friendships(self):
        """Test showing specific friendship succeeds"""
        self.api.show_friendship(target_screen_name=protected_twitter_1)

    def test_get_friends_list(self):
        """Test getting list of users authenticated user then random user is
        following succeeds"""
        self.api.get_friends_list()
        self.api.get_friends_list(screen_name='twitter')

    def test_get_followers_list(self):
        """Test getting list of users authenticated user then random user are
        followed by succeeds"""
        self.api.get_followers_list()
        self.api.get_followers_list(screen_name='twitter')

    # Users
    def test_get_account_settings(self):
        """Test getting the authenticated user account settings succeeds"""
        self.api.get_account_settings()

    def test_verify_credentials(self):
        """Test representation of the authenticated user call succeeds"""
        self.api.verify_credentials()

    def test_update_account_settings(self):
        """Test updating a user account settings succeeds"""
        self.api.update_account_settings(lang='en')

    def test_update_delivery_service(self):
        """Test updating delivery settings fails because we don't have
        a mobile number on the account"""
        self.assertRaises(TwythonError,
                          self.api.update_delivery_service,
                          device='none')

    def test_update_profile(self):
        """Test updating profile succeeds"""
        self.api.update_profile(include_entities='true')

    def test_update_profile_colors(self):
        """Test updating profile colors succeeds"""
        self.api.update_profile_colors(profile_background_color='3D3D3D')

    def test_list_blocks(self):
        """Test listing users who are blocked by the authenticated user
        succeeds"""
        self.api.list_blocks()

    def test_list_block_ids(self):
        """Test listing user ids who are blocked by the authenticated user
        succeeds"""
        self.api.list_block_ids()

    def test_create_block(self):
        """Test blocking a user succeeds"""
        self.api.create_block(screen_name='justinbieber')

    def test_destroy_block(self):
        """Test unblocking a user succeeds"""
        self.api.destroy_block(screen_name='justinbieber')

    def test_lookup_user(self):
        """Test listing a number of user objects succeeds"""
        self.api.lookup_user(screen_name='twitter,justinbieber')

    def test_show_user(self):
        """Test showing one user works"""
        self.api.show_user(screen_name='twitter')

    def test_search_users(self):
        """Test that searching for users succeeds"""
        self.api.search_users(q='Twitter API')

    def test_get_contributees(self):
        """Test returning list of accounts the specified user can
        contribute to succeeds"""
        self.api.get_contributees(screen_name='TechCrunch')

    def test_get_contributors(self):
        """Test returning list of accounts that contribute to the
        authenticated user fails because we are not a Contributor account"""
        self.assertRaises(TwythonError,
                          self.api.get_contributors,
                          screen_name=screen_name)

    def test_remove_profile_banner(self):
        """Test removing profile banner succeeds"""
        self.api.remove_profile_banner()

    def test_get_profile_banner_sizes(self):
        """Test getting list of profile banner sizes fails because
        we have not uploaded a profile banner"""
        self.assertRaises(TwythonError, self.api.get_profile_banner_sizes)

    # Suggested Users
    def test_get_user_suggestions_by_slug(self):
        """Test getting user suggestions by slug succeeds"""
        self.api.get_user_suggestions_by_slug(slug='twitter')

    def test_get_user_suggestions(self):
        """Test getting user suggestions succeeds"""
        self.api.get_user_suggestions()

    def test_get_user_suggestions_statuses_by_slug(self):
        """Test getting status of suggested users succeeds"""
        self.api.get_user_suggestions_statuses_by_slug(slug='funny')

    # Favorites
    def test_get_favorites(self):
        """Test getting list of favorites for the authenticated
        user succeeds"""
        self.api.get_favorites()

    def test_create_and_destroy_favorite(self):
        """Test creating and destroying a favorite on a tweet succeeds"""
        self.api.create_favorite(id=test_tweet_id)
        self.api.destroy_favorite(id=test_tweet_id)

    # Lists
    def test_show_lists(self):
        """Test show lists for specified user"""
        self.api.show_lists(screen_name='twitter')

    def test_get_list_statuses(self):
        """Test timeline of tweets authored by members of the
        specified list succeeds"""
        self.api.get_list_statuses(
            slug=test_list_slug, owner_screen_name=test_list_owner_screen_name)

    def test_create_update_destroy_list_add_remove_list_members(self):
        """Test create a list, adding and removing members then
        deleting the list succeeds"""
        the_list = self.api.create_list(name='Stuff %s' % int(time.time()))
        list_id = the_list['id_str']

        self.api.update_list(list_id=list_id,
                             name='Stuff Renamed %s' % int(time.time()))

        screen_names = ['johncena', 'xbox']
        # Multi add/delete members
        self.api.create_list_members(list_id=list_id, screen_name=screen_names)
        self.api.delete_list_members(list_id=list_id, screen_name=screen_names)

        # Single add/delete member
        self.api.add_list_member(list_id=list_id, screen_name='justinbieber')
        self.api.delete_list_member(list_id=list_id,
                                    screen_name='justinbieber')

        self.api.delete_list(list_id=list_id)

    def test_get_list_memberships(self):
        """Test list of memberhips the authenticated user succeeds"""
        self.api.get_list_memberships()

    def test_get_list_subscribers(self):
        """Test list of subscribers of a specific list succeeds"""
        self.api.get_list_subscribers(
            slug=test_list_slug, owner_screen_name=test_list_owner_screen_name)

    def test_subscribe_is_subbed_and_unsubscribe_to_list(self):
        """Test subscribing, is a list sub and unsubbing to list succeeds"""
        self.api.subscribe_to_list(
            slug=test_list_slug, owner_screen_name=test_list_owner_screen_name)
        # Returns 404 if user is not a subscriber
        self.api.is_list_subscriber(
            slug=test_list_slug,
            owner_screen_name=test_list_owner_screen_name,
            screen_name=screen_name)
        self.api.unsubscribe_from_list(
            slug=test_list_slug, owner_screen_name=test_list_owner_screen_name)

    def test_is_list_member(self):
        """Test returning if specified user is member of a list succeeds"""
        # Returns 404 if not list member
        self.api.is_list_member(slug=test_list_slug,
                                owner_screen_name=test_list_owner_screen_name,
                                screen_name='themattharris')

    def test_get_list_members(self):
        """Test listing members of the specified list succeeds"""
        self.api.get_list_members(
            slug=test_list_slug, owner_screen_name=test_list_owner_screen_name)

    def test_get_specific_list(self):
        """Test getting specific list succeeds"""
        self.api.get_specific_list(
            slug=test_list_slug, owner_screen_name=test_list_owner_screen_name)

    def test_get_list_subscriptions(self):
        """Test collection of the lists the specified user is
        subscribed to succeeds"""
        self.api.get_list_subscriptions(screen_name='twitter')

    def test_show_owned_lists(self):
        """Test collection of lists the specified user owns succeeds"""
        self.api.show_owned_lists(screen_name='twitter')

    # Saved Searches
    def test_get_saved_searches(self):
        """Test getting list of saved searches for authenticated
        user succeeds"""
        self.api.get_saved_searches()

    def test_create_get_destroy_saved_search(self):
        """Test getting list of saved searches for authenticated
        user succeeds"""
        saved_search = self.api.create_saved_search(query='#Twitter')
        saved_search_id = saved_search['id_str']

        self.api.show_saved_search(id=saved_search_id)
        self.api.destroy_saved_search(id=saved_search_id)

    # Places & Geo
    def test_get_geo_info(self):
        """Test getting info about a geo location succeeds"""
        self.api.get_geo_info(place_id='df51dec6f4ee2b2c')

    def test_reverse_geo_code(self):
        """Test reversing geocode succeeds"""
        self.api.reverse_geocode(lat='37.76893497', long='-122.42284884')

    def test_search_geo(self):
        """Test search for places that can be attached
        to a statuses/update succeeds"""
        self.api.search_geo(query='Toronto')

    def test_get_similar_places(self):
        """Test locates places near the given coordinates which
        are similar in name succeeds"""
        self.api.get_similar_places(lat='37', long='-122', name='Twitter HQ')

    # Trends
    def test_get_place_trends(self):
        """Test getting the top 10 trending topics for a specific
        WOEID succeeds"""
        self.api.get_place_trends(id=1)

    def test_get_available_trends(self):
        """Test returning locations that Twitter has trending
        topic information for succeeds"""
        self.api.get_available_trends()

    def test_get_closest_trends(self):
        """Test getting the locations that Twitter has trending topic
        information for, closest to a specified location succeeds"""
        self.api.get_closest_trends(lat='37', long='-122')

    # Help
    def test_get_twitter_configuration(self):
        """Test getting Twitter's configuration succeeds"""
        self.api.get_twitter_configuration()

    def test_get_supported_languages(self):
        """Test getting languages supported by Twitter succeeds"""
        self.api.get_supported_languages()

    def test_privacy_policy(self):
        """Test getting Twitter's Privacy Policy succeeds"""
        self.api.get_privacy_policy()

    def test_get_tos(self):
        """Test getting the Twitter Terms of Service succeeds"""
        self.api.get_tos()

    def test_get_application_rate_limit_status(self):
        """Test getting application rate limit status succeeds"""
        self.oauth2_api.get_application_rate_limit_status()
Exemple #12
0
class TwythonAPITestCase(unittest.TestCase):
    def setUp(self):
        self.api = Twython(app_key, app_secret,
                           oauth_token, oauth_token_secret)

    # Timelines
    def test_get_mentions_timeline(self):
        '''Test returning mentions timeline for authenticated user succeeds'''
        self.api.get_mentions_timeline()

    def test_get_user_timeline(self):
        '''Test returning timeline for authenticated user and random user
        succeeds'''
        self.api.get_user_timeline()  # Authenticated User Timeline
        self.api.get_user_timeline(screen_name='twitter')  # Random User Timeline

    def test_get_protected_user_timeline_following(self):
        '''Test returning a protected user timeline who you are following
        succeeds'''
        self.api.get_user_timeline(screen_name=protected_twitter_1)

    def test_get_protected_user_timeline_not_following(self):
        '''Test returning a protected user timeline who you are not following
        fails and raise a TwythonAuthError'''
        self.assertRaises(TwythonAuthError, self.api.get_user_timeline,
                          screen_name=protected_twitter_2)

    def test_get_home_timeline(self):
        '''Test returning home timeline for authenticated user succeeds'''
        self.api.get_home_timeline()

    # Tweets
    def test_get_retweets(self):
        '''Test getting retweets of a specific tweet succeeds'''
        self.api.get_retweets(id=test_tweet_id)

    def test_show_status(self):
        '''Test returning a single status details succeeds'''
        self.api.show_status(id=test_tweet_id)

    def test_update_and_destroy_status(self):
        '''Test updating and deleting a status succeeds'''
        status = self.api.update_status(status='Test post just to get deleted :(')
        self.api.destroy_status(id=status['id_str'])

    def test_retweet(self):
        '''Test retweeting a status succeeds'''
        retweet = self.api.retweet(id='99530515043983360')
        self.api.destroy_status(id=retweet['id_str'])

    def test_retweet_twice(self):
        '''Test that trying to retweet a tweet twice raises a TwythonError'''
        retweet = self.api.retweet(id='99530515043983360')
        self.assertRaises(TwythonError, self.api.retweet,
                          id='99530515043983360')

        # Then clean up
        self.api.destroy_status(id=retweet['id_str'])

    def test_get_oembed_tweet(self):
        '''Test getting info to embed tweet on Third Party site succeeds'''
        self.api.get_oembed_tweet(id='99530515043983360')

    def test_get_retweeters_ids(self):
        '''Test getting ids for people who retweeted a tweet succeeds'''
        self.api.get_retweeters_ids(id='99530515043983360')

    # Search
    def test_search(self):
        '''Test searching tweets succeeds'''
        self.api.search(q='twitter')

    # Direct Messages
    def test_get_direct_messages(self):
        '''Test getting the authenticated users direct messages succeeds'''
        self.api.get_direct_messages()

    def test_get_sent_messages(self):
        '''Test getting the authenticated users direct messages they've
        sent succeeds'''
        self.api.get_sent_messages()

    def test_send_get_and_destroy_direct_message(self):
        '''Test sending, getting, then destory a direct message succeeds'''
        message = self.api.send_direct_message(screen_name=protected_twitter_1,
                                               text='Hey d00d!')

        self.api.get_direct_message(id=message['id_str'])
        self.api.destroy_direct_message(id=message['id_str'])

    def test_send_direct_message_to_non_follower(self):
        '''Test sending a direct message to someone who doesn't follow you
        fails'''
        self.assertRaises(TwythonError, self.api.send_direct_message,
                          screen_name=protected_twitter_2, text='Yo, man!')

    # Friends & Followers
    def test_get_user_ids_of_blocked_retweets(self):
        '''Test that collection of user_ids that the authenticated user does
        not want to receive retweets from succeeds'''
        self.api.get_user_ids_of_blocked_retweets(stringify_ids='true')

    def test_get_friends_ids(self):
        '''Test returning ids of users the authenticated user and then a random
        user is following succeeds'''
        self.api.get_friends_ids()
        self.api.get_friends_ids(screen_name='twitter')

    def test_get_followers_ids(self):
        '''Test returning ids of users the authenticated user and then a random
        user are followed by succeeds'''
        self.api.get_followers_ids()
        self.api.get_followers_ids(screen_name='twitter')

    def test_lookup_friendships(self):
        '''Test returning relationships of the authenticating user to the
        comma-separated list of up to 100 screen_names or user_ids provided
        succeeds'''
        self.api.lookup_friendships(screen_name='twitter,ryanmcgrath')

    def test_get_incoming_friendship_ids(self):
        '''Test returning incoming friendship ids succeeds'''
        self.api.get_incoming_friendship_ids()

    def test_get_outgoing_friendship_ids(self):
        '''Test returning outgoing friendship ids succeeds'''
        self.api.get_outgoing_friendship_ids()

    def test_create_friendship(self):
        '''Test creating a friendship succeeds'''
        self.api.create_friendship(screen_name='justinbieber')

    def test_destroy_friendship(self):
        '''Test destroying a friendship succeeds'''
        self.api.destroy_friendship(screen_name='justinbieber')

    def test_update_friendship(self):
        '''Test updating friendships succeeds'''
        self.api.update_friendship(screen_name=protected_twitter_1,
                                   retweets='true')

        self.api.update_friendship(screen_name=protected_twitter_1,
                                   retweets='false')

    def test_show_friendships(self):
        '''Test showing specific friendship succeeds'''
        self.api.show_friendship(target_screen_name=protected_twitter_1)

    def test_get_friends_list(self):
        '''Test getting list of users authenticated user then random user is
        following succeeds'''
        self.api.get_friends_list()
        self.api.get_friends_list(screen_name='twitter')

    def test_get_followers_list(self):
        '''Test getting list of users authenticated user then random user are
        followed by succeeds'''
        self.api.get_followers_list()
        self.api.get_followers_list(screen_name='twitter')

    # Users
    def test_get_account_settings(self):
        '''Test getting the authenticated user account settings succeeds'''
        self.api.get_account_settings()

    def test_verify_credentials(self):
        '''Test representation of the authenticated user call succeeds'''
        self.api.verify_credentials()

    def test_update_account_settings(self):
        '''Test updating a user account settings succeeds'''
        self.api.update_account_settings(lang='en')

    def test_update_delivery_service(self):
        '''Test updating delivery settings fails because we don't have
        a mobile number on the account'''
        self.assertRaises(TwythonError, self.api.update_delivery_service,
                          device='none')

    def test_update_profile(self):
        '''Test updating profile succeeds'''
        self.api.update_profile(include_entities='true')

    def test_update_profile_colors(self):
        '''Test updating profile colors succeeds'''
        self.api.update_profile_colors(profile_background_color='3D3D3D')

    def test_list_blocks(self):
        '''Test listing users who are blocked by the authenticated user
        succeeds'''
        self.api.list_blocks()

    def test_list_block_ids(self):
        '''Test listing user ids who are blocked by the authenticated user
        succeeds'''
        self.api.list_block_ids()

    def test_create_block(self):
        '''Test blocking a user succeeds'''
        self.api.create_block(screen_name='justinbieber')

    def test_destroy_block(self):
        '''Test unblocking a user succeeds'''
        self.api.destroy_block(screen_name='justinbieber')

    def test_lookup_user(self):
        '''Test listing a number of user objects succeeds'''
        self.api.lookup_user(screen_name='twitter,justinbieber')

    def test_show_user(self):
        '''Test showing one user works'''
        self.api.show_user(screen_name='twitter')

    def test_search_users(self):
        '''Test that searching for users succeeds'''
        self.api.search_users(q='Twitter API')

    def test_get_contributees(self):
        '''Test returning list of accounts the specified user can
        contribute to succeeds'''
        self.api.get_contributees(screen_name='TechCrunch')

    def test_get_contributors(self):
        '''Test returning list of accounts that contribute to the
        authenticated user fails because we are not a Contributor account'''
        self.assertRaises(TwythonError, self.api.get_contributors,
                          screen_name=screen_name)

    def test_remove_profile_banner(self):
        '''Test removing profile banner succeeds'''
        self.api.remove_profile_banner()

    def test_get_profile_banner_sizes(self):
        '''Test getting list of profile banner sizes fails because
        we have not uploaded a profile banner'''
        self.assertRaises(TwythonError, self.api.get_profile_banner_sizes)

    # Suggested Users
    def test_get_user_suggestions_by_slug(self):
        '''Test getting user suggestions by slug succeeds'''
        self.api.get_user_suggestions_by_slug(slug='twitter')

    def test_get_user_suggestions(self):
        '''Test getting user suggestions succeeds'''
        self.api.get_user_suggestions()

    def test_get_user_suggestions_statuses_by_slug(self):
        '''Test getting status of suggested users succeeds'''
        self.api.get_user_suggestions_statuses_by_slug(slug='funny')

    # Favorites
    def test_get_favorites(self):
        '''Test getting list of favorites for the authenticated
        user succeeds'''
        self.api.get_favorites()

    def test_create_and_destroy_favorite(self):
        '''Test creating and destroying a favorite on a tweet succeeds'''
        self.api.create_favorite(id=test_tweet_id)
        self.api.destroy_favorite(id=test_tweet_id)

    # Lists
    def test_show_lists(self):
        '''Test show lists for specified user'''
        self.api.show_lists(screen_name='twitter')

    def test_get_list_statuses(self):
        '''Test timeline of tweets authored by members of the
        specified list succeeds'''
        self.api.get_list_statuses(list_id=test_list_id)

    def test_create_update_destroy_list_add_remove_list_members(self):
        '''Test create a list, adding and removing members then
        deleting the list succeeds'''
        the_list = self.api.create_list(name='Stuff')
        list_id = the_list['id_str']

        self.api.update_list(list_id=list_id, name='Stuff Renamed')

        # Multi add/delete members
        self.api.create_list_members(list_id=list_id,
                                     screen_name='johncena,xbox')
        self.api.delete_list_members(list_id=list_id,
                                     screen_name='johncena,xbox')

        # Single add/delete member
        self.api.add_list_member(list_id=list_id, screen_name='justinbieber')
        self.api.delete_list_member(list_id=list_id, screen_name='justinbieber')

        self.api.delete_list(list_id=list_id)

    def test_get_list_memberships(self):
        '''Test list of lists the authenticated user is a member of succeeds'''
        self.api.get_list_memberships()

    def test_get_list_subscribers(self):
        '''Test list of subscribers of a specific list succeeds'''
        self.api.get_list_subscribers(list_id=test_list_id)

    def test_subscribe_is_subbed_and_unsubscribe_to_list(self):
        '''Test subscribing, is a list sub and unsubbing to list succeeds'''
        self.api.subscribe_to_list(list_id=test_list_id)
        # Returns 404 if user is not a subscriber
        self.api.is_list_subscriber(list_id=test_list_id,
                                    screen_name=screen_name)
        self.api.unsubscribe_from_list(list_id=test_list_id)

    def test_is_list_member(self):
        '''Test returning if specified user is member of a list succeeds'''
        # Returns 404 if not list member
        self.api.is_list_member(list_id=test_list_id, screen_name='jack')

    def test_get_list_members(self):
        '''Test listing members of the specified list succeeds'''
        self.api.get_list_members(list_id=test_list_id)

    def test_get_specific_list(self):
        '''Test getting specific list succeeds'''
        self.api.get_specific_list(list_id=test_list_id)

    def test_get_list_subscriptions(self):
        '''Test collection of the lists the specified user is
        subscribed to succeeds'''
        self.api.get_list_subscriptions(screen_name='twitter')

    def test_show_owned_lists(self):
        '''Test collection of lists the specified user owns succeeds'''
        self.api.show_owned_lists(screen_name='twitter')

    # Saved Searches
    def test_get_saved_searches(self):
        '''Test getting list of saved searches for authenticated
        user succeeds'''
        self.api.get_saved_searches()

    def test_create_get_destroy_saved_search(self):
        '''Test getting list of saved searches for authenticated
        user succeeds'''
        saved_search = self.api.create_saved_search(query='#Twitter')
        saved_search_id = saved_search['id_str']

        self.api.show_saved_search(id=saved_search_id)
        self.api.destroy_saved_search(id=saved_search_id)

    # Places & Geo
    def test_get_geo_info(self):
        '''Test getting info about a geo location succeeds'''
        self.api.get_geo_info(place_id='df51dec6f4ee2b2c')

    def test_reverse_geo_code(self):
        '''Test reversing geocode succeeds'''
        self.api.reverse_geocode(lat='37.76893497', long='-122.42284884')

    def test_search_geo(self):
        '''Test search for places that can be attached
        to a statuses/update succeeds'''
        self.api.search_geo(query='Toronto')

    def test_get_similar_places(self):
        '''Test locates places near the given coordinates which
        are similar in name succeeds'''
        self.api.get_similar_places(lat='37', long='-122', name='Twitter HQ')

    # Trends
    def test_get_place_trends(self):
        '''Test getting the top 10 trending topics for a specific
        WOEID succeeds'''
        self.api.get_place_trends(id=1)

    def test_get_available_trends(self):
        '''Test returning locations that Twitter has trending
        topic information for succeeds'''
        self.api.get_available_trends()

    def test_get_closest_trends(self):
        '''Test getting the locations that Twitter has trending topic
        information for, closest to a specified location succeeds'''
        self.api.get_closest_trends(lat='37', long='-122')
    search_results = twitter.search(q="thanksobama", since_id = idnum, count=20)
    #searchs a hashtag from after a certian tweet with a max of 20 results
    count = 0
    for tweet in search_results["statuses"]:
        try:
            rannum = random.randrange(1,5)
            print(rannum)
            if rannum == 2:
                #Below line retweets the statuses
                twitter.retweet(id = tweet["id_str"])
                print ("Retweeted")

            if rannum == 1:
                #Below line favorites the statuses
                twitter.create_favorite(id = tweet["id_str"])
                print ("Favorited")

            if rannum == 3:
                #Below line retweets the statuses
                twitter.retweet(id = tweet["id_str"])
                twitter.create_favorite(id = tweet["id_str"])
                print ("Retweeted and Favorited")

            if rannum == 4:
              print("did nothing")

            if count == 0:
                #checks to see if its the first tweet in the list and gets ID so there are no double ups.
                idnum = tweet["id_str"]
                print(idnum)
Exemple #14
0
    'Miauuuu Miaau',
    'Miau Mateo que te veo']

#sacamos la hora
hora = time.strftime("%H")
print hora
if hora >= "09" and hora < "19":
    print "dentro del tiempo permitido para mandar el tuit"
    api = Twython(CONSUMER_KEY,CONSUMER_SECRET,ACCESS_KEY,ACCESS_SECRET)
    api.update_status_with_media(status=random.choice(texto), media=photo)
    print "tuit enviado enviado a las "+time.strftime("%H:%M")

else:
    print "fuera de hora porque son las "+time.strftime("%H:%M")+ "pero empezamos a favear"
    api = Twython(CONSUMER_KEY,CONSUMER_SECRET,ACCESS_KEY,ACCESS_SECRET)
    naughty_words = [" -RT", "SEX", "sexo", "muerto"]
    good_words = [" gato ", "miauu", " gatos ", "LaGataSoka", "@lagatasoka", "gatito", "gatitos"]
    filter = " OR ".join(good_words)
    blacklist = " -".join(naughty_words)
    keywords = filter + blacklist

    search_results = api.search(q=keywords, count=30)
    print "resultados"+str(search_results)
    for tweet in search_results["statuses"]:
        print tweet["id_str"]
        #twitter.retweet(id = tweet["id_str"])
        api.create_favorite(id = tweet["id_str"])

print "Bye, Bye...."
sys.exit()
Exemple #15
0
# Options and notes:
#
# Usage:
#
##

__author__ = "Ben McGinnes <*****@*****.**>"
__copyright__ = "Copyright \u00a9 Benjamin D. McGinnes, 2013-2014"
__copyrighta__ = "Copyright (C) Benjamin D. McGinnes, 2013-2014"
__license__ = "BSD"
__version__ = "0.0.1"
__bitcoin__ = "1KvKMVnyYgLxU1HnLQmbWaMpDx3Dz15DVU"

import sys
from twython import Twython, TwythonError
from config import *

twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)

l = len(sys.argv)

if l == 1:
    twid = input("Enter ID number of tweet to favourite: ")
elif l >= 2:
    twid = sys.argv[1]

try:
    twitter.create_favorite(id=twid)
except TwythonError as e:
    print(e)
Exemple #16
0
# Post
post = raw_input("Write your tweet: ")
twitter.update_status(status=post)

# Get timelines
print twitter.get_user_timeline(screen_name = "name")
print twitter.get_home_timeline(count = 5)

# Search
print twitter.search(q="linux", result_type="popular")

# Follow
twitter.create_friendship(screen_name = "LinuxUserMag")

# Retweet
twitter.retweet(id = "12345")

# Favouriting
twitter.create_favorite(id = "12345")
print twitter.get_favorites()

# Mentions
print twitter.get_mentions_timeline(count="5")

# Trending
print twitter.get_place_trends(id="1")

# Retrieve lists
print twitter.get_list_statuses(id = "12345")
Exemple #17
0
API_KEY = ""
API_SECRET = ""
ACCESS_TOKEN = ""
ACCESS_TOKEN_SECRET = ""

twitter = Twython(API_KEY, API_SECRET,ACCESS_TOKEN, ACCESS_TOKEN_SECRET)

while True:


    tweets = twitter.search(q='#駆け出しエンジニアと繋がりたい', lang='ja', result_type='recent', include_entities='false', count=1)
    tweets_length = len(tweets["statuses"])

    for i in range(tweets_length):

        name = tweets["statuses"][i]["user"]["name"]
        screen_name = tweets["statuses"][i]["user"]["screen_name"]
        text = tweets["statuses"][i]["text"]
        user_id = tweets["statuses"][i]["id"]
        print("name:{}\nscreen_name:{}\ntext:{}\nid:{}\n".format(name,screen_name,text,user_id))

        try:
            twitter.create_favorite(id=user_id)
            twitter.retweet(id=user_id)
            time.sleep(10)
        except:
            print("失敗しました")
            time.sleep(10)

    time.sleep(3600)
Exemple #18
0
class TwythonAPITestCase(unittest.TestCase):
    def setUp(self):

        client_args = {
            'headers': {
                'User-Agent': '__twython__ Test'
            },
            'allow_redirects': False
        }

        oauth2_client_args = {
            'headers': {}  # This is so we can hit coverage that Twython sets User-Agent for us if none is supplied
        }

        self.api = Twython(app_key, app_secret,
                           oauth_token, oauth_token_secret,
                           client_args=client_args)

        self.oauth2_api = Twython(app_key, access_token=access_token,
                                  client_args=oauth2_client_args)

    def test_construct_api_url(self):
        """Test constructing a Twitter API url works as we expect"""
        url = 'https://api.twitter.com/1.1/search/tweets.json'
        constructed_url = self.api.construct_api_url(url, q='#twitter')
        self.assertEqual(constructed_url, 'https://api.twitter.com/1.1/search/tweets.json?q=%23twitter')

    def test_get(self):
        """Test Twython generic GET request works"""
        self.api.get('account/verify_credentials')

    def test_post(self):
        """Test Twython generic POST request works, with a full url and
        with just an endpoint"""
        update_url = 'https://api.twitter.com/1.1/statuses/update.json'
        status = self.api.post(update_url, params={'status': 'I love Twython!'})
        self.api.post('statuses/destroy/%s' % status['id_str'])

    def test_get_lastfunction_header(self):
        """Test getting last specific header of the last API call works"""
        self.api.get('statuses/home_timeline')
        self.api.get_lastfunction_header('x-rate-limit-remaining')

    def test_get_lastfunction_header_not_present(self):
        """Test getting specific header that does not exist from the last call returns None"""
        self.api.get('statuses/home_timeline')
        header = self.api.get_lastfunction_header('does-not-exist')
        self.assertEqual(header, None)

    def test_get_lastfunction_header_no_last_api_call(self):
        """Test attempting to get a header when no API call was made raises a TwythonError"""
        self.assertRaises(TwythonError, self.api.get_lastfunction_header,
                          'no-api-call-was-made')

    def test_search_gen(self):
        """Test looping through the generator results works, at least once that is"""
        search = self.api.search_gen('twitter', count=1)
        counter = 0
        while counter < 2:
            counter += 1
            result = next(search)
            new_id_str = int(result['id_str'])
            if counter == 1:
                prev_id_str = new_id_str
                time.sleep(1)  # Give time for another tweet to come into search
            if counter == 2:
                self.assertTrue(new_id_str > prev_id_str)

    def test_encode(self):
        """Test encoding UTF-8 works"""
        self.api.encode('Twython is awesome!')

    def test_html_for_tweet(self):
        """Test HTML for Tweet returns what we want"""
        tweet_text = self.api.html_for_tweet(test_tweet_object)
        self.assertEqual(test_tweet_html, tweet_text)

    def test_html_for_tweet_expanded_url(self):
        """Test using expanded url in HTML for Tweet displays full urls"""
        tweet_text = self.api.html_for_tweet(test_tweet_object,
                                             use_expanded_url=True)
        # Make sure full url is in HTML
        self.assertTrue('http://google.com' in tweet_text)

    def test_html_for_tweet_short_url(self):
        """Test using expanded url in HTML for Tweet displays full urls"""
        tweet_text = self.api.html_for_tweet(test_tweet_object, False)
        # Make sure HTML doesn't contain the display OR exapanded url
        self.assertTrue(not 'http://google.com' in tweet_text)
        self.assertTrue(not 'google.com' in tweet_text)

    def test_raise_error_on_bad_ssl_cert(self):
        """Test TwythonError is raised by a RequestException when an actual HTTP happens"""
        self.assertRaises(TwythonError, self.api.get, 'https://example.com')

    # Timelines
    def test_get_mentions_timeline(self):
        """Test returning mentions timeline for authenticated user succeeds"""
        self.api.get_mentions_timeline()

    def test_get_user_timeline(self):
        """Test returning timeline for authenticated user and random user
        succeeds"""
        self.api.get_user_timeline()  # Authenticated User Timeline
        self.api.get_user_timeline(screen_name='twitter')  # Random User Timeline

    def test_get_protected_user_timeline_following(self):
        """Test returning a protected user timeline who you are following
        succeeds"""
        self.api.get_user_timeline(screen_name=protected_twitter_1)

    def test_get_protected_user_timeline_not_following(self):
        """Test returning a protected user timeline who you are not following
        fails and raise a TwythonAuthError"""
        self.assertRaises(TwythonAuthError, self.api.get_user_timeline,
                          screen_name=protected_twitter_2)

    def test_retweeted_of_me(self):
        """Test that getting recent tweets by authenticated user that have
        been retweeted by others succeeds"""
        self.api.retweeted_of_me()

    def test_get_home_timeline(self):
        """Test returning home timeline for authenticated user succeeds"""
        self.api.get_home_timeline()

    # Tweets
    def test_get_retweets(self):
        """Test getting retweets of a specific tweet succeeds"""
        self.api.get_retweets(id=test_tweet_id)

    def test_show_status(self):
        """Test returning a single status details succeeds"""
        self.api.show_status(id=test_tweet_id)

    def test_update_and_destroy_status(self):
        """Test updating and deleting a status succeeds"""
        status = self.api.update_status(status='Test post just to get deleted :(')
        self.api.destroy_status(id=status['id_str'])

    def test_get_oembed_tweet(self):
        """Test getting info to embed tweet on Third Party site succeeds"""
        self.api.get_oembed_tweet(id='99530515043983360')

    def test_get_retweeters_ids(self):
        """Test getting ids for people who retweeted a tweet succeeds"""
        self.api.get_retweeters_ids(id='99530515043983360')

    # Search
    def test_search(self):
        """Test searching tweets succeeds"""
        self.api.search(q='twitter')

    # Direct Messages
    def test_get_direct_messages(self):
        """Test getting the authenticated users direct messages succeeds"""
        self.api.get_direct_messages()

    def test_get_sent_messages(self):
        """Test getting the authenticated users direct messages they've
        sent succeeds"""
        self.api.get_sent_messages()

    def test_send_get_and_destroy_direct_message(self):
        """Test sending, getting, then destory a direct message succeeds"""
        message = self.api.send_direct_message(screen_name=protected_twitter_1,
                                               text='Hey d00d! %s' % int(time.time()))

        self.api.get_direct_message(id=message['id_str'])
        self.api.destroy_direct_message(id=message['id_str'])

    def test_send_direct_message_to_non_follower(self):
        """Test sending a direct message to someone who doesn't follow you
        fails"""
        self.assertRaises(TwythonError, self.api.send_direct_message,
                          screen_name=protected_twitter_2, text='Yo, man!')

    # Friends & Followers
    def test_get_user_ids_of_blocked_retweets(self):
        """Test that collection of user_ids that the authenticated user does
        not want to receive retweets from succeeds"""
        self.api.get_user_ids_of_blocked_retweets(stringify_ids=True)

    def test_get_friends_ids(self):
        """Test returning ids of users the authenticated user and then a random
        user is following succeeds"""
        self.api.get_friends_ids()
        self.api.get_friends_ids(screen_name='twitter')

    def test_get_followers_ids(self):
        """Test returning ids of users the authenticated user and then a random
        user are followed by succeeds"""
        self.api.get_followers_ids()
        self.api.get_followers_ids(screen_name='twitter')

    def test_lookup_friendships(self):
        """Test returning relationships of the authenticating user to the
        comma-separated list of up to 100 screen_names or user_ids provided
        succeeds"""
        self.api.lookup_friendships(screen_name='twitter,ryanmcgrath')

    def test_get_incoming_friendship_ids(self):
        """Test returning incoming friendship ids succeeds"""
        self.api.get_incoming_friendship_ids()

    def test_get_outgoing_friendship_ids(self):
        """Test returning outgoing friendship ids succeeds"""
        self.api.get_outgoing_friendship_ids()

    def test_create_friendship(self):
        """Test creating a friendship succeeds"""
        self.api.create_friendship(screen_name='justinbieber')

    def test_destroy_friendship(self):
        """Test destroying a friendship succeeds"""
        self.api.destroy_friendship(screen_name='justinbieber')

    def test_update_friendship(self):
        """Test updating friendships succeeds"""
        self.api.update_friendship(screen_name=protected_twitter_1,
                                   retweets='true')

        self.api.update_friendship(screen_name=protected_twitter_1,
                                   retweets=False)

    def test_show_friendships(self):
        """Test showing specific friendship succeeds"""
        self.api.show_friendship(target_screen_name=protected_twitter_1)

    def test_get_friends_list(self):
        """Test getting list of users authenticated user then random user is
        following succeeds"""
        self.api.get_friends_list()
        self.api.get_friends_list(screen_name='twitter')

    def test_get_followers_list(self):
        """Test getting list of users authenticated user then random user are
        followed by succeeds"""
        self.api.get_followers_list()
        self.api.get_followers_list(screen_name='twitter')

    # Users
    def test_get_account_settings(self):
        """Test getting the authenticated user account settings succeeds"""
        self.api.get_account_settings()

    def test_verify_credentials(self):
        """Test representation of the authenticated user call succeeds"""
        self.api.verify_credentials()

    def test_update_account_settings(self):
        """Test updating a user account settings succeeds"""
        self.api.update_account_settings(lang='en')

    def test_update_delivery_service(self):
        """Test updating delivery settings fails because we don't have
        a mobile number on the account"""
        self.assertRaises(TwythonError, self.api.update_delivery_service,
                          device='none')

    def test_update_profile(self):
        """Test updating profile succeeds"""
        self.api.update_profile(include_entities='true')

    def test_update_profile_colors(self):
        """Test updating profile colors succeeds"""
        self.api.update_profile_colors(profile_background_color='3D3D3D')

    def test_list_blocks(self):
        """Test listing users who are blocked by the authenticated user
        succeeds"""
        self.api.list_blocks()

    def test_list_block_ids(self):
        """Test listing user ids who are blocked by the authenticated user
        succeeds"""
        self.api.list_block_ids()

    def test_create_block(self):
        """Test blocking a user succeeds"""
        self.api.create_block(screen_name='justinbieber')

    def test_destroy_block(self):
        """Test unblocking a user succeeds"""
        self.api.destroy_block(screen_name='justinbieber')

    def test_lookup_user(self):
        """Test listing a number of user objects succeeds"""
        self.api.lookup_user(screen_name='twitter,justinbieber')

    def test_show_user(self):
        """Test showing one user works"""
        self.api.show_user(screen_name='twitter')

    def test_search_users(self):
        """Test that searching for users succeeds"""
        self.api.search_users(q='Twitter API')

    def test_get_contributees(self):
        """Test returning list of accounts the specified user can
        contribute to succeeds"""
        self.api.get_contributees(screen_name='TechCrunch')

    def test_get_contributors(self):
        """Test returning list of accounts that contribute to the
        authenticated user fails because we are not a Contributor account"""
        self.assertRaises(TwythonError, self.api.get_contributors,
                          screen_name=screen_name)

    def test_remove_profile_banner(self):
        """Test removing profile banner succeeds"""
        self.api.remove_profile_banner()

    def test_get_profile_banner_sizes(self):
        """Test getting list of profile banner sizes fails because
        we have not uploaded a profile banner"""
        self.assertRaises(TwythonError, self.api.get_profile_banner_sizes)

    # Suggested Users
    def test_get_user_suggestions_by_slug(self):
        """Test getting user suggestions by slug succeeds"""
        self.api.get_user_suggestions_by_slug(slug='twitter')

    def test_get_user_suggestions(self):
        """Test getting user suggestions succeeds"""
        self.api.get_user_suggestions()

    def test_get_user_suggestions_statuses_by_slug(self):
        """Test getting status of suggested users succeeds"""
        self.api.get_user_suggestions_statuses_by_slug(slug='funny')

    # Favorites
    def test_get_favorites(self):
        """Test getting list of favorites for the authenticated
        user succeeds"""
        self.api.get_favorites()

    def test_create_and_destroy_favorite(self):
        """Test creating and destroying a favorite on a tweet succeeds"""
        self.api.create_favorite(id=test_tweet_id)
        self.api.destroy_favorite(id=test_tweet_id)

    # Lists
    def test_show_lists(self):
        """Test show lists for specified user"""
        self.api.show_lists(screen_name='twitter')

    def test_get_list_statuses(self):
        """Test timeline of tweets authored by members of the
        specified list succeeds"""
        self.api.get_list_statuses(list_id=test_list_id)

    def test_create_update_destroy_list_add_remove_list_members(self):
        """Test create a list, adding and removing members then
        deleting the list succeeds"""
        the_list = self.api.create_list(name='Stuff')
        list_id = the_list['id_str']

        self.api.update_list(list_id=list_id, name='Stuff Renamed')

        screen_names = ['johncena', 'xbox']
        # Multi add/delete members
        self.api.create_list_members(list_id=list_id,
                                     screen_name=screen_names)
        self.api.delete_list_members(list_id=list_id,
                                     screen_name=screen_names)

        # Single add/delete member
        self.api.add_list_member(list_id=list_id, screen_name='justinbieber')
        self.api.delete_list_member(list_id=list_id, screen_name='justinbieber')

        self.api.delete_list(list_id=list_id)

    def test_get_list_subscribers(self):
        """Test list of subscribers of a specific list succeeds"""
        self.api.get_list_subscribers(list_id=test_list_id)

    def test_subscribe_is_subbed_and_unsubscribe_to_list(self):
        """Test subscribing, is a list sub and unsubbing to list succeeds"""
        self.api.subscribe_to_list(list_id=test_list_id)
        # Returns 404 if user is not a subscriber
        self.api.is_list_subscriber(list_id=test_list_id,
                                    screen_name=screen_name)
        self.api.unsubscribe_from_list(list_id=test_list_id)

    def test_is_list_member(self):
        """Test returning if specified user is member of a list succeeds"""
        # Returns 404 if not list member
        self.api.is_list_member(list_id=test_list_id, screen_name='jack')

    def test_get_list_members(self):
        """Test listing members of the specified list succeeds"""
        self.api.get_list_members(list_id=test_list_id)

    def test_get_specific_list(self):
        """Test getting specific list succeeds"""
        self.api.get_specific_list(list_id=test_list_id)

    def test_get_list_subscriptions(self):
        """Test collection of the lists the specified user is
        subscribed to succeeds"""
        self.api.get_list_subscriptions(screen_name='twitter')

    def test_show_owned_lists(self):
        """Test collection of lists the specified user owns succeeds"""
        self.api.show_owned_lists(screen_name='twitter')

    # Saved Searches
    def test_get_saved_searches(self):
        """Test getting list of saved searches for authenticated
        user succeeds"""
        self.api.get_saved_searches()

    def test_create_get_destroy_saved_search(self):
        """Test getting list of saved searches for authenticated
        user succeeds"""
        saved_search = self.api.create_saved_search(query='#Twitter')
        saved_search_id = saved_search['id_str']

        self.api.show_saved_search(id=saved_search_id)
        self.api.destroy_saved_search(id=saved_search_id)

    # Places & Geo
    def test_get_geo_info(self):
        """Test getting info about a geo location succeeds"""
        self.api.get_geo_info(place_id='df51dec6f4ee2b2c')

    def test_reverse_geo_code(self):
        """Test reversing geocode succeeds"""
        self.api.reverse_geocode(lat='37.76893497', long='-122.42284884')

    def test_search_geo(self):
        """Test search for places that can be attached
        to a statuses/update succeeds"""
        self.api.search_geo(query='Toronto')

    def test_get_similar_places(self):
        """Test locates places near the given coordinates which
        are similar in name succeeds"""
        self.api.get_similar_places(lat='37', long='-122', name='Twitter HQ')

    # Trends
    def test_get_place_trends(self):
        """Test getting the top 10 trending topics for a specific
        WOEID succeeds"""
        self.api.get_place_trends(id=1)

    def test_get_available_trends(self):
        """Test returning locations that Twitter has trending
        topic information for succeeds"""
        self.api.get_available_trends()

    def test_get_closest_trends(self):
        """Test getting the locations that Twitter has trending topic
        information for, closest to a specified location succeeds"""
        self.api.get_closest_trends(lat='37', long='-122')

    # Help
    def test_get_application_rate_limit_status(self):
        """Test getting application rate limit status succeeds"""
        self.oauth2_api.get_application_rate_limit_status()
def favorite(data):
	twitter = Twython(os.getenv('APP_KEY'), os.getenv('APP_SECRET'), os.getenv('OAUTH_TOKEN'), os.getenv('OAUTH_TOKEN_SECRET'), client_args={'verify':False})
        print "Bot: create_favorite: %s" % data['id']
        twitter.create_favorite( id=data['id'] )
Exemple #20
0
naughty_words = [" -RT", "church", "faith", "god", "politician", "terrorism"]

#And a list of words we WOULD like to RT
good_words = [
    "skoolie", "bus conversion", "bus", "van conversion", "tinyhouse",
    "tinyhome"
]

#OR is Twitter's search operator to search for this OR that
#So let's join everything in good_words with an OR!
filter = " OR ".join(good_words)

# The - is Twitter's search operator for negative keywords
# So we want to prefix every negative keyword with a -
blacklist = " -".join(naughty_words)

#And finally our list of keywords that we want to search for
#This will search for any words in good_words minus any naughty_words
keywords = filter + blacklist

#This time we want to set our q to search for our keywords
search_results = twitter.search(q=keywords, count=1)
try:
    for tweet in search_results["statuses"]:
        try:
            twitter.create_favorite(id=tweet["id_str"])
        except TwythonError as e:
            print e
except TwythonError as e:
    print e
# Options and notes:
#
# Usage:  
#
##

from license import __author__
from license import __copyright__
from license import __copyrighta__
from license import __license__
__version__ = "0.0.1"
from license import __bitcoin__

import sys
from twython import Twython, TwythonError
from config import *

twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)

l = len(sys.argv)

if l == 1:
    twid = input("Enter ID number of tweet to favourite: ")
elif l >= 2:
    twid = sys.argv[1]

try:
    twitter.create_favorite(id=twid)
except TwythonError as e:
    print(e)
class TwitterHelper(object):
    def __init__(self, identity):
        self.identity = identity
        if not self.identity.tokens:
            self.identity.tokens = authorisationhelper.get_tokens(identity.screen_name)
        self.twitter = Twython(
            self.identity.tokens[0],
            self.identity.tokens[1],
            self.identity.tokens[2],
            self.identity.tokens[3]
        )
        # self.identity.twid = self.twitter.lookup_user(screen_name=identity.screen_name)[0]["id_str"]
        self.mutation = [" ,", " .", " *", " `", " -", " _"]

        self.twitter_configuration = self.twitter.get_twitter_configuration()

        logger.debug(self.twitter_configuration)
        giphyhelper.set_photo_size_limit(self.twitter_configuration["photo_size_limit"])

        me = self.twitter.lookup_user(screen_name=self.identity.screen_name)[0]
        logger.debug(me)
        self.identity.update(me)

        self.rates = None
        self.update_rate_limits()

    @retry(**retry_args)
    def send(self, outbox_item):
        if type(outbox_item) is OutgoingTweet:

            outbox_item.display()

            if outbox_item.filePaths and any(outbox_item.filePaths):
                for filePath in outbox_item.filePaths:
                    # ext = os.path.splitext(filePath)
                    # if ext == "mp4":
                    #     media_id = self._upload_video(filePath)
                    # else:
                    media_id = self._upload_media(filePath)
                    if media_id:
                        outbox_item.media_ids.append(media_id)

            split_tweets = tweet_splitter.split_tweet(outbox_item, self.twitter_configuration)

            in_reply_to_id_str = outbox_item.in_reply_to_id_str

            for split_tweet in split_tweets:
                split_tweet.in_reply_to_id_str = in_reply_to_id_str
                response = self.twitter.update_status(**split_tweet.get_tweet_params())
                split_tweet.id_str = response["id_str"]
                self.identity.conversations.outgoing(split_tweet)
                self.identity.statistics.record_outgoing_tweet()
                in_reply_to_id_str = split_tweet.id_str

            return in_reply_to_id_str

        if type(outbox_item) is OutgoingDirectMessage:
            if not outbox_item.screen_name and not outbox_item.user_id:
                outbox_item.screen_name = self.identity.admin_screen_name

            outbox_item.display()
            self.twitter.send_direct_message(
                text=outbox_item.text,
                screen_name=outbox_item.screen_name,
                user_id=outbox_item.user_id)
            self.identity.statistics.record_outgoing_direct_message()
        return None

    def quote_tweet(self, inbox_item, text=None, file_paths=None):
        reply_as_quote_tweet = inbox_item.is_tweet
        reply_as_dm = inbox_item.is_direct_message

        if reply_as_quote_tweet:
            logger.info("quoting to %s as quote tweet", inbox_item.text)
            tweet = OutgoingTweet(
                quote=inbox_item,
                text=text,
                file_paths=file_paths,
            )
            return self.send(tweet)

        if reply_as_dm:
            logger.info("replying to %s as DM", inbox_item.text)
            dm = OutgoingDirectMessage(
                reply_to=inbox_item,
                text=text)
            return self.send(dm)

        return None

    def reply_with(self, inbox_item, text=None, as_tweet=False, as_direct_message=False, file_paths=None,
                   in_reply_to_id_str=None):
        reply_as_tweet = as_tweet or not as_direct_message and inbox_item.is_tweet
        reply_as_dm = as_direct_message or not as_tweet and inbox_item.is_direct_message

        if reply_as_tweet:
            logger.info("replying to %s as tweet", inbox_item.text)
            tweet = OutgoingTweet(
                reply_to=inbox_item,
                text=text,
                file_paths=file_paths,
                in_reply_to_id_str=in_reply_to_id_str)
            return self.send(tweet)

        if reply_as_dm:
            logger.info("replying to %s as DM", inbox_item.text)
            dm = OutgoingDirectMessage(
                reply_to=inbox_item,
                text=text)
            return self.send(dm)

        return None

    def _upload_media(self, file_path):
        file = None
        try:
            file = open(file_path, 'rb')
            media = self.twitter.upload_media(media=file)
            self.identity.statistics.increment("Media Uploads")
            return media["media_id_string"]
        finally:
            if file:
                file.close()

    def get_streamer(self, topic=None, topic_name=None, responses=None, filter_level=None):
        return Streamer(self.identity, topic, topic_name, responses, filter_level)

    def _upload_video(self, file_path):
        logger.info('[MyTwitter] uploading ' + file_path)
        url = 'https://upload.twitter.com/1.1/media/upload.json'
        file_size = os.path.getsize(file_path)

        logger.info('[MyTwitter] Init')
        init_params = {
            "command": "INIT",
            "media_type": "video/mp4",
            "total_bytes": file_size
        }
        init_response = self.twitter.post(url, init_params)

        logger.info(init_response)

        media_id = init_response["media_id_string"]
        logger.info('[MyTwitter] media_id ' + media_id)

        segment = 0
        chunk_size = 4 * 1024 * 1024
        for chunk in fsh.bytes_from_file(file_path, chunk_size):
            logger.info('[MyTwitter] Append ' + str(segment))

            append_params = {
                'command': 'APPEND',
                'media_id': media_id,
                'segment_index': segment
            }
            append_response = self.twitter.post(url, append_params, {'media': chunk})

            logger.info(append_response)

        segment += 1

        logger.info('[MyTwitter] Finalize')
        finalize_params = {
            "command": "FINALIZE",
            "media_id": media_id,

        }
        self.twitter.post(url, finalize_params)

        return media_id

    def get_trending_topics_for(self, woeids):
        trending_topics = []
        for woeid in woeids:
            trends = self.twitter.get_place_trends(id=woeid)[0].get('trends', [])
            for trend in trends:
                trending_topics.append(trend['name'])
        return trending_topics

    def get_saved_searches(self):
        saved_searches = []
        searches = self.twitter.get_saved_searches()
        for srch in searches:
            saved_searches.append(srch['name'])
        return saved_searches

    def delete_saved_searches(self):
        searches = self.twitter.get_saved_searches()
        for srch in searches:
            self.twitter.destroy_saved_search(id=srch["id_str"])

    def search(self, text, result_type="popular"):
        query = quote_plus(text)
        return self.twitter.search(q=query, result_type=result_type)["statuses"]

    @retry(**retry_args)
    def favourite(self, id_str):
        try:
            self.twitter.create_favorite(id=id_str)
            self.identity.statistics.record_favourite()
        except TwythonError as ex:
            if "You have already favourited this tweet" in str(ex):
                logger.warning(ex)
            else:
                raise

    @retry(**retry_args)
    def retweet(self, id_str):
        try:
            self.twitter.retweet(id=id_str)
            self.identity.statistics.record_retweet()
        except TwythonError as ex:
            if "You have already retweeted this tweet" in str(ex):
                logger.warning(ex)
            else:
                raise

    @retry(**retry_args)
    def add_user_to_list(self, list_id, user_id, screen_name):
        self.twitter.create_list_members(list_id=list_id, user_id=user_id, screen_name=screen_name)

    @retry(**retry_args)
    def block_user(self, user_id, user_screen_name=None):
        self.twitter.create_block(user_id=user_id, screen_name=user_screen_name)

    @retry(**retry_args)
    def get_user_timeline(self, **kwargs):
        return self._rate_limit("/statuses/user_timeline", self.twitter.get_user_timeline, **kwargs)

    def unblock_user(self, user):
        self.twitter.destroy_block(user_id=user.id, screen_name=user.screen_name)

    @retry(**retry_args)
    def unblock_users(self):
        user_ids = self.twitter.list_block_ids(stringify_ids=True)
        for user_id in user_ids["ids"]:
            self.twitter.destroy_block(user_id=user_id)

    @retry(**retry_args)
    def show_owned_lists(self):
        return self.twitter.show_owned_lists()["lists"]

    @retry(**retry_args)
    def get_list_members(self, list_id):
        return self.twitter.get_list_members(list_id=list_id, count=5000, include_entities=False)

    @blocked
    @retry(**retry_args)
    def create_list(self, **kwargs):
        return self.twitter.create_list(**kwargs)

    @retry(**retry_args)
    def follow(self, user_id, screen_name):
        logger.info("following user id {} @{}".format(user_id, screen_name))
        self.twitter.create_friendship(user_id=user_id, screen_name=screen_name)
        self.identity.statistics.increment("Follows")

    @retry(**retry_args)
    def unfollow(self, user_id, screen_name):
        logger.info("unfollowing user id {} @{}".format(user_id, screen_name))
        self.twitter.destroy_friendship(user_id=user_id, screen_name=screen_name)
        self.identity.statistics.increment("Unfollows")

    @retry(**retry_args)
    def block(self, user_id, screen_name):
        logger.info("blocking user id {} @{}".format(user_id, screen_name))
        self.twitter.create_block(user_id=user_id, screen_name=screen_name)
        self.identity.statistics.increment("Blocks")

    @retry(**retry_args)
    def report(self, user_id, screen_name):
        logger.info("reporting user id {} @{}".format(user_id, screen_name))
        self.twitter.report_spam(user_id=user_id, screen_name=screen_name)
        self.identity.statistics.increment("Reports")

    @retry(**retry_args)
    def lookup_user(self, user_id):
        return self._rate_limit("/users/lookup", self.twitter.lookup_user, user_id=user_id)

    def sing_song(self, song, target=None, inbox_item=None, text=None, hashtag=None):
        if not text:
            text = random.choice(["All together now!", "Sing along!"])
        text += ' ' + song["video"]
        if hashtag:
            text += ' ' + hashtag

        in_reply_to_id_str = self._send_to(
            inbox_item=inbox_item,
            text=text,
            target=target,
            in_reply_to_id_str=None)
        time.sleep(5)

        lastlyrics = set([])
        for lyric in song["lyrics"]:
            lyric = lyric.strip()
            if lyric:
                if "<<screen_name>>" in lyric:
                    lyric = lyric.replace("<<screen_name>>", "@" + target)
                if hashtag:
                    lyric += " " + hashtag
                while lyric in lastlyrics:
                    lyric += random.choice(self.mutation)
                lastlyrics.add(lyric)
                self.identity.statistics.record_outgoing_song_lyric()
                in_reply_to_id_str = self._send_to(
                    inbox_item,
                    lyric,
                    target,
                    in_reply_to_id_str)
                time.sleep(5)

    def _send_to(self, inbox_item, text, target, in_reply_to_id_str):
        if inbox_item:
            return self.reply_with(
                inbox_item=inbox_item,
                text=text,
                in_reply_to_id_str=in_reply_to_id_str)
        else:
            status = ""
            if target:
                # noinspection PyUnresolvedReferences
                if isinstance(target, basestring):
                    status = ".@" + target
                elif isinstance(target, User.User):
                    status = ".@" + target.screen_name
            status += " " + text
            tweet = OutgoingTweet(
                text=status,
                in_reply_to_id_str=in_reply_to_id_str)
            return self.send(tweet)

    @retry(**retry_args)
    def get_list_subscriptions(self):
        return self.twitter.get_list_subscriptions()

    @retry(**retry_args)
    def subscribe_to_list(self, list_id):
        return self.twitter.subscribe_to_list(list_id=list_id)

    @retry(**retry_args)
    def geocode(self, location):
        result = self.twitter.search_geo(
            query=location.full_name,

            max_results=5,
            lat=location.latitude,
            long=location.longitude)
        logger.info(result)
        if result["result"]["places"]:
            # for place in result["result"]["places"]:
            #     logger.info(place["full_name"])

            place = result["result"]["places"][0]
            location.place_id_twitter = place["id"]

            return location
        else:
            return None

    @retry(**retry_args)
    def reverse_geocode(self, location):

        result = self.twitter.reverse_geocode(

            max_results=5,
            lat=location.latitude,
            long=location.longitude)
        logger.info(result)
        if result["result"]["places"]:
            # for place in result["result"]["places"]:
            #     logger.info(place["full_name"])

            place = result["result"]["places"][0]
            location.place_id_twitter = place["id"]

            return location
        else:
            return None

    @retry(**retry_args)
    def update_profile_image(self, file_path):
        if file_path:
            logger.info("updating profile image %s" % file_path)
            with open(file_path, 'rb') as file:
                self.twitter.update_profile_image(image=file)

    @retry(**retry_args)
    def update_profile_banner_image(self, file_path):
        if file_path:
            logger.info("updating banner image %s" % file_path)
            with open(file_path, 'rb') as file:
                try:
                    self.twitter.update_profile_banner_image(banner=file)
                except TwythonError as ex:
                    if "Response was not valid JSON" in str(ex):
                        # twython issue i think
                        logger.warning(ex)
                    else:
                        raise

    @retry(**retry_args)
    def update_profile(self, **kwargs):
        return self.twitter.update_profile(**kwargs)

    @retry(**retry_args)
    def get_list_statuses(self, **kwargs):
        return self.twitter.get_list_statuses(**kwargs)

    @retry(**retry_args)
    def get_user_suggestions_by_slug(self, **kwargs):
        return self.twitter.get_user_suggestions_by_slug(**kwargs)

    @retry(**retry_args)
    def get_user_suggestions(self, **kwargs):
        return self.twitter.get_user_suggestions(**kwargs)

    @retry(**retry_args)
    def lookup_status(self, **kwargs):
        return self.twitter.lookup_status(**kwargs)

    @retry(**retry_args)
    def get_followers(self, **kwargs):
        kwargs["stringify_ids"] = True
        followers = set()
        cursor = -1
        while cursor != "0":
            kwargs["cursor"] = cursor
            logger.info("getting followers")
            response = self.twitter.get_followers_ids(**kwargs)
            cursor = response["next_cursor_str"]
            followers = followers.union(set(response["ids"]))

        return followers

    @retry(**retry_args)
    def get_following(self, **kwargs):
        kwargs["stringify_ids"] = True
        following = set()
        cursor = -1
        while cursor != "0":
            kwargs["cursor"] = cursor
            logger.info("getting following")
            response = self.twitter.get_friends_ids(**kwargs)
            cursor = response["next_cursor_str"]
            following = following.union(set(response["ids"]))
        return following

    @retry(**retry_args)
    def update_rate_limits(self):
        data = self.twitter.get_application_rate_limit_status()
        self.rates = RateLimits(data)
        logger.info("Updated rate limits for {}: {}".format(self.identity.screen_name, self.rates.display()))

    def _rate_limit(self, limit_name, func, *args, **kwargs):
        if self.rates.can(limit_name):
            try:
                return func(*args, **kwargs)
            except Exception as ex:
                logger.warning(ex)
                return None
        else:
            logger.warning("{} limit exceeded".format(limit_name))
            return None

    @retry(**retry_args)
    def get_statuses(self, id_strs):
        id_strs_csv = ",".join(id_strs)
        return self.twitter.lookup_status(id=id_strs_csv)

    @retry(**retry_args)
    def get_status(self, id_str):
        return self.twitter.show_status(id=id_str)
Exemple #23
0
class TweetBot:
	def __init__(self, app_key, app_secret, oauth_token, oauth_token_secret):
		self.account = Twython(app_key, app_secret, oauth_token, oauth_token_secret)
		self.step = 15 

	def verify_credentials(self):
		# https://dev.twitter.com/rest/reference/get/account/verify_credentials
		info = self.account.verify_credentials(include_entities=False, skip_status=True, include_email=False)
		name = info.get('name', None)
		if name is None:
			log.error('Could not verify credentials')
		else:
			log.info('Logged in as @{name}, tweets: {tweets}, followers: {followers}'.format(
				name = name,
				tweets = info['statuses_count'],
				followers = info['followers_count']))
		return info

	def upload_twitter_picture(self, picture_path):
		photo = open(picture_path, 'rb')
		log.debug("Uploading '{}'".format(picture_path))
		response = self.account.upload_media(media=photo)
		return response['media_id']

	def reply_media_tweet(self, status, reply_id, media_path):
		media_id = self.upload_twitter_picture(media_path)
		tweet = self.account.update_status(status=status, media_ids=[media_id], in_reply_to_status_id=reply_id)
		return tweet

	def reply_text_tweet(self, status, reply_id):
		tweet = self.account.update_status(status=status, in_reply_to_status_id=reply_id)
		log.info('Responded with text to {}'.format(reply_id))
		return tweet

	def rate_limit_remaining(self):
		rate_limit = self.account.get_lastfunction_header('x-rate-limit-remaining')
		log.info('Rate limit remaining: {}'.format(rate_limit))
		return rate_limit

	def favorite(self, status_id):
		tweet = self.account.create_favorite(id=status_id)
		log.debug('Favorited tweet {}'.format(status_id))
		return tweet

	# Find first tweet mentioning any element of query_list_OR
	# in the tweet text (excluding user names).
	# Only tweets for which predicate_func(tweet) is truthy are returned.
	# Returns a tuple of the found status/tweet and what element of
	# the query_list_OR was identified.
	# Returns (None, None) if no matching tweets were found.
	def find_single_tweet(self, query_list_OR, predicate_func):
		counter = 0
		while counter <= len(query_list_OR):
			current_query = query_list_OR[counter:counter+self.step]
			log.debug("Searching for '{}'".format(', '.join(current_query)))
			statuses = self.account.search(q=' OR '.join(current_query), count=50)['statuses']
			log.debug("Found {} matching tweets".format(len(statuses)))
			self.rate_limit_remaining()
			counter += self.step
			for status in statuses:
				# Should be able to identify which part of the query list was mentioned
				text = status['text'].lower()
				found = None
				for query_item in current_query:
					if text.rfind(query_item.lower()) > -1:
						found = query_item
						break
				if found is None:
					continue
				# Identified query part should not be part of tweeting user's name
				if found.lower() in status['user']['screen_name'].lower():
					continue
				# Identified query part should not be part of a mentioned user's name
				mentions = status['entities'].get('user_mentions')
				for m in mentions:
					if found.lower() in m['screen_name'].lower():
						continue
				# Identified query part should not be in user name being replied to
				if found.lower() in (status['in_reply_to_screen_name'] or '').lower():
					continue
				# Should return True for the passed predicate_func
				if not predicate_func(status):
					continue
				log.info(TWITTER_STATUS_URL_TEMPLATE.format(id=status['id']))
				log.info(status['text'].replace('\n',' '))
				return (status, found)
		log.warn("No tweets matching '{}' were found".format(query_list_OR))
		return (None, None)
Exemple #24
0
#!/usr/local/bin/python3.5
#This module Retweets and favourites every post that has #bottest2017. Try it out!
#BE AWARE: This script was written to run on a raspberry pi specifically

from twython import TwythonStreamer, Twython, TwythonError

#Create a .txt file in the directory of your script with your API keys.
keys = {}
with open("API_keys.txt") as f:
    for line in f:
        (key, val) = line.split()
        keys[int(key)] = val

api = Twython(keys[1], keys[2], keys[3], keys[4])

search_results = api.search(q="#bottest2017", count=100)
try:
    for tweet in search_results["statuses"]:
        api.retweet(id=tweet["id_str"])
        api.create_favorite(id=tweet["id_str"])
        print("I favourited and retweeted a couple of tweets!")
except TwythonError as e:
    print(e)
Exemple #25
0
class Winston:
    def __init__(self):
        self.bot = Twython(
            app_key=get_secret("CONSUMER_KEY"),
            app_secret=get_secret("CONSUMER_SECRET"),
            oauth_token=get_secret("ACCESS_TOKEN_KEY"),
            oauth_token_secret=get_secret("ACCESS_TOKEN_SECRET"))
        self.potential_tweets = [
            "@PlayOverwatch I didn't pay my taxes!",
            "I'm wanted in over 60 countries!", "Overwatch.", "Echo!",
            "@PlayOverwatch #LetWinstonWallRide",
            "@PlayOverwatch #LetWinstonWallClimb",
            "Please Delete Echo\n\nSincerely, Winston From Overwatch\n\n@PlayOverwatch",
            "Year of the Winston Event When? @PlayOverwatch", "Is This On?",
            "How Embarrassing!", "Winston From Overwatch.",
            "Is it too much to ask for some peanut butter covered toes? @PlayOverwatch",
            "I'm holding Sigma hostage in Paris.\nFor every hour Echo isn't nerfed, I will remove one of his toes.\n\n@PlayOverwatch",
            "My new year's resolutions: Less peanut butter, more... bananas.",
            "I'm feeling unstoppable!",
            "I have a crippling addiction to peanut butter."
        ]
        self.potential_tweets_with_images = [
            ["Are You With Me? @PlayOverwatch", "winston_grin.jpg"],
            ["You won't like me when I'm angry.", "winston_angry.jpg"],
            ["Look out world! I'm on a rampage!", "winston_primal_rage.jpg"],
            ["Holy Shit.", "overwatch_meme.jpg"]
        ]

    def send_tweet(self, tweet_text):
        """Sends a tweet to Twitter"""

        self.bot.update_status(status=tweet_text)
        logger.info(f"Tweet Sent: '{tweet_text}'")

    def send_random_tweet(self):
        """Tweet something random from potential tweets"""

        result = random.choice([True, False])
        if result:
            random_tweet = random.choice(self.potential_tweets)
            self.send_tweet(random_tweet)
        else:
            random_tweet_with_image = random.choice(
                self.potential_tweets_with_images)
            self.tweet_with_media(random_tweet_with_image)

    def tweet_with_media(self, text_and_media):
        """Tweet with media + optional text"""

        text = text_and_media[0]
        filename = text_and_media[1]

        path = f"./bot/media/{filename}"
        media = open(path, 'rb')

        try:
            response = self.bot.upload_media(media=media)
            self.bot.update_status(status=text,
                                   media_ids=[response['media_id']])
            logger.info(
                f"Tweet Sent With Image: || Tweet: {text} || Image Name: {filename}"
            )
        except TwythonError as error:
            print(error.msg)

    def follow_someone(self, username):
        """Follows someone based on given id"""

        self.bot.create_friendship(screen_name=username)
        logger.info(f"Followed User: "******"""Likes a tweet based on it's ID"""

        self.bot.create_favorite(id=tweet_id)
        logger.info(f"Liked Tweet, Tweet ID: " f'{tweet_id}')
def main(episodenumber, live_tweet, testmode):
    
    import sqlite3 as lite
    from twython import Twython    
    import os
    import warnings
    warnings.filterwarnings("ignore")

    dir = os.path.dirname(__file__)
    filename = os.path.join(dir, '../tweets.db')
    con = lite.connect(filename)
    
    import twitterconfig 
    twitter = Twython(twitterconfig.APP_KEY, twitterconfig.APP_SECRET, twitterconfig.OAUTH_TOKEN, twitterconfig.OAUTH_TOKEN_SECRET)

    
    top_retweets = '' 
    striketweet = '#Tatort - Ins Schwarze getwittert: '
    top_tweeters = [] 
    
    
    with con:
        
        cur = con.cursor()
        command = 'SELECT * FROM tatorttweets WHERE lfd =  ' + str(episodenumber) + ' ORDER BY retweet_count DESC LIMIT 10' 

        cur.execute(command)
        rows = cur.fetchall()
        for row in rows:
            if testmode: print row[2]
            
            newtweet = striketweet + ' \n@' + row[2] 
            if not ((len(newtweet) > 140) or (row[2] in top_tweeters)): 
                striketweet = newtweet 
                top_tweeters.append(row[2])
            try: 
                twitter.create_friendship(screen_name=row[2])
            except Exception as e: 
                if testmode: print e

            if testmode: print row[4]

            searchstring = '"' + row[4] + '"'

            response = twitter.search(q=searchstring, include_entities=1, count=100)
            for tweet in response['statuses']: 
                if 'RT @' not in tweet['text'] and (row[2] == tweet['user']['screen_name']): 
                    oembed = twitter.get_oembed_tweet(id=tweet['id'])
#                     print oembed['html']
                    try: 
                        twitter.create_favorite(id=tweet['id'])
                        twitter.retweet(id=tweet['id'])
                    except Exception as e: 
                        if testmode: print e

                    top_retweets += oembed['html'].encode('utf-8') + " <br />\n"
                
        
        topretweetsfilename = os.path.join(dir, "../FlaskWebProject/templates/top_retweets/top_retweets_" + str(episodenumber) + ".txt")
        topretweetsfile = open(topretweetsfilename, "w")
#         print top_retweets 
        print >> topretweetsfile, top_retweets
        topretweetsfile.close()
        
#         cmd = "scp -P 50001 " + topretweetsfilename + " [email protected]:../public/tatorttweets/FlaskWebProject/templates/top_retweets/top_retweets_" + str(episodenumber) + ".txt"
#         print cmd
#         os.system(cmd)
        
        if testmode: print 
        if testmode: print striketweet
        if testmode: print len(striketweet)
        
        
        
        if live_tweet: 
            try:
                twitter.update_status(status=striketweet)
                twitter.update_status(status="Die meist-retweeted #Tatort tweets: http://tatort.mash-it.net/" + str(episodenumber) + "#Strike")
            except Exception as e: 
                if testmode: print e
Exemple #27
0
class MainWindow(object):
    def __init__(self, c_key, c_secret, a_key, a_secret):
        self.win = curses.initscr()
        curses.noecho()
        curses.cbreak()
        locale.setlocale(locale.LC_ALL, "")
        self.max_y, self.max_x = self.win.getmaxyx()
        self.win.refresh()
        self.mwin = self.win.subwin(self.max_y-2, self.max_x, 0, 0)
        self.mwin.scrollok(True)
        self.cmdbar = self.win.subwin(1, self.max_x, self.max_y-1, 0)
        self.statbar = self.win.subwin(1, self.max_x, self.max_y-2, 0)
        self.statbar.bkgd("-")

        self.latest_id = 0
        self.loaded_statuses = []
        

        self.plugin = []
        self.key_bind = {}
        self.add_plugin(default_plugin(self))
        self.change_modename("Waiting")

        self.api = Twython(c_key, c_secret, a_key, a_secret)
        self.streamer = cmaletter_streamer(self, c_key, c_secret, a_key, a_secret)

        self.get_home_timeline(num = 40)
        
    def main(self):
        while 1:
            key = self.cmdbar.getkey()

            if key == "q":
                break
            
            if key in self.key_bind:
                name, func = self.key_bind[key]
                self.change_modename(name)
                func(self.mwin)
                self.change_modename("Waiting")

                curses.curs_set(0)

            self.show_timeline()

        curses.nocbreak()
        curses.echo()
        curses.endwin()

    def add_plugin(self, cls):
        self.plugin.append(cls)
        for name, func, bind in cls.cmd_list:
            self.key_bind[bind] = (name, func)
        
    def get_home_timeline(self, num=-1):
        if num == -1:
            statuses = self.api.get_home_timeline(since_id = self.latest_id)
        else:
            statuses = self.api.get_home_timeline(count = num)
            
        for status in statuses[::-1]:
            self.on_status(status)
            self.latest_id = status['id']

    def get_loaded_status(self):
        return self.loaded_statuses
            
    def user_input(self):
        self.cmdbar.erase()
        self.cmdbar.refresh()
        curses.echo()
        input = self.cmdbar.getstr()
        curses.noecho()
        return input

    def fit_window(self):
        self.max_y, self.max_x = self.win.getmaxyx()
        self.mwin.resize(self.max_y-2, self.max_x)
        self.mwin.mvwin(0,0)
        self.statbar.resize(1,self.max_x)
        self.statbar.mvwin(self.max_y-2, 0)
        self.cmdbar.resize(1, self.max_x)
        self.cmdbar.mvwin(self.max_y-1, 0)
        self.win.refresh()
        
    def show_timeline(self, all=False):
        self.fit_window()
        self.mwin.erase()
        length = len(self.loaded_statuses)
        if all == True:
            show_range = range(length)
        else:
            show_range = range(max(0, length-self.max_y), length)

        for i in show_range:
            status = self.loaded_statuses[i]
            self.mwin.addstr("\n%s:%s" % (status['user']['screen_name'], status['text']))
        self.mwin.refresh()
    
    def tweet(self, content, in_reply_to=None):
        if in_reply_to == None:
            self.api.update_status(status=content)
        else:
            self.api.update_status(status=content, in_reply_to_status_id=in_reply_to) 

    def retweet(self, id):
        self.api.retweet(id=id)

    def create_favorite(self, id):
        self.api.create_favorite(id=id)
        
    def change_modename(self, name):
        self.modename = name
        self.statbar_refresh()

    def statbar_refresh(self):
        self.statbar.erase()
        self.statbar.addstr("  (%s)" % self.modename)
        self.statbar.refresh()

    def cmdbar_output(self, text):
        self.cmdbar.erase()
        self.cmdbar.addnstr(text, self.max_x)
        self.cmdbar.refresh()
        
    def on_status(self, status):
        self.mwin.addstr("%s: %s\n" % (status['user']['screen_name'], status['text']))
        self.mwin.refresh()
        self.loaded_statuses.append(status)
Exemple #28
0
class TmBot(object):
   '''
      The class that actually runs the bot.
   '''

   def __init__(self, argDict=None):
      if not argDict:
         argDict = { 'debug' : False, "force": False, 'stream': False, 'botPath' : "."}
      # update this object's internal dict with the dict of args that was passed
      # in so we can access those values as attributes.
      self.__dict__.update(argDict)

      # we build a list of dicts containing status (and whatever other args
      # we may need to pass to the update_status function as we exit, most
      # probably 'in_reply-to_status_id' when we're replying to someone.)
      self.tweets = []

      self.settings = Settings(self.GetPath("ajjthebot.json"))
      self.history = Settings(self.GetPath("ajjthebot_history.json"))
      s = self.settings
      if self.stream:
         self.twitter = BotStreamer(s.appKey, s.appSecret, s.accessToken, s.accessTokenSecret)
         self.twitter.SetOutputPath(self.botPath)
      else:
         self.twitter = Twython(s.appKey, s.appSecret, s.accessToken, s.accessTokenSecret)

   def GetPath(self, path):
      '''
         Put all the relative path calculations in one place. If we're given a path
         that has a leading slash, we treat it as absolute and do nothing. Otherwise,
         we treat it as a relative path based on the botPath setting in our config file.
      '''
      if not path.startswith(os.sep):
         path = os.path.join(self.botPath, path)
      return path

   def Log(self, eventType, dataList):
      '''
         Create an entry in the log file. Each entry will look like:
         timestamp\tevent\tdata1\tdata2 <etc>\n
         where:
         timestamp = integer seconds since the UNIX epoch
         event = string identifying the event
         data1..n = individual data fields, as appropriate for each event type.
         To avoid maintenance issues w/r/t enormous log files, the log filename
         that's stored in the settings file is passed through datetime.strftime()
         so we can expand any format codes found there against the current date/time
         and create e.g. a monthly log file.
      '''
      now = int(time())
      today = datetime.fromtimestamp(now)
      fileName = self.settings.logFilePath
      if not fileName:
         fileName = "%Y-%m.txt"
         self.settings.logFilePath = fileName
      path = self.GetPath(fileName)
      path = today.strftime(path)
      with open(path, "a+t") as f:
         f.write("{0}\t{1}\t".format(now, eventType))
         f.write("\t".join(dataList))
         f.write("\n")

   def SendTweets(self):
      ''' send each of the status updates that are collected in self.tweets
      '''
      for msg in self.tweets:
         if self.debug:
            print msg['status'].encode("UTF-8")
         else:
            self.twitter.update_status(**msg)


   def CheckDaySpacing(self, album, title):
      ''' There are a few tunes that seem to come up *way* too often. We'll maintain 
         a new history file that just tracks the last time that any given (album, track) tuple
         is used (and maybe this should just be title?). If we're okay to use this song, return 
         true. 
      '''
      key = "{0}_{1}".format(album, title)
      retval = True
      lastUsed = self.history[key]
      if lastUsed:
         minimumSpace = self.settings.minimumDaySpacing
         if not minimumSpace:
            minimumSpace = 30
            self.settings.minimumDaySpacing = minimumSpace
         today = date.today()
         last = date.fromordinal(lastUsed)
         # how many days has it been since we last tweeted this album/track?
         daysAgo = (today - last).days
         retval =  daysAgo > minimumSpace
         if not retval:
            self.Log("TooSoon", [album, title, "used {0} days ago".format(daysAgo)])
      return retval


   def LogHistory(self, album, title):
      today = date.today()
      key = "{0}_{1}".format(album, title)
      self.history[key] = today.toordinal()

   def CreateUpdate(self):
      '''
         Called everytime the bot is Run().
         If a random number is less than the probability that we should generate
         a tweet (or if we're told to force one), we look into the lyrics database
         and (we hope) append a status update to the list of tweets.

         1/11/14: Added a configurable 'minimumSpacing' variable to prevent us from
         posting an update too frequently. Starting at an hour ()

      '''
      doUpdate = False
      last = self.settings.lastUpdate or 0
      now = int(time())
      lastTweetAge = now - last

      maxSpace = self.settings.maximumSpacing
      if not maxSpace:
         # default to creating a tweet at *least* every 4 hours.
         maxSpace = 4 * 60 * 60
         self.settings.maximumSpacing = maxSpace

      if lastTweetAge > maxSpace:
         # been too long since the last tweet. Make a new one for our fans!
         doUpdate = True

      elif random() < self.settings.tweetProbability:
         # Make sure that we're not tweeting too frequently. Default is to enforce
         # a 1-hour gap between tweets (configurable using the 'minimumSpacing' key
         # in the config file, providing a number of minutes we must remain silent.)
         requiredSpace = self.settings.minimumSpacing
         if not requiredSpace:
            # no entry in the file -- let's create one. Default = 1 hour.
            requiredSpace = 60*60
            self.settings.minimumSpacing = requiredSpace

         if lastTweetAge > requiredSpace:
            # Our last tweet was a while ago, let's make another one.
            doUpdate = True

      if doUpdate or self.force:
         try:
            # Occasionally force some short(er) updates so they're not all
            # paragraph-length.. (these values arbitrarily chosen)
            maxLen = choice([120, 120, 120, 120, 100, 100, 100, 80, 80, 40])
            album, track, msg = self.GetLyric(maxLen)
            self.tweets.append({'status' : msg})
            self.settings.lastUpdate = int(time())
            # we'll log album name, track name, number of lines, number of characters
            self.Log("Tweet", [album, track, str(1 + msg.count("\n")), str(len(msg))])
         except NoLyricError:
            self.Log("NoLyric", [])
            pass

   def HandleMentions(self):
      '''
         Get all the tweets that mention us since the last time we ran and process each
         one.
         Any time we're mentioned in someone's tweet, we favorite it. If they ask
         us a question, we reply to them.
      '''
      mentions = self.twitter.get_mentions_timeline(since_id=self.settings.lastMentionId)
      if mentions:
         # Remember the most recent tweet id, which will be the one at index zero.
         self.settings.lastMentionId = mentions[0]['id_str']
         for mention in mentions:
            who = mention['user']['screen_name']
            text = mention['text']
            theId = mention['id_str']

            # we favorite every mention that we see
            if self.debug:
               print "Faving tweet {0} by {1}:\n {2}".format(theId, who, text.encode("utf-8"))
            else:
               self.twitter.create_favorite(id=theId)

            eventType = 'Mention'
            # if they asked us a question, reply to them.
            if "?" in text:
               # create a reply to them.
               maxReplyLen = 120 - len(who)
               album, track, msg = self.GetLyric(maxReplyLen)
               # get just the first line
               msg = msg.split('\n')[0]
               # In order to post a reply, you need to be sure to include their username
               # in the body of the tweet.
               replyMsg = "@{0} {1}".format(who, msg)
               self.tweets.append({'status': replyMsg, "in_reply_to_status_id" : theId})
               eventType = "Reply"

            self.Log(eventType, [who])



   def HandleQuotes(self):
      ''' The streaming version of the bot may have detected some quoted tweets
         that we want to respond to. Look for files with the .fav extension, and 
         if we find any, handle them. 
      '''
      faves = glob(self.GetPath("*.fav"))
      for fileName in faves:
         with open(fileName, "rt") as f:
            tweetId = f.readline().strip()
            if self.debug:
               print "Faving quoted tweet {0}".format(tweetId)
            else:
               try:
                  self.twitter.create_favorite(id=tweetId)
               except TwythonError as e:
                  self.Log("EXCEPTION", str(e))
         os.remove(fileName)


   def Run(self):
      if self.stream:
         if self.debug:
            print "About to stream from user account."
         try:
            # The call to user() will sit forever waiting for events on 
            # our user account to stream down. Those events will be handled 
            # for us by the BotStreamer object that we created ab
            self.twitter.user()
         except KeyboardInterrupt:
            # disconnect cleanly from the server.
            self.twitter.disconnect()
      else:
         self.CreateUpdate()
         self.HandleMentions()
         self.HandleQuotes()
         self.SendTweets()

         # if anything we dpsid changed the settings, make sure those changes get written out.
         self.settings.lastExecuted = str(datetime.now())
         self.settings.Write()
         self.history.Write()


   def GetLyric(self, maxLen, count=10):
      ''' open a random lyric file, then grab a random stanza of lyrics from it,
         then (if needed) trim it down into lines <= maxLen
         returns a tuple (album, track, stanza) (we may want to log the album/tracks
            that are being used...)

         If we don't immediately find a random chunk of text that meets the maxLen
         criteria, we call ourself recursively, decrementing the count parameter until
         it hits zero, at which point we give up and raise an exception. Obviously, we
         could look for a longer time, or come up with a search algorithm to find text
         meets the current length criteria, or, or, or..., but I actually like the idea
         that it's possible to occasionally just throw up our hands and give up. We'll
         try again in a bit.
      '''
      if 0 == count:
         raise NoLyricError()

      files = glob(self.GetPath(self.settings.lyricFilePath))
      if not files:
         # there aren't any lyrics files to use -- tell them to  GetLyrics
         raise LyricsFileError("Please run GetLyrics.py to fetch lyric data first.")

      fName = choice(files)
      album, track = ParseFilename(fName)
      # Check to see if it's been long enough since we tweeted from this song:
      if not self.CheckDaySpacing(album, track):
         return self.GetLyric(maxLen, count-1)
      stanza = ""
      with open(fName, "rt") as f:
         data = f.read().decode("utf-8")
         stanzas = data.split("\n\n")
         stanza = choice(stanzas).strip().split('\n')
         stanza = TrimTweetToFit(stanza, maxLen)

      if stanza:
         self.LogHistory(album, track)
         return (album, track, stanza)
      else:
         return self.GetLyric(maxLen, count-1)
Exemple #29
0
class Twitter:
    twitter = None

    def __init__(self):
        twitter_credential = self.importCredential()
        self.twitter = Twython(
            twitter_credential['api_key'],
            twitter_credential['api_secret_key'],
            twitter_credential['access_token'],
            twitter_credential['access_token_secret']
        )  

    def importCredential(self):
        twitter_credential = {}
        with open('credentials.json') as f:
            credential = json.load(f)
        twitter_credential = credential['twitter'] 
        return twitter_credential

    def getHomeTimeline(self, count=200):
        timeline = self.twitter.get_home_timeline(count=count)
        return timeline
    
    def getUserTimeline(self, screen_name, count=200):
        timeline = self.twitter.get_user_timeline(screen_name=screen_name, count=count)
        return timeline
        
    def postTweet(self, message):
        self.twitter.update_status(status=message)
        print("Tweeted: " + message)

    def replyTweet(self, message, tweet_id):
        selected_tweet = self.twitter.show_status(id=tweet_id)
        mention_tweet_owner = '@' + selected_tweet['user']['screen_name']
        message = mention_tweet_owner + ' ' + message
        self.twitter.update_status(status=message, in_reply_to_status_id=tweet_id)
        print("Tweeted reply: " + message)

    def retweet(self, tweet_id):
        self.twitter.retweet(id=tweet_id)
        print(tweet_id + " Retweeted!")

    def getClosestTrend(self):
        locationResponse = requests.get('https://freegeoip.app/json/')
        location = locationResponse.json()
        locationTwitter = self.twitter.get_closest_trends(lat=location['latitude'], long=location['longitude'])
        trends = self.twitter.get_place_trends(id=int(locationTwitter[0]['woeid']))
        trends = trends[0]['trends']
        return trends

    def getWorldWideTrend(self):
        trends = self.twitter.get_place_trends(id=1, exclude="words")
        trends = trends[0]['trends']
        return trends

    def selectHashtagFromTrend(self, trends):
        hashtagTrend = ""
        for trend in trends:
            if (trend['name'].find('#') != -1):
                hashtagTrend = trend['name']
                break 
        return hashtagTrend

    def likeTweet(self, tweet_id):
        self.twitter.create_favorite(id=tweet_id)
        print(tweet_id + " liked!")

    def getFollowersList(self, screen_name, cursor=-1):
        fetchCount = 5
        followers = self.twitter.get_followers_list(screen_name=screen_name, count=fetchCount, cursor=cursor)
        return followers

    def followAccount(self, screen_name):
        self.twitter.create_friendship(screen_name=screen_name)
        print ("following : " + screen_name)