Exemple #1
0
def fallback_humanize(date, fallback_format=None, use_fallback=False):
    """
    Format date with arrow and a fallback format
    """
    # Convert to local timezone
    date = arrow.get(date).to('local')
    # Set default fallback format
    if not fallback_format:
        fallback_format = '%Y/%m/%d %H:%M:%S'
    # Determine using fallback format or not by a variable
    if use_fallback:
        return date.datetime.strftime(fallback_format)
    try:
        # Use Arrow's humanize function
        lang, encode = locale.getdefaultlocale()
        clock = date.humanize(locale=lang)
    except:
        # Notice at the 1st time only
        if not dg['humanize_unsupported']:
            dg['humanize_unsupported'] = True
            printNicely(
                light_magenta(
                    'Humanized date display method does not support your $LC_ALL.'
                ))
        # Fallback when LC_ALL is not supported
        clock = date.datetime.strftime(fallback_format)
    return clock
Exemple #2
0
def notify_follow(e):
    """
    Notify a follow event
    """
    # Retrieve info
    target = e['target']
    if target['screen_name'] != c['original_name']:
        return
    source = e['source']
    created_at = e['created_at']
    # Format
    source_user = cycle_color(source['name']) + \
        color_func(c['NOTIFICATION']['source_nick'])(
        ' @' + source['screen_name'])
    notify = color_func(c['NOTIFICATION']['notify'])('followed you')
    date = parser.parse(created_at)
    clock = fallback_humanize(date)
    clock = color_func(c['NOTIFICATION']['clock'])(clock)
    meta = c['NOTIFY_FORMAT']
    meta = source_user.join(meta.split('#source_user'))
    meta = notify.join(meta.split('#notify'))
    meta = clock.join(meta.split('#clock'))
    meta = emojize(meta)
    # Output
    printNicely('')
    printNicely(meta)
Exemple #3
0
def notify_list_user_subscribed(e):
    """
    Notify a list_user_subscribed event
    """
    # Retrieve info
    target = e['target']
    if target['screen_name'] != c['original_name']:
        return
    source = e['source']
    target_object = [e['target_object']]  # list of Twitter list
    created_at = e['created_at']
    # Format
    source_user = cycle_color(source['name']) + \
        color_func(c['NOTIFICATION']['source_nick'])(
        ' @' + source['screen_name'])
    notify = color_func(c['NOTIFICATION']['notify'])(
        'subscribed to your list')
    date = parser.parse(created_at)
    date = arrow.get(date).to('local')
    lang, encode = locale.getdefaultlocale()
    clock = arrow.get(date).to('local').humanize(locale=lang)
    clock = color_func(c['NOTIFICATION']['clock'])(clock)
    meta = c['NOTIFY_FORMAT']
    meta = source_user.join(meta.split('#source_user'))
    meta = notify.join(meta.split('#notify'))
    meta = clock.join(meta.split('#clock'))
    # Output
    printNicely('')
    printNicely(meta)
    print_list(target_object, noti=True)
Exemple #4
0
def main():
    args = parse_arguments()

    if not all((args.token, args.token_secret, args.consumer_key, args.consumer_secret)):
        print(__doc__)
        return 2

    # When using twitter stream you must authorize.
    auth = OAuth(args.token, args.token_secret, args.consumer_key, args.consumer_secret)
    if args.user_stream:
        stream = TwitterStream(auth=auth, domain='userstream.twitter.com')
        tweet_iter = stream.user()
    elif args.site_stream:
        stream = TwitterStream(auth=auth, domain='sitestream.twitter.com')
        tweet_iter = stream.site()
    else:
        stream = TwitterStream(auth=auth, timeout=60.0)
        tweet_iter = stream.statuses.sample()

    # Iterate over the sample stream.
    for tweet in tweet_iter:
        # You must test that your tweet has text. It might be a delete
        # or data message.
        if tweet.get('text'):
            printNicely(tweet['text'])
Exemple #5
0
def notify_retweet(t):
    """
    Notify a retweet
    """
    source = t['user']
    created_at = t['created_at']
    # Format
    source_user = cycle_color(source['name']) + \
        color_func(c['NOTIFICATION']['source_nick'])(
        ' @' + source['screen_name'])
    notify = color_func(c['NOTIFICATION']['notify'])(
        'retweeted your tweet')
    date = parser.parse(created_at)
    date = arrow.get(date).to('local')
    lang, encode = locale.getdefaultlocale()
    clock = arrow.get(date).to('local').humanize(locale=lang)
    clock = color_func(c['NOTIFICATION']['clock'])(clock)
    meta = c['NOTIFY_FORMAT']
    meta = source_user.join(meta.split('#source_user'))
    meta = notify.join(meta.split('#notify'))
    meta = clock.join(meta.split('#clock'))
    # Output
    printNicely('')
    printNicely(meta)
    draw(t=t['retweeted_status'], noti=True)
