コード例 #1
0
def generate_graphs():
    for pair_config in KEYS:
        media_ids = []
        tweet = ''
        for interval in ['day', 'week', 'month', 'year']:
            text = output_graph(interval, pair_config)
            if not text:
                continue
            tweet += text
            if args.tweeting and pair_config['APP_KEY']:
                twitter = Twython(pair_config['APP_KEY'], pair_config['APP_SECRET'],
                                  pair_config['OAUTH_TOKEN'], pair_config['OAUTH_TOKEN_SECRET'])
                photo = open('{0}-{1}.png'.format(interval, pair_config['screen_name']), 'rb')
                try:
                    response = twitter.upload_media(media=photo)
                except TwythonError:
                    client.captureException()
                    return True
                media_ids += [response['media_id']]
            time.sleep(10)
        if args.tweeting and pair_config['APP_KEY']:
            twitter = Twython(pair_config['APP_KEY'], pair_config['APP_SECRET'],
                            pair_config['OAUTH_TOKEN'], pair_config['OAUTH_TOKEN_SECRET'])
            try:
                for status in twitter.get_user_timeline(screen_name=pair_config['screen_name']):
                    twitter.destroy_status(id=status['id_str'])
                twitter.update_status(status=tweet, media_ids=media_ids)
            except TwythonError:
                client.captureException()
コード例 #2
0
ファイル: clean.py プロジェクト: honishi/tweet-cleaner
def clean_tweet(screen_name, clean_interval, clean_threshold,
                consumer_key, consumer_secret, access_key, access_secret):
    while True:
        try:
            twitter = Twython(consumer_key, consumer_secret, access_key, access_secret)
            my_statuses = twitter.get_user_timeline(screen_name=screen_name)
            # logging.debug(my_statuses)

            clean_base_datetime = (datetime.datetime.now()
                                   - datetime.timedelta(seconds=clean_threshold))

            for status in my_statuses:
                status_id = status['id']
                created_at = datetime.datetime.strptime(status['created_at'],
                                                        '%a %b %d %H:%M:%S +0000 %Y')
                text = status['text']
                # logging.debug("id:{} created_at:{} text:{}".format(status_id, created_at, text))

                should_destroy = (created_at < clean_base_datetime)
                if should_destroy:
                    logging.info("removing status:{} {} {}".format(status_id, created_at, text))
                    twitter.destroy_status(id=status_id)
                    # logging.info("removed status")
                    # raise Exception()

        except Exception as exception:
            logging.error("caught exception:{}".format(exception))

        logging.debug("sleeping {} seconds...".format(clean_interval))
        time.sleep(clean_interval)
コード例 #3
0
ファイル: twdelall.py プロジェクト: saravan2/twython-scripts
def main():
    try:

        notDeleted = 0

        # Command line processing
        if len(sys.argv) > 1:
            usage()
            printf("Ignoring unwanted arguments")

        twitter = Twython(twiden.twitter_app_key, twiden.twitter_app_secret,
                          twiden.twitter_oauth_token,
                          twiden.twitter_oauth_token_secret)

        while True:

            timeline = twitter.get_user_timeline(count=50)

            if (len(timeline) == 0):
                print("** No tweets left to delete **")
                break

            for tweet in timeline:
                print(tweet)
                break
                tw_user_id = tweet['user']['id']
                tw_id = tweet['id']
                tw_user_mentions = tweet['entities']['user_mentions']
                print("Attempting to delete : {}".format(tweet['text']))
                try:
                    twitter.destroy_status(id=tw_id)
                except TwythonError as tei:
                    print(
                        "User id : {}\nTweet id : {}\nTweet : {}\nUser Mentions : {}\n**could not be deleted**\n"
                        .fortmat(tw_user_id, tw_id, tweet['text'],
                                 tw_user_mentions))
                    print(tei)
                    notDeleted += 1
                    pass
            time.sleep(60)

        #End of while

        if notDeleted:
            print("** {} tweets could not be deleted **".fortmat(notDeleted))
    except TwythonError as te:
        print(te)
    except SystemExit as se:
        sys.exit(se)
    except:
        traceback.print_exc(file=sys.stdout)
    sys.exit(0)
コード例 #4
0
def delete_tweet(id):
    #get credentials
    twitter = Twython(credentials.consumer_key, credentials.consumer_secret,
                      credentials.access_token,
                      credentials.access_token_secret)
    response = twitter.destroy_status(id=id)
    return response
