def twitter_authentication(): CONSUMER_KEYS = os.path.expanduser('.twitter-consumer-keys') CONSUMER_KEY, CONSUMER_SECRET = oauth.read_token_file(CONSUMER_KEYS) MY_TWITTER_CREDS = os.path.expanduser('.twitter-bin-numbers-credentials') if not os.path.exists(MY_TWITTER_CREDS): oauth_dance("binary-numbers", CONSUMER_KEY, CONSUMER_SECRET, MY_TWITTER_CREDS) oauth_token, oauth_secret = oauth.read_token_file(MY_TWITTER_CREDS) twitter = Twitter(auth=oauth.OAuth(oauth_token, oauth_secret, CONSUMER_KEY, CONSUMER_SECRET)) return twitter
def __init__(self, configFilename): self.configFilename = configFilename self.config = load_config(self.configFilename) global ACTIVE_PREFIXES ACTIVE_PREFIXES = PREFIXES[self.config.get('irc', 'prefixes')] oauth_file = self.config.get('twitter', 'oauth_token_file') if not os.path.exists(oauth_file): oauth_dance("IRC Bot", CONSUMER_KEY, CONSUMER_SECRET, oauth_file) oauth_token, oauth_secret = read_token_file(oauth_file) self.twitter = Twitter( auth=OAuth( oauth_token, oauth_secret, CONSUMER_KEY, CONSUMER_SECRET), api_version='1', domain='api.twitter.com') self.irc = irclib.IRC() self.irc.add_global_handler('privmsg', self.handle_privmsg) self.irc.add_global_handler('ctcp', self.handle_ctcp) self.ircServer = self.irc.server() self.sched = Scheduler( (SchedTask(self.process_events, 1), SchedTask(self.check_statuses, 120))) self.lastUpdate = (datetime.utcnow() - timedelta(minutes=10)).utctimetuple()
def main(args=sys.argv[1:]): arg_options = {} try: parse_args(args, arg_options) except GetoptError as e: print("Can't parse argument") print(file=sys.stderr) raise SystemExit(1) #config_path = OPTIONS.get('config_filename') config_path = os.path.expanduser(arg_options.get('config_filename') or OPTIONS.get('config_filename')) # check why config path is None print(config_path) config_options = loadConfig(config_path) #print(config_options) options = dict(OPTIONS) for d in config_options, arg_options: for k, v in list(d.items()): if v: options[k] = v #print(options) if options['refresh'] and options['action'] not in ('friends', 'public', 'replies'): print("You can only refresh the friends, public, or replies action.", file=sys.stderr) print("Use 'twitter -h' for help", file=sys.stderr) return 1 oauth_filename = os.path.expanduser(options['oauth_filename']) if (options['action'] == 'authorize' or not os.path.exists(oauth_filename)): oauth_dance("the Command-Line-Tool", CONSUMER_KEY, CONSUMER_SECRET, options['oauth_filename']) global ansiFormatter ansiFormatter = ansi.AnsiCmd(options['force-ansi']) oauth_token, oauth_token_secret = read_token_file(oauth_filename) twitter = Twitter( auth=OAuth(oauth_token, oauth_token_secret, CONSUMER_KEY, CONSUMER_SECRET), secure=options['secure'], api_version='1', domain='api.twitter.com') try: Action()(twitter, options) # except NoSuchActionError as e: # print(e, file=sys.stderr) # raise SystemExit(1) except TwitterError as e: print(str(e), file=sys.stderr) print("Use 'twitter -h' for help", file=sys.stderr) raise SystemExit(1) print("twitter called inside main")
def twitter_main (args=sys.argv[1:]): arg_options = {} try: parse_args(args, arg_options) except GetoptError as e: print("I can't do that, %s." % (e), file=sys.stderr) print(file=sys.stderr) raise SystemExit(1) config_path = os.path.expanduser( arg_options.get('config_filename') or OPTIONS.get('config_filename')) config_options = loadConfig(config_path) # Apply the various options in order, the most important applied last. # Defaults first, then what's read from config file, then command-line # arguments. options = dict(OPTIONS) for d in config_options, arg_options: for k, v in list(d.items()): if v: options[k] = v if options['refresh'] and options['action'] not in ( 'friends', 'replies'): print("You can only refresh the friends or replies actions.", file=sys.stderr) print("Use 'twitter -h' for help.", file=sys.stderr) return 1 oauth_filename = os.path.expanduser(options['oauth_filename']) if (options['action'] == 'authorize' or not os.path.exists(oauth_filename)): oauth_dance( "the Command-Line Tool", keys.CONSUMER_KEY, keys.CONSUMER_SECRET, options['oauth_filename']) global ansiFormatter ansiFormatter = ansi.AnsiCmd(options["force-ansi"]) oauth_token, oauth_token_secret = read_token_file(oauth_filename) twitter = Twitter( auth=OAuth( oauth_token, oauth_token_secret, keys.CONSUMER_KEY, keys.CONSUMER_SECRET), secure=options['secure'], api_version='1.1', domain='api.twitter.com') try: Action()(twitter, options) except NoSuchActionError as e: print(e, file=sys.stderr) raise SystemExit(1) except TwitterError as e: print(str(e), file=sys.stderr) print("Use 'twitter -h' for help.", file=sys.stderr) raise SystemExit(1)
def main(args=sys.argv[1:]): if not args: print(__doc__) return 1 if not os.path.exists(OAUTH_FILENAME): oauth_dance( "the Python Twitter Logger", CONSUMER_KEY, CONSUMER_SECRET, OAUTH_FILENAME) oauth_token, oauth_token_secret = read_token_file(OAUTH_FILENAME) twitter = Twitter( auth=OAuth( oauth_token, oauth_token_secret, CONSUMER_KEY, CONSUMER_SECRET), domain='api.twitter.com') screen_name = args[0] if args[1:]: max_id = args[1] else: max_id = None n_tweets = 0 while True: try: tweets_processed, max_id = get_tweets(twitter, screen_name, max_id) n_tweets += tweets_processed log_debug("Processed %i tweets (max_id %s)" %(n_tweets, max_id)) if tweets_processed == 0: log_debug("That's it, we got all the tweets we could. Done.") break except TwitterError as e: log_debug("Twitter bailed out. I'm going to sleep a bit then try again") sleep(3) return 0
def main(): CONSUMER_KEY = "NXdiUFv7ZqhO5Ojr8GocA" CONSUMER_SECRET = "CMRgb7BHpHLlcZ0NqHF06pWbFtv1zPqV98KTaFxV2YQ" oauth_filename = os.environ.get('HOME', '') + os.sep + '.my_twitter_oauth' print oauth_filename if not os.path.exists(oauth_filename): oauth_dance("ibread", CONSUMER_KEY, CONSUMER_SECRET, oauth_filename) oauth_token, oauth_token_secret = read_token_file(oauth_filename) print oauth_token, oauth_token_secret tw = Twitter( auth=OAuth(oauth_token, oauth_token_secret, CONSUMER_KEY, CONSUMER_SECRET), secure=True, api_version='1', domain='api.twitter.com') #x = tw.statuses.friends_timeline(count=10) #for i in x: # pass # print i['user']['screen_name'], i['text'] tw.statuses.update(status=u'好困啊')
def __init__(self, configFilename): self.configFilename = configFilename self.config = load_config(self.configFilename) oauth_file = self.config.get('twitter', 'oauth_token_file') if not os.path.exists(oauth_file): oauth_dance("IRC Bot", CONSUMER_KEY, CONSUMER_SECRET, oauth_file) oauth_token, oauth_secret = read_token_file(oauth_file) self.twitter = Twitter( auth=OAuth( oauth_token, oauth_secret, CONSUMER_KEY, CONSUMER_SECRET), api_version='1', domain='api.twitter.com') self.irc = irclib.IRC() self.irc.add_global_handler('privmsg', self.handle_privmsg) self.irc.add_global_handler('ctcp', self.handle_ctcp) self.ircServer = self.irc.server() self.sched = Scheduler( (SchedTask(self.process_events, 1), SchedTask(self.check_statuses, 60))) self.lastUpdate = time.gmtime()
if options['refresh'] and options['action'] not in ( 'home', 'friends', 'public', 'replies'): print >> sys.stderr, "You can only refresh the friends, public, or replies actions." print >> sys.stderr, "Use 'twitter -h' for help." return 1 oauth_filename = os.path.expanduser(options['oauth_filename']) if (options['action'] == 'authorize' or not os.path.exists(oauth_filename)): oauth_dance( "the Command-Line Tool", CONSUMER_KEY, CONSUMER_SECRET, options['oauth_filename']) oauth_token, oauth_token_secret = read_token_file(oauth_filename) twitter = Twitter( auth=OAuth( oauth_token, oauth_token_secret, CONSUMER_KEY, CONSUMER_SECRET), secure=options['secure'], api_version='1', domain='api.twitter.com') try: Action()(twitter, options) except NoSuchActionError, e: print >>sys.stderr, e raise SystemExit(1) except TwitterError, e: print >> sys.stderr, str(e)
def test_read_token_file(self): (access_token, expires_in, access_uid) = read_token_file(self.TOKEN_FILE) self.assertTrue(access_token) self.assertEqual(access_uid, '2133898242')
def test_expires(self): import time (access_token, expires_in, access_uid) = read_token_file(self.TOKEN_FILE) self.assertEqual(type(expires_in), float) self.assertTrue(expires_in - time.time() > 0)
def main(args=sys.argv[1:]): options = { 'oauth': False, 'save-dir': ".", 'api-rate': False, 'timeline': "", 'mentions': "", 'dms': "", 'favorites': False, 'follow-redirects': False, 'redirect-sites': None, 'isoformat': False, } try: parse_args(args, options) except GetoptError as e: err("I can't do that, %s." % e) raise SystemExit(1) # exit if no user given # except if asking for API rate, or archive of timeline or mentions if not options['extra_args'] and not (options['api-rate'] or options['timeline'] or options['mentions'] or options['dms']): print(__doc__) return # authenticate using OAuth, asking for token if necessary if options['oauth']: oauth_filename = (os.getenv("HOME", "") + os.sep + ".twitter-archiver_oauth") if not os.path.exists(oauth_filename): oauth_dance("Twitter-Archiver", CONSUMER_KEY, CONSUMER_SECRET, oauth_filename) oauth_token, oauth_token_secret = read_token_file(oauth_filename) auth = OAuth(oauth_token, oauth_token_secret, CONSUMER_KEY, CONSUMER_SECRET) else: auth = NoAuth() twitter = Twitter(auth=auth, api_version='1.1', domain='api.twitter.com') if options['api-rate']: rate_limit_status(twitter) return global format_text if options['follow-redirects'] or options['redirect-sites'] : if options['redirect-sites']: hosts = parse_host_list(options['redirect-sites']) else: hosts = None format_text = functools.partial(expand_format_text, hosts) else: format_text = direct_format_text # save own timeline or mentions (the user used in OAuth) if options['timeline'] or options['mentions']: if isinstance(auth, NoAuth): err("You must be authenticated to save timeline or mentions.") raise SystemExit(1) if options['timeline']: filename = options['save-dir'] + os.sep + options['timeline'] print("* Archiving own timeline in %s" % filename) elif options['mentions']: filename = options['save-dir'] + os.sep + options['mentions'] print("* Archiving own mentions in %s" % filename) tweets = {} try: tweets = load_tweets(filename) except Exception as e: err("Error when loading saved tweets: %s - continuing without" % str(e)) try: statuses(twitter, "", tweets, options['mentions'], options['favorites'], isoformat=options['isoformat']) except KeyboardInterrupt: err() err("Interrupted") raise SystemExit(1) save_tweets(filename, tweets) if options['timeline']: print("Total tweets in own timeline: %i" % len(tweets)) elif options['mentions']: print("Total mentions: %i" % len(tweets)) if options['dms']: if isinstance(auth, NoAuth): err("You must be authenticated to save DMs.") raise SystemExit(1) filename = options['save-dir'] + os.sep + options['dms'] print("* Archiving own DMs in %s" % filename) dms = {} try: dms = load_tweets(filename) except Exception as e: err("Error when loading saved DMs: %s - continuing without" % str(e)) try: statuses(twitter, "", dms, received_dms=True, isoformat=options['isoformat']) statuses(twitter, "", dms, received_dms=False, isoformat=options['isoformat']) except KeyboardInterrupt: err() err("Interrupted") raise SystemExit(1) save_tweets(filename, dms) print("Total DMs sent and received: %i" % len(dms)) # read users from command-line or stdin users = options['extra_args'] if len(users) == 1 and users[0] == "-": users = [line.strip() for line in sys.stdin.readlines()] # save tweets for every user total, total_new = 0, 0 for user in users: filename = options['save-dir'] + os.sep + user if options['favorites']: filename = filename + "-favorites" print("* Archiving %s tweets in %s" % (user, filename)) tweets = {} try: tweets = load_tweets(filename) except Exception as e: err("Error when loading saved tweets: %s - continuing without" % str(e)) new = 0 before = len(tweets) try: statuses(twitter, user, tweets, options['mentions'], options['favorites'], isoformat=options['isoformat']) except KeyboardInterrupt: err() err("Interrupted") raise SystemExit(1) save_tweets(filename, tweets) total += len(tweets) new = len(tweets) - before total_new += new print("Total tweets for %s: %i (%i new)" % (user, len(tweets), new)) print("Total: %i tweets (%i new) for %i users" % (total, total_new, len(users)))
def main(args=sys.argv[1:]): options = { 'oauth': False, 'followers': True, 'api-rate': False, 'show_id': False } try: parse_args(args, options) except GetoptError as e: err("I can't do that, %s." % e) raise SystemExit(1) # exit if no user or given, except if asking for API rate if not options['extra_args'] and not options['api-rate']: print(__doc__) raise SystemExit(1) # authenticate using OAuth, asking for token if necessary if options['oauth']: oauth_filename = (os.getenv("HOME", "") + os.sep + ".twitter-follow_oauth") if not os.path.exists(oauth_filename): oauth_dance("Twitter-Follow", CONSUMER_KEY, CONSUMER_SECRET, oauth_filename) oauth_token, oauth_token_secret = read_token_file(oauth_filename) auth = OAuth(oauth_token, oauth_token_secret, CONSUMER_KEY, CONSUMER_SECRET) else: auth = NoAuth() twitter = Twitter(auth=auth, api_version='1.1', domain='api.twitter.com') if options['api-rate']: rate_limit_status(twitter) return # obtain list of followers (or following) for every given user for user in options['extra_args']: user_ids, users = [], {} try: user_ids = follow(twitter, user, options['followers']) users = lookup(twitter, user_ids) except KeyboardInterrupt as e: err() err("Interrupted.") raise SystemExit(1) for uid in user_ids: if options['show_id']: try: print(str(uid) + "\t" + users[uid].encode("utf-8")) except KeyError: pass else: try: print(users[uid].encode("utf-8")) except KeyError: pass # print total on stderr to separate from user list on stdout if options['followers']: err("Total followers for %s: %i" % (user, len(user_ids))) else: err("Total users %s is following: %i" % (user, len(user_ids)))
if v: options[k] = v if options['refresh'] and options['action'] not in ('friends', 'public', 'replies'): print >> sys.stderr, "You can only refresh the friends, public, or replies actions." print >> sys.stderr, "Use 'twitter -h' for help." return 1 oauth_filename = os.path.expanduser(options['oauth_filename']) if (options['action'] == 'authorize' or not os.path.exists(oauth_filename)): oauth_dance("the Command-Line Tool", CONSUMER_KEY, CONSUMER_SECRET, options['oauth_filename']) oauth_token, oauth_token_secret = read_token_file(oauth_filename) twitter = Twitter(auth=OAuth(oauth_token, oauth_token_secret, CONSUMER_KEY, CONSUMER_SECRET), secure=options['secure'], api_version='1', domain='api.twitter.com') try: Action()(twitter, options) except NoSuchActionError, e: print >> sys.stderr, e raise SystemExit(1) except TwitterError, e: print >> sys.stderr, str(e) print >> sys.stderr, "Use 'twitter -h' for help."