Exemple #6
0
def notify_follow(e):
    """
    Notify a follow event
    """
    # Retrieve info
    target = e['target']
    if target['screen_name'] != c['original_name']:
        return
    source = e['source']
    created_at = e['created_at']
    # Format
    source_user = cycle_color(source['name']) + \
        color_func(c['NOTIFICATION']['source_nick'])(
        ' @' + source['screen_name'])
    notify = color_func(c['NOTIFICATION']['notify'])(
        'followed you')
    date = parser.parse(created_at)
    date = arrow.get(date).to('local')
    lang, encode = locale.getdefaultlocale()
    clock = arrow.get(date).to('local').humanize(locale=lang)
    clock = color_func(c['NOTIFICATION']['clock'])(clock)
    meta = c['NOTIFY_FORMAT']
    meta = source_user.join(meta.split('#source_user'))
    meta = notify.join(meta.split('#notify'))
    meta = clock.join(meta.split('#clock'))
    # Output
    printNicely('')
    printNicely(meta)
Exemple #7
0
def main():
    args = parse_arguments()

    if not all((args.token, args.token_secret, args.consumer_key,
                args.consumer_secret)):
        print(__doc__)
        return 2

    # When using twitter stream you must authorize.
    auth = OAuth(args.token, args.token_secret, args.consumer_key,
                 args.consumer_secret)
    if args.user_stream:
        stream = TwitterStream(auth=auth, domain='userstream.twitter.com')
        tweet_iter = stream.user()
    elif args.site_stream:
        stream = TwitterStream(auth=auth, domain='sitestream.twitter.com')
        tweet_iter = stream.site()
    else:
        stream = TwitterStream(auth=auth, timeout=60.0)
        tweet_iter = stream.statuses.sample()

    # Iterate over the sample stream.
    for tweet in tweet_iter:
        # You must test that your tweet has text. It might be a delete
        # or data message.
        if tweet.get('text'):
            printNicely(tweet['text'])
Exemple #8
0
    def connectToStream(self, auth):
        printNicely("-- Connecting to Stream --")
        stream = TwitterStream(auth = auth, secure = True, timeout = 20, heartbeat_timeout = 90)
        tweet_iter = stream.statuses.filter(track = "love")

       # while True:
        #    print(".")
         #   self.publish('com.myapp.heartbeat')
          #  yield sleep(1)

        for tweet in tweet_iter:
            # check whether this is a valid tweet
            if tweet is None:
                printNicely("-- None --")
                return
            elif tweet is Timeout:
                printNicely("-- Timeout --")
                sleep(5);
                return
            elif tweet is HeartbeatTimeout:
                printNicely("-- Heartbeat Timeout --")
                return
            elif tweet is Hangup:
                printNicely("-- Hangup --")
                return
            elif tweet.get('text'):
            #   obj = {'text': tweet["text"], 'user': tweet["user"]["screen_name"]}
                obj = {'text': tweet["text"]}
                yield obj
    def listen(self):
        self.stream = TwitterStream(auth=self.auth, **self.stream_args)

        self.query_args = dict()
        if self.filterstr:
            # https://dev.twitter.com/docs/streaming-apis/parameters#track
            self.query_args['track'] = self.filterstr

        if self.filterstr:
            self.tweet_iter = self.stream.statuses.filter(**self.query_args)
        else:
            self.tweet_iter = self.stream.statuses.sample()
        for tweet in self.tweet_iter:
            if tweet is None:
                 printNicely("-- None --")
            elif tweet is Timeout:
                printNicely("-- Timeout --")
            elif tweet is HeartbeatTimeout:
                printNicely("-- Heartbeat Timeout --")
            elif tweet is Hangup:
                printNicely("-- Hangup --")
            elif tweet.get('text'):
                if self.callback:
                    # We parse the text to sort tweet into right channel
                    for keywords in self.keywords:
                        for word in keywords:
                            r = re.search(word,tweet.get("text"),re.IGNORECASE)
                            if not r:
                                continue
                            else:
                                tweet["channel"] = "," .join(keywords)
                                self.callback(json.dumps(tweet))
            else:
                printNicely("-- Some data: " + str(tweet))
Exemple #10
0
def notify_list_user_unsubscribed(e):
    """
    Notify a list_user_unsubscribed event
    """
    # Retrieve info
    target = e['target']
    if target['screen_name'] != c['original_name']:
        return
    source = e['source']
    target_object = [e['target_object']]  # list of Twitter list
    created_at = e['created_at']
    # Format
    source_user = cycle_color(source['name']) + \
        color_func(c['NOTIFICATION']['source_nick'])(
        ' @' + source['screen_name'])
    notify = color_func(
        c['NOTIFICATION']['notify'])('unsubscribed from your list')
    date = parser.parse(created_at)
    clock = fallback_humanize(date)
    clock = color_func(c['NOTIFICATION']['clock'])(clock)
    meta = c['NOTIFY_FORMAT']
    meta = source_user.join(meta.split('#source_user'))
    meta = notify.join(meta.split('#notify'))
    meta = clock.join(meta.split('#clock'))
    meta = emojize(meta)
    # Output
    printNicely('')
    printNicely(meta)
    print_list(target_object, noti=True)