コード例 #5
0
ファイル: __init__.py プロジェクト: pfischi/shTwitter
class TwitterStreamer(TwythonStreamer):
    def __init__(self, plugin, app_key, app_secret, oauth_token, oauth_token_secret):
        self.plugin = plugin
        self.app_key = app_key
        self.app_secret = app_secret
        self.oauth_token = oauth_token
        self.oauth_token_secret = oauth_token_secret
        TwythonStreamer.__init__(self, self.app_key, self.app_secret, self.oauth_token, self.oauth_token_secret)
        self.twitter_api = Twython(self.app_key, self.app_secret, self.oauth_token, self.oauth_token_secret)

    def on_success(self, data):
        if 'text' in data:
            item_data = data['text'].lower()
            self.plugin.update_items_with_data(item_data)
            self.twitter_api.destroy_status(id=data['id'])

    def on_error(self, status_code, data):
        print(status_code)
コード例 #6
0
class tweetdelete:
    def __init__(self, token_file, read_default_file, database):

        # Initialize Twitter
        if not os.path.isfile(token_file):
            print(f'Could not find {token_file}. We need to reauthenticate.')
            self.authenticate(token_file)
        self.keys = json.load(open(token_file))
        self.twitter = Twython(**self.keys)

        # Open connection to database
        self.db = pymysql.connect(read_default_file=read_default_file,
                                  database=database)
        self.c = self.db.cursor()

        # Check if database is empty, indicating this is a first run
        # Direct user to initial setup using the Twitter archive
        if not self.c.execute("""SELECT * FROM tweetdelete"""):
            self.initialize_from_archive()

    def authenticate(self, token_file):
        """ Authenticate with Twitter and save the OAUTH tokens"""

        keys = {}
        keys['app_key'] = input('Enter the App Consumer Key: ').strip()
        keys['app_secret'] = input('Enter the App Consumer Secret: ').strip()

        twitter = Twython(**keys)
        auth = twitter.get_authentication_tokens()

        keys['oauth_token'] = auth['oauth_token']
        keys['oauth_token_secret'] = auth['oauth_token_secret']
        auth_url = auth['auth_url']
        print(f'\nVisit this url to authorize the application: {auth_url}\n')
        oauth_verifier = input('Enter the PIN code: ')

        twitter = Twython(**keys)
        auth = twitter.get_authorized_tokens(oauth_verifier)
        keys['oauth_token'] = auth['oauth_token']
        keys['oauth_token_secret'] = auth['oauth_token_secret']

        with open(token_file, 'w') as fp:
            json.dump(keys, fp)

        print(f'The authorized user tokens were saved to {token_file}')

    def run(self, sql, data):
        """Execute SQL command with data payload"""
        try:
            self.c.execute(sql, data)
            self.db.commit()
            return True
        except Exception as e:
            self.db.rollback()
            print(f'Error: {e}')
            return False

    def flag_error(self, tweet_id):
        """Flag item as inaccesible via the API in the database"""
        sql = """UPDATE tweetdelete SET error = error + 1 WHERE id=%s"""
        if self.run(sql, tweet_id):
            return ' Flagged in database.'

    def initialize_from_archive(self):
        """Use Twitter archive to initialize the database"""

        msg = "\nThe `tweetdelete` database is currently empty. Because Twitter restricts API access " \
              "to older content we need to use the account archive to access the full account history. " \
              "Follow the instructions at the following link to download and extract your full archive: " \
              "\nhttps://help.twitter.com/en/managing-your-account/how-to-download-your-twitter-archive"
        path = input(f'{msg}\n\nEnter path to Twitter archive: ').strip()

        tweet_path = os.path.join(path, 'tweet.js')
        if not os.path.exists(tweet_path):
            sys.exit(
                f'tweet.js not found in {path}. Please try again with valid Twitter archive.'
            )

        like_path = os.path.join(path, 'like.js')
        if not os.path.exists(like_path):
            sys.exit(
                f'like.js not found in {path}. Please try again with valid Twitter archive.'
            )

        # Load the tweets and add to the database
        print('Parsing tweet.js')
        with open(tweet_path, 'r') as fp:
            tweets = fp.read()
        tweets = tweets.replace('window.YTD.tweet.part0 = ', '')
        count_tweets = 0
        for tweet in json.loads(tweets):
            tweet_id = int(tweet['id_str'])
            created_at = parser.parse(tweet['created_at'])

            sql = """INSERT INTO tweetdelete (id,created_at,kind) VALUES (%s,%s,0)"""
            data = (tweet_id, created_at)
            if self.run(sql, data):
                print(f'{tweet_id} added to database.')
                count_tweets += 1

        # Load the likes and add to the database
        # Note whether the tweet is actually favorited according to the API
        print('Parsing like.js')
        with open(like_path, 'r') as fp:
            likes = fp.read()
        likes = likes.replace('window.YTD.like.part0 = ', '')
        count_likes = 0
        for like in json.loads(likes):
            tweet_id = int(like['like']['tweetId'])

            try:
                # likes.js does not contain timestamps, use tweet as proxy
                tweet = self.twitter.show_status(id=tweet_id)
                created_at = parser.parse(tweet['created_at'])

                sql = """INSERT INTO tweetdelete (id,created_at,kind,favorited) VALUES (%s,%s,1,%s)"""
                data = (tweet_id, created_at, tweet['favorited'])
                if self.run(sql, data):
                    print(f'{tweet_id} added to database.')
                    count_likes += 1

            except Exception as e:
                print(f'Error retrieving {tweet_id}: {e}')

            sleep(1)

        print(
            f'Added {count_tweets} tweets and {count_likes} likes to the database'
        )

    def add_new_tweets(self):
        """Iterate through user timeline and add tweets to database."""

        # Most recent tweet in database is used to stop iteration
        ret = self.c.execute(
            """SELECT id FROM tweetdelete WHERE kind=0 ORDER BY id DESC LIMIT 1"""
        )
        max_id_db = self.c.fetchone()[0] if ret else 0

        keep_going = True
        max_id = None
        count = 0

        while keep_going:
            print(f'Loading tweets before: {max_id}')
            timeline = self.twitter.get_user_timeline(count=200,
                                                      max_id=max_id,
                                                      include_rts=True,
                                                      trim_user=True)

            if len(timeline) == 0:  # Reached end of timeline
                break

            for tweet in timeline:
                tweet_id = int(tweet['id_str'])
                created_at = parser.parse(tweet['created_at'])

                if tweet_id <= max_id_db:
                    keep_going = False
                    break

                sql = """INSERT INTO tweetdelete (id,created_at,kind) VALUES (%s,%s,0)"""
                data = (tweet_id, created_at)
                if self.run(sql, data):
                    print(f'{tweet_id} added to database.')
                    count += 1

            max_id = tweet_id - 1
            sleep(1)

        print(f'Added {count} tweets to the database')

    def add_new_likes(self):
        """Iterate through user likes and add tweets to database."""

        # Most recent like in database is used to stop iteration
        ret = self.c.execute(
            """SELECT id FROM tweetdelete WHERE kind=1 ORDER BY id DESC LIMIT 1"""
        )
        max_id_db = self.c.fetchone()[0] if ret else 0

        keep_going = True
        max_id = None
        count = 0

        while keep_going:
            print(f'Loading likes before: {max_id}')
            likes = self.twitter.get_favorites(count=200,
                                               max_id=max_id,
                                               include_entities=False)

            if len(likes) == 0:  # Reached end of likes
                break

            for like in likes:
                tweet_id = int(like['id_str'])

                if tweet_id <= max_id_db:
                    keep_going = False
                    break

                # Since the timestamp of likes is not available, we use the current timestamp
                created_at = gmtime()

                sql = """INSERT INTO tweetdelete (id,created_at,kind,favorited) VALUES (%s,%s,1,%s)"""
                data = (tweet_id, created_at, like['favorited'])
                if self.run(sql, data):
                    print(f'{tweet_id} added to database.')
                    count += 1

            max_id = tweet_id - 1
            sleep(1)

        print(f'Added {count} likes to the database')

    def cull_tweets(self):
        """Delete tweets more than 3 months old"""

        # Get all tweets in database more than 3 months old
        # Skip tweets with more than 10 errors
        sql = """
              SELECT id FROM tweetdelete
              WHERE
                kind = 0 AND
                error < 10 AND
                created_at < (NOW() - INTERVAL 3 MONTH)
              """
        self.c.execute(sql)
        tweets = self.c.fetchall()

        count = 0
        for tweet in tweets:
            tweet_id = tweet[0]
            msg = ''

            # Delete the tweet and remove from database
            try:
                self.twitter.destroy_status(id=tweet_id)
                count += 1
                msg += f'Deleted {tweet_id}.'
                if self.run("""DELETE FROM tweetdelete WHERE id=%s""",
                            tweet_id):
                    msg += ' Removed from database.'
            except Exception as e:
                msg += f'Error deleting {tweet_id} ({e}).'
                msg += self.flag_error(tweet_id)

            print(msg)
            sleep(1)

        print(f'Deleted {count} tweets')

    def cull_likes(self):
        """Unlike tweets more than 3 months old"""

        # Get all likes in database more than 3 months old that are
        # favorited according to the API. Skip tweets with more than 10 errors
        sql = """
              SELECT id FROM tweetdelete
              WHERE
                kind = 1 AND
                favorited = 1 AND
                error < 10 AND
                created_at < (NOW() - INTERVAL 3 MONTH)
              """
        self.c.execute(sql)
        likes = self.c.fetchall()

        count = 0
        for like in likes:
            tweet_id = like[0]
            msg = ''

            # Unlike the tweet
            try:
                self.twitter.destroy_favorite(id=tweet_id)
                count += 1
                msg += f'Unliked {tweet_id}.'
                if self.run("""DELETE FROM tweetdelete WHERE id=%s""",
                            tweet_id):
                    msg += ' Removed from database.'
            except Exception as e:
                msg += f'Error unliking {tweet_id} ({e}).'
                msg += self.flag_error(tweet_id)

            print(msg)
            sleep(1)

        print(f'Unliked {count} tweets')