Exemple #11
0
def muting():
    """
    List muting user
    """
    t = Twitter(auth=authen())
    # Init cursor
    next_cursor = -1
    rel = {}
    # Cursor loop
    while next_cursor != 0:
        list = t.mutes.users.list(
            screen_name=g['original_name'],
            cursor=next_cursor,
            skip_status=True,
            include_entities=False,
        )
        for u in list['users']:
            rel[u['name']] = '@' + u['screen_name']
        next_cursor = list['next_cursor']
    # Print out result
    printNicely('All: ' + str(len(rel)) + ' people.')
    for name in rel:
        user = '******' + cycle_color(name)
        user += color_func(c['TWEET']['nick'])(' ' + rel[name] + ' ')
        printNicely(user)
Exemple #12
0
def twitterlist():
    """
    Twitter's list
    """
    t = Twitter(auth=authen())
    # List all lists or base on action
    try:
        g['list_action'] = g['stuff'].split()[0]
    except:
        show_lists(t)
        return
    # Sub-function
    action_ary = {
        'home': list_home,
        'all_mem': list_members,
        'all_sub': list_subscribers,
        'add': list_add,
        'rm': list_remove,
        'sub': list_subscribe,
        'unsub': list_unsubscribe,
        'own': list_own,
        'new': list_new,
        'update': list_update,
        'del': list_delete,
    }
    try:
        return action_ary[g['list_action']](t)
    except:
        printNicely(red('Please try again.'))
Exemple #13
0
def fallback_humanize(date, fallback_format=None, use_fallback=False):
    """
    Format date with arrow and a fallback format
    """
    # Convert to local timezone
    date = arrow.get(date).to('local')
    # Set default fallback format
    if not fallback_format:
        fallback_format = '%Y/%m/%d %H:%M:%S'
    # Determine using fallback format or not by a variable
    if use_fallback:
        return date.datetime.strftime(fallback_format)
    try:
        # Use Arrow's humanize function
        lang, encode = locale.getdefaultlocale()
        clock = date.humanize(locale=lang)
    except:
        # Notice at the 1st time only
        if not dg['humanize_unsupported']:
            dg['humanize_unsupported'] = True
            printNicely(
                light_magenta('Humanized date display method does not support your $LC_ALL.'))
        # Fallback when LC_ALL is not supported
        clock = date.datetime.strftime(fallback_format)
    return clock
Exemple #14
0
def help_list():
    """
    Lists
    """
    s = ' ' * 2
    # Twitter list
    usage = '\n'
    usage += s + grey(u'\u266A' + ' Twitter list\n')
    usage += s * 2 + light_green('list') + \
        ' will show all lists you are belong to.\n'
    usage += s * 2 + light_green('list home') + \
        ' will show timeline of list. You will be asked for list\'s name.\n'
    usage += s * 2 + light_green('list all_mem') + \
        ' will show list\'s all members.\n'
    usage += s * 2 + light_green('list all_sub') + \
        ' will show list\'s all subscribers.\n'
    usage += s * 2 + light_green('list add') + \
        ' will add specific person to a list owned by you.' + \
        ' You will be asked for list\'s name and person\'s name.\n'
    usage += s * 2 + light_green('list rm') + \
        ' will remove specific person from a list owned by you.' + \
        ' You will be asked for list\'s name and person\'s name.\n'
    usage += s * 2 + light_green('list sub') + \
        ' will subscribe you to a specific list.\n'
    usage += s * 2 + light_green('list unsub') + \
        ' will unsubscribe you from a specific list.\n'
    usage += s * 2 + light_green('list own') + \
        ' will show all list owned by you.\n'
    usage += s * 2 + light_green('list new') + \
        ' will create a new list.\n'
    usage += s * 2 + light_green('list update') + \
        ' will update a list owned by you.\n'
    usage += s * 2 + light_green('list del') + \
        ' will delete a list owned by you.\n'
    printNicely(usage)
Exemple #15
0
def list():
    """
    Twitter's list
    """
    t = Twitter(auth=authen())
    # List all lists or base on action
    try:
        g['list_action'] = g['stuff'].split()[0]
    except:
        show_lists(t)
        return
    # Sub-function
    action_ary = {
        'home': list_home,
        'all_mem': list_members,
        'all_sub': list_subscribers,
        'add': list_add,
        'rm': list_remove,
        'sub': list_subscribe,
        'unsub': list_unsubscribe,
        'own': list_own,
        'new': list_new,
        'update': list_update,
        'del': list_delete,
    }
    try:
        return action_ary[g['list_action']](t)
    except:
        printNicely(red('Please try again.'))
Exemple #16
0
def help_friends_and_followers():
    """
    Friends and Followers
    """
    s = ' ' * 2
    # Follower and following
    usage = '\n'
    usage += s + grey(u'\u266A' + ' Friends and followers \n')
    usage += s * 2 + \
        light_green('ls fl') + \
        ' will list all followers (people who are following you).\n'
    usage += s * 2 + \
        light_green('ls fr') + \
        ' will list all friends (people who you are following).\n'
    usage += s * 2 + light_green('fl @dtvd88') + ' will follow ' + \
        magenta('@dtvd88') + '.\n'
    usage += s * 2 + light_green('ufl @dtvd88') + ' will unfollow ' + \
        magenta('@dtvd88') + '.\n'
    usage += s * 2 + light_green('mute @dtvd88') + ' will mute ' + \
        magenta('@dtvd88') + '.\n'
    usage += s * 2 + light_green('unmute @dtvd88') + ' will unmute ' + \
        magenta('@dtvd88') + '.\n'
    usage += s * 2 + light_green('muting') + ' will list muting users.\n'
    usage += s * 2 + light_green('block @dtvd88') + ' will block ' + \
        magenta('@dtvd88') + '.\n'
    usage += s * 2 + light_green('unblock @dtvd88') + ' will unblock ' + \
        magenta('@dtvd88') + '.\n'
    usage += s * 2 + light_green('report @dtvd88') + ' will report ' + \
        magenta('@dtvd88') + ' as a spam account.\n'
    printNicely(usage)
Exemple #17
0
def sent():
    """
    Sent direct messages
    """
    t = Twitter(auth=authen())
    num = c['MESSAGES_DISPLAY']
    rel = []
    if g['stuff'].isdigit():
        num = int(g['stuff'])
    cur_page = 1
    # Max message per page is 20 so we have to loop
    while num > 20:
        rel = rel + t.direct_messages.sent(
            count=20,
            page=cur_page,
            include_entities=False,
            skip_status=False
        )
        num -= 20
        cur_page += 1
    rel = rel + t.direct_messages.sent(
        count=num,
        page=cur_page,
        include_entities=False,
        skip_status=False
    )
    # Display
    printNicely('Sent: newest ' + str(len(rel)) + ' messages.')
    for m in reversed(rel):
        print_message(m)
    printNicely('')
Exemple #18
0
def list_update(t):
    """
    Update a list
    """
    slug = raw_input(light_magenta('Your list that you want to update: '))
    name = raw_input(light_magenta('Update name (leave blank to unchange): '))
    mode = raw_input(light_magenta('Update mode (public/private): '))
    description = raw_input(light_magenta('Update description: '))
    try:
        if name:
            t.lists.update(
                slug='-'.join(slug.split()),
                owner_screen_name=g['original_name'],
                name=name,
                mode=mode,
                description=description)
        else:
            t.lists.update(
                slug=slug,
                owner_screen_name=g['original_name'],
                mode=mode,
                description=description)
        printNicely(green(slug + ' list is updated.'))
    except:
        printNicely(red('Oops something is wrong with Twitter :('))
def quote():
    """
    Quote a tweet
    """
    # Get tweet
    t = Twitter(auth=authen())
    try:
        id = int(g['stuff'].split()[0])
    except:
        printNicely(red('Sorry I can\'t understand.'))
        return
    tid = c['tweet_dict'][id]
    tweet = t.statuses.show(id=tid)
    # Get formater
    formater = format_quote(tweet)
    if not formater:
        return
    # Get comment
    prefix = light_magenta('Compose your ') + light_green('#comment: ')
    comment = raw_input(prefix)
    if comment:
        quote = comment.join(formater.split('#comment'))
        t.statuses.update(status=quote)
    else:
        printNicely(light_magenta('No text added.'))
Exemple #20
0
def notify_list_user_unsubscribed(e):
    """
    Notify a list_user_unsubscribed event
    """
    # Retrieve info
    target = e['target']
    if target['screen_name'] != c['original_name']:
        return
    source = e['source']
    target_object = [e['target_object']]  # list of Twitter list
    created_at = e['created_at']
    # Format
    source_user = cycle_color(source['name']) + \
        color_func(c['NOTIFICATION']['source_nick'])(
        ' @' + source['screen_name'])
    notify = color_func(c['NOTIFICATION']['notify'])(
        'unsubscribed from your list')
    date = parser.parse(created_at)
    clock = fallback_humanize(date)
    clock = color_func(c['NOTIFICATION']['clock'])(clock)
    meta = c['NOTIFY_FORMAT']
    meta = source_user.join(meta.split('#source_user'))
    meta = notify.join(meta.split('#notify'))
    meta = clock.join(meta.split('#clock'))
    meta = emojize(meta)
    # Output
    printNicely('')
    printNicely(meta)
    print_list(target_object, noti=True)