コード例 #7
0
class TwitterBot:
    
    def __init__(self, name, con_k, con_s, acc_k, acc_s):
        self.name = name
        self.con_k = con_k
        self.con_s = con_s
        self.acc_k = acc_k
        self.acc_s = acc_s
        self.twitter = Twython(self.con_k, self.con_s, self.acc_k, self.acc_s)
        self.last_intervals = []
        # total number of trends you want to tweet
        self.num_trends = 3
        # number of seconds in a campaign window
        self.campaign_window = 600
        self.last_tweet = ""
        # tweets that will expire after a time limit
        self.temp_tweets = {}

    def tweet(self, msg):
        if self.twitter is not None:
            # > 140 char detection
            if len(msg) > 140:
                msg = msg[0:139]
            syslog.syslog('%s is tweeting %s' % (self.name, msg))
            try:
                tweet = self.twitter.update_status(status=msg)
                self.last_tweet = msg
                return tweet
            except Exception as e:
                syslog.syslog('%s error tweeting -> %s' % (self.name, str(e)))

    # Deletes a tweet from the given id
    def delete_tweet(self, tweet_id):
        if self.twitter is not None:
            try:
                destroyed = self.twitter.destroy_status(id=tweet_id)
                syslog.syslog('%s deleted %s' % (self.name, destroyed['text']))
                return destroyed
            except Exception as e:
                syslog.syslog('%s error deleting tweet -> %s' %(self.name, str(e)))

    # Deletes the most recent tweets
    def delete_tweets(self, num_tweets):
        if self.twitter is not None:
            try:
                timeline = self.twitter.get_user_timeline(screen_name = self.name, count = num_tweets)
                for tweet in timeline:
                    self.delete_tweet(tweet['id'])
                syslog.syslog('%s deleted %s tweet(s)' % (self.name, str(num_tweets)))
                return timeline
            except Exception as e:
                syslog.syslog('%s error deleting tweets -> %s' %(self.name, str(e)))


    # Replace all links in the text with the specified link
    def replace_link(self, text, link):
        replaced = ""
        for word in text.split():
            if word.startswith("http://") or word.startswith("https://"):
                replaced += link+" "
            else:
                replaced += word+" "
        replaced.strip()
        return replaced

    def retweet(self, tweet_id):
        if self.twitter is not None:
            try:
                tweet = self.twitter.retweet(id=tweet_id)
                syslog.syslog('%s is retweeting %s' % (self.name, tweet['text']))
                return tweet
            except Exception as e:
                syslog.syslog('%s error retweeting -> %s' %(self.name, str(e)))

    # This attack grabs a random tweet from a list of umich twitter accounts
    # If the tweet has a link it will be substituded for the attack link
    # The text of this modified tweet will then be tweeted by the bot
    # If the tweet does not have a link it is simply retweeted
    def repost_attack(self, link):
        if self.twitter is not None:
            try:
                #Get timeline of umich accounts
                umich_timeline = self.twitter.get_list_statuses(slug='UMich', owner_screen_name='JoseClark92', count=200)
                #Get user's timeline
                user_timeline = self.twitter.get_user_timeline(screen_name=self.name, count=100)
                #Get a random tweet that has not been posted by this bot
                repost = None
                while repost is None:
                    rand_tweet = random.choice(umich_timeline)
                    for tweet in user_timeline:
                        if rand_tweet['text'] in tweet: continue
                    repost = rand_tweet

                #If the tweet contains a link, replace the link and tweet it
                if "http" in repost['text']:
                    replaced = self.replace_link(repost['text'], link)
                    tweet = self.tweet(replaced)
                    #Add to the list of temporary tweets
                    self.temp_tweets[tweet['id']] = datetime.now()
                    return replaced
                #If the tweet does not contain a link, retweet it
                else:
                    retweet(tweet_id=repost['id'])
                    return repost['text']
            except Exception as e:
                syslog.syslog('%s repost attack error -> %s' %(self.name, str(e)))
    
    #Removes all temp tweets that are older than an hour
    def delete_old_tweets(self, time_to_live):
        if self.twitter is not None:
            try:
                now = datetime.now()
                for tweet in self.temp_tweets:
                    age = (self.temp_tweets[tweet] - now).seconds
                    if age > time_to_live:
                        self.delete_tweet(tweet)
            except Exception as e:
            syslog.syslog('%s error deleting old tweets -> %s' %(self.name, str(e)))

    def get_global_trends(self):
        trends = self.twitter.get_place_trends(id=1)
        ret = [trend['name']
               for trend in trends[0].get('trends')][:self.num_trends]
        return ','.join(ret)

    def post_campaign(self, url):
        trends = self.get_global_trends().split(',')
        # get minimum datetime and maximum datetime to spawn intervals in between them
        # current time
        mindt = datetime.now()
        maxdt = mindt + timedelta(seconds=self.campaign_window)
        # get num_trends intervals for num_trends tweets
        intervals = [self.randtime(mindt, maxdt)
                     for x in xrange(self.num_trends)]
        # zip the intervals and the trends
        tweet_zips = zip(intervals, trends)
        map(lambda interval_tuple: gevent.spawn_later(interval_tuple[
            0] - int(mindt.strftime('%s')), self.tweet, interval_tuple[1] + ' ' + url), tweet_zips)

    def randtime(self, mindt, maxdt):
        return randint(int(mindt.strftime('%s')), int(maxdt.strftime('%s')))