Exemple #21
0
def notify_follow(e):
    """
    Notify a follow event
    """
    # Retrieve info
    target = e['target']
    if target['screen_name'] != c['original_name']:
        return
    source = e['source']
    created_at = e['created_at']
    # Format
    source_user = cycle_color(source['name']) + \
        color_func(c['NOTIFICATION']['source_nick'])(
        ' @' + source['screen_name'])
    notify = color_func(c['NOTIFICATION']['notify'])(
        'followed you')
    date = parser.parse(created_at)
    clock = fallback_humanize(date)
    clock = color_func(c['NOTIFICATION']['clock'])(clock)
    meta = c['NOTIFY_FORMAT']
    meta = source_user.join(meta.split('#source_user'))
    meta = notify.join(meta.split('#notify'))
    meta = clock.join(meta.split('#clock'))
    meta = emojize(meta)
    # Output
    printNicely('')
    printNicely(meta)
Exemple #22
0
def help_list():
    """
    Lists
    """
    s = ' ' * 2
    # Twitter list
    usage = '\n'
    usage += s + grey(u'\u266A' + ' Twitter list\n')
    usage += s * 2 + light_green('list') + \
        ' will show all lists you are belong to.\n'
    usage += s * 2 + light_green('list home') + \
        ' will show timeline of list. You will be asked for list\'s name.\n'
    usage += s * 2 + light_green('list all_mem') + \
        ' will show list\'s all members.\n'
    usage += s * 2 + light_green('list all_sub') + \
        ' will show list\'s all subscribers.\n'
    usage += s * 2 + light_green('list add') + \
        ' will add specific person to a list owned by you.' + \
        ' You will be asked for list\'s name and person\'s name.\n'
    usage += s * 2 + light_green('list rm') + \
        ' will remove specific person from a list owned by you.' + \
        ' You will be asked for list\'s name and person\'s name.\n'
    usage += s * 2 + light_green('list sub') + \
        ' will subscribe you to a specific list.\n'
    usage += s * 2 + light_green('list unsub') + \
        ' will unsubscribe you from a specific list.\n'
    usage += s * 2 + light_green('list own') + \
        ' will show all list owned by you.\n'
    usage += s * 2 + light_green('list new') + \
        ' will create a new list.\n'
    usage += s * 2 + light_green('list update') + \
        ' will update a list owned by you.\n'
    usage += s * 2 + light_green('list del') + \
        ' will delete a list owned by you.\n'
    printNicely(usage)
Exemple #23
0
def help_friends_and_followers():
    """
    Friends and Followers
    """
    s = ' ' * 2
    # Follower and following
    usage = '\n'
    usage += s + grey(u'\u266A' + ' Friends and followers \n')
    usage += s * 2 + \
        light_green('ls fl') + \
        ' will list all followers (people who are following you).\n'
    usage += s * 2 + \
        light_green('ls fr') + \
        ' will list all friends (people who you are following).\n'
    usage += s * 2 + light_green('fl @dtvd88') + ' will follow ' + \
        magenta('@dtvd88') + '.\n'
    usage += s * 2 + light_green('ufl @dtvd88') + ' will unfollow ' + \
        magenta('@dtvd88') + '.\n'
    usage += s * 2 + light_green('mute @dtvd88') + ' will mute ' + \
        magenta('@dtvd88') + '.\n'
    usage += s * 2 + light_green('unmute @dtvd88') + ' will unmute ' + \
        magenta('@dtvd88') + '.\n'
    usage += s * 2 + light_green('muting') + ' will list muting users.\n'
    usage += s * 2 + light_green('block @dtvd88') + ' will block ' + \
        magenta('@dtvd88') + '.\n'
    usage += s * 2 + light_green('unblock @dtvd88') + ' will unblock ' + \
        magenta('@dtvd88') + '.\n'
    usage += s * 2 + light_green('report @dtvd88') + ' will report ' + \
        magenta('@dtvd88') + ' as a spam account.\n'
    printNicely(usage)
Exemple #24
0
def main():
    args = parse_arguments()

    # When using twitter stream you must authorize.
    auth = OAuth(args.token, args.token_secret, args.consumer_key,
                 args.consumer_secret)

    # These arguments are optional:
    stream_args = dict(timeout=args.timeout,
                       block=not args.no_block,
                       heartbeat_timeout=args.heartbeat_timeout)

    query_args = dict()
    if args.track_keywords:
        query_args['track'] = args.track_keywords

    if args.user_stream:
        stream = TwitterStream(auth=auth,
                               domain='userstream.twitter.com',
                               **stream_args)
        tweet_iter = stream.user(**query_args)
    elif args.site_stream:
        stream = TwitterStream(auth=auth,
                               domain='sitestream.twitter.com',
                               **stream_args)
        tweet_iter = stream.site(**query_args)
    else:
        stream = TwitterStream(auth=auth, **stream_args)
        if args.track_keywords:
            tweet_iter = stream.statuses.filter(**query_args)
        else:
            tweet_iter = stream.statuses.sample()

    # Connect to RethinkDB
    try:
        db.connect()
    except RqlDriverError:
        log.error('Couldn\'t connect to database.')

    # Iterate over the sample stream.
    for tweet in tweet_iter:
        # You must test that your tweet has text. It might be a delete or data message.
        if tweet is None:
            log.error('None')
        elif tweet is Timeout:
            log.error('Timeout')
        elif tweet is HeartbeatTimeout:
            log.error('Heartbeat Timeout')
        elif tweet is Hangup:
            log.error('Hangup')
        elif tweet.get('text'):
            tweet[
                'stream_id'] = '1234567890'  # TODO: add that stream_id gets passed to open_stream.py
            db.insert(DATABASE, TWEETS_TABLE, tweet)
            printNicely(tweet['text'])
        else:
            log.error('Some data ' + str(tweet))
Exemple #25
0
def show_lists(t):
    """
    List list
    """
    rel = t.lists.list(screen_name=g['original_name'])
    if rel:
        print_list(rel)
    else:
        printNicely(light_magenta('You belong to no lists :)'))
Exemple #26
0
def show_lists(t):
    """
    List list
    """
    rel = t.lists.list(screen_name=g['original_name'])
    if rel:
        print_list(rel)
    else:
        printNicely(light_magenta('You belong to no lists :)'))
Exemple #27
0
def print_trends(trends):
    """
    Display topics
    """
    for topic in trends[:c['TREND_MAX']]:
        name = topic['name']
        url = topic['url']
        line = cycle_color(name) + ': ' + color_func(c['TREND']['url'])(url)
        printNicely(line)
    printNicely('')
def quit():
    """
    Exit all
    """
    try:
        save_history()
        printNicely(green('See you next time :)'))
    except:
        pass
    sys.exit()
Exemple #29
0
def print_trends(trends):
    """
    Display topics
    """
    for topic in trends[:c['TREND_MAX']]:
        name = topic['name']
        url = topic['url']
        line = cycle_color(name) + ': ' + color_func(c['TREND']['url'])(url)
        printNicely(line)
    printNicely('')
Exemple #30
0
def detail_twitter_error(twitterException):
    """
    Display Twitter Errors nicely
    """
    data = twitterException.response_data
    try:
        for m in data.get('errors', dict()):
            printNicely(yellow(m.get('message')))
    except:
        printNicely(yellow(data))
Exemple #31
0
def detail_twitter_error(twitterException):
    """
    Display Twitter Errors nicely
    """
    data = twitterException.response_data
    try:
        for m in data.get('errors', dict()):
            printNicely(yellow(m.get('message')))
    except:
        printNicely(yellow(data))
Exemple #32
0
def quit():
    """
    Exit all
    """
    try:
        save_history()
        printNicely(green('See you next time :)'))
    except:
        pass
    sys.exit()
Exemple #33
0
def follow():
    """
    Follow a user
    """
    t = Twitter(auth=authen())
    screen_name = g['stuff'].split()[0]
    if screen_name.startswith('@'):
        t.friendships.create(screen_name=screen_name[1:], follow=True)
        printNicely(green('You are following ' + screen_name + ' now!'))
    else:
        printNicely(red('A name should begin with a \'@\''))
Exemple #34
0
def mentions():
    """
    Mentions timeline
    """
    t = Twitter(auth=authen())
    num = c['HOME_TWEET_NUM']
    if g['stuff'].isdigit():
        num = int(g['stuff'])
    for tweet in reversed(t.statuses.mentions_timeline(count=num)):
        draw(t=tweet)
    printNicely('')
Exemple #35
0
def do_stuff(auth, query_args, stream_args, toggle):

    if toggle == "toggle":
        # We'll do a short tweet than a long one then a short...
        do_short = True
    else:
        # Only one size
        do_short = toggle == "short"

    word_count = 0
    tweet_count = 0

    stream = TwitterStream(auth=auth, **stream_args)
    tweet_iter = stream.statuses.filter(**query_args)

    # Iterate over the sample stream
    for tweet in tweet_iter:
        # You must test that your tweet has text. It might be a delete
        # or data message.
        if tweet is None:
            pass
            #             printNicely("-- None --")
            #         elif tweet is Timeout:
            #             printNicely("-- Timeout --")
            #         elif tweet is HeartbeatTimeout:
            #             printNicely("-- Heartbeat Timeout --")
            #         elif tweet is Hangup:
            #             printNicely("-- Hangup --")
        else:
            if "extended_tweet" in tweet:
                text = tweet["extended_tweet"]["full_text"]
            else:
                text = tweet.get("text")

            # pprint(tweet)
            processed = process_tweet(text, query_args['track'], do_short)
            if processed:
                tweet_count += 1
                word_count += len(processed.split())

                processed = do_html_things(processed)

                printNicely(
                    '<div id={0} class={1}><a href=#{0}>{2}</a></div>'.format(
                        tweet_count, "s" if do_short else "l", processed))
                # print(do_short)
                if toggle == "toggle":
                    do_short = not do_short  # toggle
                # print(do_short)

        if word_count > 56000:  # 280 * 200
            break

    printNicely("")