def main():
    reload(sys)
    sys.setdefaultencoding('utf-8')
    # get bot info
    with open('bots.csv', 'r') as bot_file:
        try:
            read_in = bot_file.readlines()
            # get lines and filter out comments or misconfigured lines
            lines = [l.rstrip() for l in read_in if not l.startswith(
                "#") and (l.startswith("bot=") or l.startswith("irc="))]
            if len(lines) <= 0:
                s = 'Could not load any bots from bot_file'
                syslog.syslog('ERROR: %s' % s)
                raise Exception(s)
            # read in irc info, will always read first one
            irc_lines = [l for l in lines if l.startswith("irc=")]
            if len(irc_lines) <= 0:
                s = 'Could not load IRC info from bot_file'
                syslog.syslog('ERROR: %s' % s)
                raise Exception(s)
            # remove irc_line from lines
            map(lambda x: lines.remove(x), irc_lines)
            irc_serv, irc_chan, irc_name = irc_lines[
                0].split("=")[1].split(",")
            syslog.syslog('Loaded bot %s, connecting to %s and channel %s' % (
                irc_name, irc_serv, irc_chan))
            # spawn the bots, give them 45 seconds to connect to twitter then return the object
            # we will wait and start the thread for irc as our main event loop
            jobs = [gevent.spawn(spawn_bots, line) for line in lines]
            gevent.joinall(jobs, timeout=45)
            # get all the twitter bots, will raise exception if oauth fails
            bot_list = [bot.value for bot in jobs]
            # join irc as a nodehead , this bot controls many twitter bots and
            # runs campaigns for all
            port = 6667
            if ":" in irc_serv:
                irc_serv, port = irc_serv.split(":")
            irc_bot = IrcNodeHead(
                irc_chan, irc_name, irc_serv, int(port), bot_list)
            irc_bot.start()
        except Exception as e:
            syslog.syslog(syslog.LOG_ERR, 'BIRDIE: ' + str(e))
            print "ERROR: " + str(e)