def home():
    """
    Home
    """
    t = Twitter(auth=authen())
    num = c['HOME_TWEET_NUM']
    if g['stuff'].isdigit():
        num = int(g['stuff'])
    for tweet in reversed(t.statuses.home_timeline(count=num)):
        draw(t=tweet, iot=g['iot'])
    printNicely('')
Exemple #37
0
def report():
    """
    Report a user as a spam account
    """
    t = Twitter(auth=authen())
    screen_name = g['stuff'].split()[0]
    if screen_name.startswith('@'):
        t.users.report_spam(screen_name=screen_name[1:])
        printNicely(green('You reported ' + screen_name + '.'))
    else:
        printNicely(red('Sorry I can\'t understand.'))
Exemple #38
0
def follow():
    """
    Follow a user
    """
    t = Twitter(auth=authen())
    screen_name = g['stuff'].split()[0]
    if screen_name.startswith('@'):
        t.friendships.create(screen_name=screen_name[1:], follow=True)
        printNicely(green('You are following ' + screen_name + ' now!'))
    else:
        printNicely(red('A name should begin with a \'@\''))
Exemple #39
0
def list_delete(t):
    """
    Delete a list
    """
    slug = raw_input(light_magenta('Your list that you want to update: '))
    try:
        t.lists.destroy(slug='-'.join(slug.split()),
                        owner_screen_name=g['original_name'])
        printNicely(green(slug + ' list is deleted.'))
    except:
        printNicely(red('Oops something is wrong with Twitter :('))
Exemple #40
0
def reset():
    """
    Reset prefix of line
    """
    if g['reset']:
        printNicely(magenta('Need tips ? Type "h" and hit Enter key!'))
    g['reset'] = False
    try:
        printNicely(str(eval(g['cmd'])))
    except Exception:
        pass
Exemple #41
0
def mentions():
    """
    Mentions timeline
    """
    t = Twitter(auth=authen())
    num = c['HOME_TWEET_NUM']
    if g['stuff'].isdigit():
        num = int(g['stuff'])
    for tweet in reversed(t.statuses.mentions_timeline(count=num)):
        draw(t=tweet)
    printNicely('')
def retweet():
    """
    ReTweet
    """
    t = Twitter(auth=authen())
    try:
        id = int(g['stuff'].split()[0])
    except:
        printNicely(red('Sorry I can\'t understand.'))
        return
    tid = c['tweet_dict'][id]
    t.statuses.retweet(id=tid, include_entities=False, trim_user=True)
Exemple #43
0
def list_new(t):
    """
    Create a new list
    """
    name = raw_input(light_magenta('New list\'s name: '))
    mode = raw_input(light_magenta('New list\'s mode (public/private): '))
    description = raw_input(light_magenta('New list\'s description: '))
    try:
        t.lists.create(name=name, mode=mode, description=description)
        printNicely(green(name + ' list is created.'))
    except:
        printNicely(red('Oops something is wrong with Twitter :('))
Exemple #44
0
def report():
    """
    Report a user as a spam account
    """
    t = Twitter(auth=authen())
    screen_name = g['stuff'].split()[0]
    if screen_name.startswith('@'):
        t.users.report_spam(
            screen_name=screen_name[1:])
        printNicely(green('You reported ' + screen_name + '.'))
    else:
        printNicely(red('Sorry I can\'t understand.'))
Exemple #45
0
def list_unsubscribe(t):
    """
    Unsubscribe a list
    """
    owner, slug = get_slug()
    # Subscribe
    try:
        t.lists.subscribers.destroy(slug=slug, owner_screen_name=owner)
        printNicely(green('Done.'))
    except:
        printNicely(
            light_magenta('I\'m sorry you can not unsubscribe to this list.'))
Exemple #46
0
def list_home(t):
    """
    List home
    """
    owner, slug = get_slug()
    res = t.lists.statuses(slug=slug,
                           owner_screen_name=owner,
                           count=c['LIST_MAX'],
                           include_entities=False)
    for tweet in res:
        draw(t=tweet)
    printNicely('')
Exemple #47
0
def trash():
    """
    Remove message
    """
    t = Twitter(auth=authen())
    try:
        id = int(g['stuff'].split()[0])
    except:
        printNicely(red('Sorry I can\'t understand.'))
    mid = c['message_dict'][id]
    t.direct_messages.destroy(id=mid)
    printNicely(green('Message deleted.'))
Exemple #48
0
def unfollow():
    """
    Unfollow a user
    """
    t = Twitter(auth=authen())
    screen_name = g['stuff'].split()[0]
    if screen_name.startswith('@'):
        t.friendships.destroy(screen_name=screen_name[1:],
                              include_entities=False)
        printNicely(green('Unfollow ' + screen_name + ' success!'))
    else:
        printNicely(red('A name should begin with a \'@\''))
Exemple #49
0
def trash():
    """
    Remove message
    """
    t = Twitter(auth=authen())
    try:
        rid = int(g['stuff'].split()[0])
    except:
        printNicely(red('Sorry I can\'t understand.'))
    mid = db.rainbow_to_message_query(rid)[0].message_id
    t.direct_messages.destroy(id=mid)
    printNicely(green('Message deleted.'))
def trash():
    """
    Remove message
    """
    t = Twitter(auth=authen())
    try:
        id = int(g['stuff'].split()[0])
    except:
        printNicely(red('Sorry I can\'t understand.'))
    mid = c['message_dict'][id]
    t.direct_messages.destroy(id=mid)
    printNicely(green('Message deleted.'))
Exemple #51
0
def list_delete(t):
    """
    Delete a list
    """
    slug = raw_input(light_magenta('Your list that you want to update: '))
    try:
        t.lists.destroy(
            slug='-'.join(slug.split()),
            owner_screen_name=g['original_name'])
        printNicely(green(slug + ' list is deleted.'))
    except:
        printNicely(red('Oops something is wrong with Twitter :('))
Exemple #52
0
def retweet():
    """
    ReTweet
    """
    t = Twitter(auth=authen())
    try:
        id = int(g['stuff'].split()[0])
    except:
        printNicely(red('Sorry I can\'t understand.'))
        return
    tid = db.rainbow_to_tweet_query(id)[0].tweet_id
    t.statuses.retweet(id=tid, include_entities=False, trim_user=True)
Exemple #53
0
def retweet():
    """
    ReTweet
    """
    t = Twitter(auth=authen())
    try:
        id = int(g['stuff'].split()[0])
    except:
        printNicely(red('Sorry I can\'t understand.'))
        return
    tid = c['tweet_dict'][id]
    t.statuses.retweet(id=tid, include_entities=False, trim_user=True)
Exemple #54
0
def block():
    """
    Block a user
    """
    t = Twitter(auth=authen())
    screen_name = g['stuff'].split()[0]
    if screen_name.startswith('@'):
        t.blocks.create(screen_name=screen_name[1:],
                        include_entities=False,
                        skip_status=True)
        printNicely(green('You blocked ' + screen_name + '.'))
    else:
        printNicely(red('A name should begin with a \'@\''))
Exemple #55
0
def muting():
    """
    List muting user
    """
    # Get dict of muting users
    md = build_mute_dict(dict_data=True)
    printNicely('All: ' + str(len(md)) + ' people.')
    for name in md:
        user = '******' + cycle_color(md[name])
        user += color_func(c['TWEET']['nick'])(' ' + name + ' ')
        printNicely(user)
    # Update from Twitter
    c['IGNORE_LIST'] = [n for n in md]
Exemple #56
0
def delete():
    """
    Delete
    """
    t = Twitter(auth=authen())
    try:
        id = int(g['stuff'].split()[0])
    except:
        printNicely(red('Sorry I can\'t understand.'))
        return
    tid = c['tweet_dict'][id]
    t.statuses.destroy(id=tid)
    printNicely(green('Okay it\'s gone.'))
Exemple #57
0
def unblock():
    """
    Unblock a user
    """
    t = Twitter(auth=authen())
    screen_name = g['stuff'].split()[0]
    if screen_name.startswith('@'):
        t.blocks.destroy(screen_name=screen_name[1:],
                         include_entities=False,
                         skip_status=True)
        printNicely(green('Unblock ' + screen_name + ' success!'))
    else:
        printNicely(red('A name should begin with a \'@\''))
Exemple #58
0
def detail_twitter_error(twitterException):
    """
    Display Twitter Errors nicely
    """
    try:
        # twitterException.response_data can be byte string on Python 3
        # or nornal dict on Python 2
        loadedJson = json.loads(twitterException.response_data.decode('utf8'))
        for m in loadedJson.get('errors', dict()):
            info = "Error " + str(m.get('code')) + ": " + m.get('message')
            printNicely(yellow(info))
    except:
        info = "Error: " + twitterException.response_data.decode('utf8')
        printNicely(yellow(info))
Exemple #59
0
def whois():
    """
    Show profile of a specific user
    """
    t = Twitter(auth=authen())
    screen_name = g['stuff'].split()[0]
    if screen_name.startswith('@'):
        try:
            user = t.users.show(screen_name=screen_name[1:],
                                include_entities=False)
            show_profile(user)
        except:
            printNicely(red('Omg no user.'))
    else:
        printNicely(red('A name should begin with a \'@\''))
Exemple #60
0
def list_own(t):
    """
    List own
    """
    rel = []
    next_cursor = -1
    while next_cursor != 0:
        res = t.lists.ownerships(screen_name=g['original_name'],
                                 cursor=next_cursor)
        rel += res['lists']
        next_cursor = res['next_cursor']
    if rel:
        print_list(rel)
    else:
        printNicely(light_magenta('You own no lists :)'))