# spawn bots given the config options, and return the object to jobs

def spawn_bots(bot_line):
    name, con_k, con_s, acc_k, acc_s = bot_line.split("=")[1].split(",")
    return TwitterBot(name, con_k, con_s, acc_k, acc_s)

if __name__ == "__main__":
    main()
コード例 #8
0
class TwitButler(object):
    
    def __init__(self, keys=consts.keys,me='exumbra_insoIem',logging=True):
        auth = [
            keys['app']['api_key'],
            keys['app']['api_secret'],
            keys['user']['access_token'],
            keys['user']['access_token_secret'],
        ]
        self.api = Twython(*auth)
        # self.api.update_status(status="tst3")
        
        self.streamer = TwythonStreamer(*auth)
        self.streamer.on_success = self.on_stream_success
        self.streamer.on_error = self.on_error
        self.me = me
        self.app_name = "twitbutler"
        self.logging = logging
    
    def on_stream_success(self,data):
        if (data.get('in_reply_to_screen_name') == self.me):
            try:
                log("____")
                log(data['text'])
                self.respond_to(data)
            except Exception as e:
                log(e)
                pass
    
    def respond_to(self,data):
        try:
            response = parse_command(data)
        except Exception as e:
            log(traceback.format_exc())
            self.debug_log_tweet(data,format(e.args))
            return
        if isinstance(response,str):
            # respond with string only!
            self.api.update_status(
                status = (
                    '@' + data['user']['screen_name'] +
                    " " + response
                ),
                in_reply_to_status_id = data['id']
            )
        elif isinstance(response, MediaResponse):
            self.api.update_status_with_media(
                status = (
                    '@' + data['user']['screen_name'] +
                    " " + response.text
                ),
                media = response.media,
                in_reply_to_status_id = data['id']
            )
        elif isinstance(response, DeleteResponse):
            # FIXME : here lies dirty work.
            reason = ""
            if 'in_reply_to_status_id' in data:
                orig_id = response.data['in_reply_to_status_id']
                try:
                    orig_tw = self.api.show_status(id=orig_id)
                except Exception as e:
                    ftext = "Can't get the original tweet : " + str(e)
                else:
                    if self.is_qualified_deletion_request(orig_tw, data):
                        try:
                            self.api.destroy_status(id=orig_tw['id'])
                            return
                        except Exception as e:
                            ftext = "Counldn't destroy it : " + str(e)
                    else:
                        ftext = "Can't delete that."
            else:
                ftext = "Specify tweet."
            self.api.update_status(
                status = (
                    '@' + data['user']['screen_name'] + ' ' + ftext
                    + ' [{}]'.format(str(time.time())[-6:])
                ),
                in_reply_to_status_id = data['id']
            )
    
    def on_error(self,status_code,data):
        log(status_code)
    
    def debug_log_tweet(self,data,txt):
        if self.logging:
            self.api.update_status(
                status = (
                    '@' + data['user']['screen_name'] +
                    " Exception: {} [{}]".format(txt, str(time.time())[:6])
                ),
                in_reply_to_status_id = data['id']
            )
        else:
            return
    
    def is_qualified_deletion_request(self,tw_del, tw_req):
        if self.app_name not in tw_del['source']:
            # if the tweet being requested for deletion
            # is from twitbutler,
            # TODO : better checking
            return False
        if 'in_reply_to_screen_name' not in tw_del:
            # and is in response to something,
            return False
        if (tw_del['in_reply_to_screen_name'] !=
                tw_req['user']['screen_name']):
            # aand user requesting for delete is the original commander.
            return False
        
        return True
コード例 #9
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()
コード例 #10
0
ファイル: test_twython.py プロジェクト: chrisbol/twython
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')
コード例 #11
0
ファイル: chillpill.py プロジェクト: meetar/chillpill
    print "usernames found:"
    print re.findall(regex, tweet)

  m = re.sub(regex, '', tweet)

  if debug:
    print "trimmed tweet:" + m

  # find any lowercase characters
  m = re.search('[a-z]', m)
  # if none are found
  if m is None:
    # ALL CAPS - DELETE
    print tweet
    print "ALL CAPS - DELETING: " + tweet_id
    try:
      twitter.destroy_status(id=tweet_id)
    except Exception, exception:
      print "Error:"
      print exception

  else:
    if debug:
      print "you're good"
    # sys.exit()

  if debug:
    print 'Sleeping... \n'

  time.sleep(timeout)
  # sys.exit()
コード例 #12
0
ファイル: twdelq.py プロジェクト: saravan2/twython-scripts
def main():
    try:

        notDeleted = 0
        _count = -1

        # Command line processing
        if len(sys.argv) < 2:
            print(
                "** Abort : Attempt again with query as second parameter and optional count**"
            )
            usage()
            sys.exit(-1)
        if len(sys.argv) >= 3:
            _count = int(sys.argv[2])
            if _count <= 0:
                usage()
                sys.exit(-1)
        if len(sys.argv) >= 4:
            print("Ignoring unwanted arguments")

        twitter = Twython(twiden.twitter_app_key, twiden.twitter_app_secret,
                          twiden.twitter_oauth_token,
                          twiden.twitter_oauth_token_secret)

        while True:
            qCount = 50 if (_count > 0 and _count > 50) else _count
            search_results = twitter.search(q=sys.argv[1], count=qCount)
            if (len(search_results["statuses"]) == 0):
                print(
                    "**Running search query now produced 0 tweets to delete **\n"
                )
                break
            for tweet in search_results["statuses"]:
                tw_user_id = tweet['user']['id']
                tw_id = tweet['id']
                tw_user_mentions = tweet['entities']['user_mentions']
                print("Attempting to delete : {}".format(tweet['text']))
                try:
                    twitter.destroy_status(id=tw_id)
                except TwythonError as tei:
                    print(
                        "User id : {}\nTweet id : {}\nTweet : {}\nUser Mentions : {}\n**could not be deleted**\n"
                        .fortmat(tw_user_id, tw_id, tweet['text'],
                                 tw_user_mentions))
                    print(tei)
                    notDeleted += 1
                    pass

            time.sleep(60)

            if (_count < 0):
                continue

            _count = _count - qCount
            if (_count <= 0):
                break

        #End of while

        if notDeleted:
            print("** {} tweets could not be deleted **".fortmat(notDeleted))
    except TwythonError as te:
        print(te)
    except SystemExit as se:
        sys.exit(se)
    except:
        traceback.print_exc(file=sys.stdout)
    sys.exit(0)
コード例 #13
0
ファイル: test_endpoints.py プロジェクト: nouvak/twython
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()
コード例 #14
0
ファイル: clients.py プロジェクト: nontangent/task334-bot
    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'])
コード例 #15
0
ファイル: tweet-remove.py プロジェクト: Hasimir/twython-tools
# 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 >= 2:
    twid = sys.argv[1]
else:
    twid = input("ID number of tweet to delete: ")

try:
    tweet = twitter.destroy_status(id=twid)
except TwythonError as e:
    print(e)
コード例 #16
0
    def delete_tweet(self, consumer_key, consumer_secret, access_token,
                     access_token_secret, tweet_id):
        twitter = Twython(consumer_key, consumer_secret, access_token,
                          access_token_secret)

        return twitter.destroy_status(id=tweet_id)
コード例 #17
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()
コード例 #18
0
ファイル: twitter.py プロジェクト: Samael500/sev-boats
class Twitter(object):

    """ Class for twitter use """

    query_string = '#севастополь -украина OR северная OR катер OR SevastopolBoats OR sevboats :) since:%s lang:ru'
    weather_string = u'#погода в Севастополе на %s.'
    timelimit = 90
    max_follow = 100

    def __init__(self, auth=TWITTER_OAUTH_INFO):
        self.twitter = Twython(**auth)

    def post_tweet(self, message):
        """ Writes message into twitter stream """
        return self.twitter.update_status(status=message, trim_user=True)

    def delete_tweet(self, tweet_id):
        """ Remove tweet from timeline """
        return self.twitter.destroy_status(id=tweet_id, trim_user=True)

    def post_debug(self, message):
        """ Writes message into console to test """
        print message
        return dict(id=0, id_str='0', text=message)

    def search(self, query=None, count=10):
        """ Search tweet with sevboats ref """
        if query is None:
            since = (datetime.datetime.now() - datetime.timedelta(days=7)).date().strftime('%Y-%m-%d')
            query = self.query_string % since if 'since:%s' in self.query_string else self.query_string
        return self.twitter.search(q=query, count=count)

    def follow(self, user_id):
        """ Follow user by id """
        try:
            return self.twitter.create_friendship(user_id=user_id, follow=True)
        except TwythonError:
            return dict(status='error', id_str=None)

    def unfollow(self, user_id):
        """ Un Follow user by id """
        try:
            return self.twitter.destroy_friendship(user_id=user_id)
        except TwythonError:
            return dict(status='error', id_str=None)

    def follow_list(self, friends_ids):
        """ Follow user in search result """
        friends = []
        for user_id in friends_ids:
            friends.append(self.follow(user_id)['id_str'])
        return friends

    def unfollow_list(self, friends_ids):
        """ Un Follow user in ids list """
        friends = []
        for user_id in friends_ids:
            friends.append(self.unfollow(user_id)['id_str'])
        return friends

    def search_to_list(self, search_list=None):
        """ Follow user in search result """
        if search_list is None:
            search_list = self.search()
        users_ids = []
        for tweet in search_list['statuses']:
            users_ids.append(tweet['user']['id_str'])
        return users_ids

    def my_followers(self):
        """ Get list of my followers """
        followers_ids = []
        next_cursor = -1
        while next_cursor != '0':
            cursor = next_cursor
            fids = self.twitter.get_followers_ids(cursor=cursor, stringify_ids=True, count=1000)
            followers_ids += fids['ids']
            next_cursor = fids['next_cursor_str']
            time.sleep(self.timelimit)
        return followers_ids

    def follow_search(self):
        """ Follow for all user in search results """
        users_ids = self.search_to_list()
        self.follow_list(users_ids)
        return users_ids

    def follow_followers(self):
        """ Follow for all followers """
        followers_ids = self.my_followers()
        friends_ids = self.i_follow()
        users_ids = []
        for follower in followers_ids:
            if follower not in friends_ids:
                users_ids.append(follower)
        self.follow_list(users_ids[:self.max_follow])
        return users_ids

    def i_follow(self):
        """ Get list of user i follow what """
        friends_ids = []
        next_cursor = -1
        while next_cursor != '0':
            cursor = next_cursor
            fids = self.twitter.get_friends_ids(cursor=cursor, stringify_ids=True, count=1000)
            friends_ids += fids['ids']
            next_cursor = fids['next_cursor_str']
            time.sleep(self.timelimit)
        return friends_ids

    def post_image_weather(self):
        """ Create weather image and post to twitter """
        # get weather image
        print 'start'
        weth = Weather()
        weather_img, date_title = weth.draw_img()
        # create stream
        print 'streem'
        image_io = StringIO()
        # weather_img.save(image_io, format='JPEG', quality=100, subsampling=0, optimize=True, progressive=True)
        weather_img.save(image_io, format='PNG')
        image_io.seek(0)
        # post tweet
        print 'post'
        return self.twitter.update_status_with_media(media=image_io, status=self.weather_string % date_title)
コード例 #19
0
class TwitterDelete:
    """
    Deletes old tweets.
    """
    def __init__(self, keys_file: str = "keys.yaml") -> None:
        with open(keys_file, "r") as file:
            keys = yaml.safe_load(file)

        self.twitter = Twython(*keys.values())

        try:
            self.twitter.verify_credentials()
        except TwythonAuthError:
            print("Invalid (or missing) credentials.")
            sys.exit()

    def pull_ids(self,
                 file_name: str = "tweet.js",
                 deleted_csvs: str = "deleted.csv") -> list:
        """
        Reads a Twitter .csv file and returns a
        list of IDs from an users' history.

        Parameters:
        ----------
        file_name: str
            A file name for the Tweet archive
        """
        tweet_ids: list = []
        deleted_ids: list = []

        with open(file_name, "r") as file:
            tweets = file.readlines()[1:]
            tweets.insert(0, "[{")
            tweets = "".join(tweets)

            tweet_history = json.loads(tweets)

            for row in tweet_history:
                tweet_ids.append(row["tweet"].get("id"))

        try:
            with open(deleted_csvs, "r") as deleteds_file:
                deleted_tweets = csv.reader(deleteds_file)
                for row in deleted_tweets:
                    deleted_id = row[0]
                    deleted_ids.append(deleted_id)
        except FileNotFoundError:
            pass

        tweet_ids = list(set(tweet_ids) - set(deleted_ids))

        return tweet_ids

    def delete_tweets(self,
                      tweet_ids: list,
                      deleted_file_name: str = "deleted.csv") -> list:
        """
        Deletes tweets from a list of tweet ids.

        Parameters:
        ----------
        tweet ids: list
            List of tweet ids.
        """
        deleted: list = []
        persist: bool = True

        try:
            while persist == True:
                with open(deleted_file_name, "a") as deleted_file:
                    deleted_write = csv.writer(deleted_file)
                    try:
                        for tweet_id in tweet_ids:
                            try:
                                self.twitter.destroy_status(id=tweet_id)
                                deleted.append(tweet_id)
                                deleted_write.writerow([tweet_id])
                            except TwythonRateLimitError as e:
                                time.sleep(int(e.retry_after) - time.time())
                                continue
                            except TwythonError as e:
                                try:
                                    self.twitter.request(
                                        endpoint="statuses/unretweet",
                                        method="POST",
                                        params={"id": tweet_id},
                                    )

                                except TwythonError:
                                    print(str(e))
                                    continue
                                else:
                                    print(str(e))
                                    continue

                    except StopIteration:
                        persist = False
                        break

        except KeyboardInterrupt:
            return deleted

        return deleted
コード例 #20
0
ファイル: test_core.py プロジェクト: hungtrv/twython
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()
コード例 #21
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 >= 2:
    twid = sys.argv[1]
else:
    twid = input("ID number of tweet to delete: ")

try:
    tweet = twitter.destroy_status(id=twid)
except TwythonError as e:
    print(e)