def connect_to_twitter(self): oauth_token, oauth_secret = twitter.read_token_file('account_credentials') consumer_key, consumer_secret = twitter.read_token_file('app_credentials') authpoop = twitter.OAuth(oauth_token, oauth_secret, consumer_key, consumer_secret) self.rest_t = twitter.Twitter(auth=authpoop ) self.stream_t = twitter.TwitterStream(domain='userstream.twitter.com',auth=authpoop,timeout=30)
def tweet(entry, conf, dryrun=False): """Send a tweet with the title, link and tags from an entry. The first time you need to authorize Acrylamid but than it works without any interaction.""" key = "6k00FRe6w4SZfqEzzzyZVA" secret = "fzRfQcqQX4gcZziyLeoI5wSbnFb7GGj2oEh10hnjPUo" creds = os.path.expanduser('~/.twitter_oauth') if not os.path.exists(creds): twitter.oauth_dance("Acrylamid", key, secret, creds) oauth_token, oauth_token_secret = twitter.read_token_file(creds) t = twitter.Twitter( auth=twitter.OAuth(oauth_token, oauth_token_secret, key, secret)) tweet = u"New Blog Entry: {0} {1} {2}".format( entry.title, helpers.joinurl(conf['www_root'], entry.permalink), ' '.join([u'#' + helpers.safeslug(tag) for tag in entry.tags])) print(' ', bold(blue("tweet ")), end='') print('\n'.join(wrap(tweet.encode('utf8'), subsequent_indent=' ' * 13))) if not dryrun: try: t.statuses.update(status=tweet.encode('utf8')) except twitter.api.TwitterError as e: try: log.warn("%s" % json.loads(e.response_data)['error']) except (ValueError, TypeError): log.warn("Twitter: something went wrong...")
def getTwitterByConfig(filename="MYCREDS.txt", path='.'): oauth_token, oauth_secret = twitter.read_token_file( os.path.join(path, filename)) tw = twitter.Twitter(auth=twitter.OAuth( oauth_token, oauth_secret, APIKEYS.SPOKENTIMELINE_CONSUMERKEY, APIKEYS.SPOKENTIMELINE_CONSUMERSECRET)) return tw
def tweet(entry, conf, dryrun=False): """Send a tweet with the title, link and tags from an entry. The first time you need to authorize Acrylamid but than it works without any interaction.""" key = "6k00FRe6w4SZfqEzzzyZVA" secret = "fzRfQcqQX4gcZziyLeoI5wSbnFb7GGj2oEh10hnjPUo" creds = os.path.expanduser('~/.twitter_oauth') if not os.path.exists(creds): twitter.oauth_dance("Acrylamid", key, secret, creds) oauth_token, oauth_token_secret = twitter.read_token_file(creds) t = twitter.Twitter(auth=twitter.OAuth(oauth_token, oauth_token_secret, key, secret)) tweet = u"New Blog Entry: {0} {1} {2}".format(entry.title, helpers.joinurl(conf['www_root'], entry.permalink), ' '.join([u'#' + helpers.safeslug(tag) for tag in entry.tags])) print(' ', bold(blue("tweet ")), end='') print('\n'.join(wrap(tweet.encode('utf8'), subsequent_indent=' '*13))) if not dryrun: try: t.statuses.update(status=tweet.encode('utf8')) except twitter.api.TwitterError as e: try: log.warn("%s" % json.loads(e.response_data)['error']) except (ValueError, TypeError): log.warn("Twitter: something went wrong...")
def hitTwitter(): cfg = configparser.ConfigParser() cfg.read(CONFIG_FOLDER + "/myTwitter.cfg") TW_ACCOUNT = cfg.get('auth', 'ACCOUNT') CONSUMER_KEY = cfg.get('auth', 'CONSUMER_KEY') CONSUMER_SECRET = cfg.get('auth', 'CONSUMER_SECRET') MY_TWITTER_CREDS = os.path.expanduser(CONFIG_FOLDER + '/.tw_credentials_' + TW_ACCOUNT) if not os.path.exists(DATA_FOLDER): os.makedirs(DATA_FOLDER) if not os.path.exists(MY_TWITTER_CREDS): oauth_dance("TW_App", CONSUMER_KEY, CONSUMER_SECRET, MY_TWITTER_CREDS) oauth_token, oauth_secret = read_token_file(MY_TWITTER_CREDS) if (check_internet()): tw = Twitter(auth=OAuth( oauth_token, oauth_secret, CONSUMER_KEY, CONSUMER_SECRET)) else: raise urllib.error.URLError("No internet connection") return tw
def main(): parser = argparse.ArgumentParser(description='Publishing IBroker DB updates on twitter', formatter_class=argparse.ArgumentDefaultsHelpFormatter, ) parser.add_argument('--config', metavar='JSON_FILENAME', type=str, help='location of config file, using "{}" by default'.format(_DEFAULT_CONFIG_FILE), default=_DEFAULT_CONFIG_FILE ) parser.add_argument('--log-only', action='store_true', help='only logs message to be published, no twitter update') args = parser.parse_args() full_config_path = os.path.abspath(args.config) logging.info('reading from config "%s"', full_config_path) if not os.path.isfile(full_config_path): raise RuntimeError('unable to load config file: {}'.format(full_config_path)) config_json = json.load(open(args.config, 'rt')) config_keys = ('target_folder_id', 'twitter_consumer_token', 'twitter_consumer_secret', 'twitter_token_filename') for config_key in config_keys: if config_key not in config_json.keys(): raise RuntimeError('Key {} is missing from config file'.format(config_key)) consumer_token = config_json['twitter_consumer_token'] consumer_secret = config_json['twitter_consumer_secret'] twitter_token_filename = config_json['twitter_token_filename'] if not os.path.isfile(twitter_token_filename): oauth_dance('announcements-app', consumer_token, consumer_secret, twitter_token_filename) oauth_token, oauth_token_secret = read_token_file(twitter_token_filename) twitter_service = Twitter(auth=OAuth(oauth_token, oauth_token_secret, consumer_token, consumer_secret)) target_folder_id = config_json['target_folder_id'] publish_twitter(twitter_service, target_folder_id, args.log_only)
def twitter_init(): try: config_settings["twitter_creds_file"] = os.path.abspath( os.path.expanduser(config_settings["twitter_creds_file"]) ) if not os.path.exists(config_settings["twitter_creds_file"]): twitter.oauth_dance( "fuzzer_stats", config_settings["twitter_consumer_key"], config_settings["twitter_consumer_secret"], config_settings["twitter_creds_file"], ) oauth_token, oauth_secret = twitter.read_token_file(config_settings["twitter_creds_file"]) twitter_instance = twitter.Twitter( auth=twitter.OAuth( oauth_token, oauth_secret, config_settings["twitter_consumer_key"], config_settings["twitter_consumer_secret"], ) ) return twitter_instance except (twitter.TwitterHTTPError, URLError): print_err("Network error, twitter login failed! Check your connection!") sys.exit(1)
def tweet(config, in_queue, flag, session_mutex): oauth_token, oauth_secret = twitter.read_token_file(config.twitter_keys.cred_path) _twitter = twitter.Twitter(auth=twitter.OAuth(oauth_token, oauth_secret, config.twitter_keys.key, config.twitter_keys.secret)) def send_tweet(body): print("TWEET: Posting tweet...") _twitter.statuses.update(status=body) print("TWEET: Complete") count = 0 flag.wait() while flag.isSet() or not in_queue.empty(): try: msg, schedule, uid = in_queue.get(timeout=10) count += 1 print("\nTWEET ATOM: {0}".format(datetime.fromtimestamp(schedule).strftime("%H:%M:%S %m-%d-%Y"))) with session_mutex: session = db.Session(config.resources.dbschema) db.Atom.set_state(db.WAIT, uid, session) session.commit() session.close() ## Wait for schedule it hit while int(time()) < schedule: if not flag.isSet(): print("TWEET: Warning: Exiting with scheduled tweets. Oh well") return else: sleep(1) send_tweet(msg) with session_mutex: session = db.Session(config.resources.dbschema) db.Atom.set_state(db.SENT, uid, session) session.commit() session.close() sleep(config.tweet_quota.delta) if (count % config.tweet_quota.joke_align) == 0: with session_mutex: session = db.Session(config.resources.dbschema) joke = db.Joke.get_next(session) if joke: print("SENDING A JOKE") send_tweet(joke.body) session.commit() sleep(config.tweet_quota.delta) session.close() except Empty: sleep(0) print("Exiting Tweet Engine.")
def post_to_twitter(msg): ''' todo: check if trigramosaurus has been updated today, if so, skip updating. ''' oauth_token, oauth_secret = twitter.read_token_file('trigramosaurus_credentials') consumer_key, consumer_secret = twitter.read_token_file('app_credentials') t = twitter.Twitter( auth=twitter.OAuth(oauth_token, oauth_secret, consumer_key, consumer_secret) ) try: result = t.statuses.update(status=msg) # invalid status causes twitter.api.TwitterHTTPError except: error_out("some sort of twitter error",True) return result
def get_twitter(): MY_TWITTER_CREDS = os.path.expanduser('~/.twitter_oauth') oauth_token, oauth_secret = read_token_file(MY_TWITTER_CREDS) t = Twitter( auth=OAuth(oauth_token, oauth_secret, CONSUMER_KEY, CONSUMER_SECRET) ) return t
def get_auth(): """ Twitter has some bizarre requirements about how to authorize an "app" to use its API. The user of the app has to log in to get a secret token. That's fine. But the app itself has its own "consumer secret" token. The app has to know it, and the user of the app has to not know it. This is, of course, impossible. It's equivalent to DRM. Your computer can't *really* make use of secret information while hiding the same information from you. The threat appears to be that, if you have this super-sekrit token, you can impersonate the app while doing something different. Well, of course you can do that, because you *have the source code* and you can change it to do what you want. You still have to log in as a particular user who has a token that's actually secret, you know. Even developers of closed-source applications that use the Twitter API are unsure what to do, for good reason. These "secrets" are not secret in any cryptographic sense. A bit of Googling shows that the secret tokens for every popular Twitter app are already posted on the Web. Twitter wants us to pretend this string can be kept secret, and hide this secret behind a fig leaf like everybody else does. So that's what we've done. """ from twitter.oauth import OAuth from twitter import oauth_dance, read_token_file def unhide(secret): """ Do something mysterious and exactly as secure as every other Twitter app. """ return ''.join([chr(ord(c) - 0x2800) for c in secret]) fig_leaf = '⠴⡹⠹⡩⠶⠴⡶⡅⡂⡩⡅⠳⡏⡉⡈⠰⠰⡹⡥⡶⡈⡐⡍⡂⡫⡍⡗⡬⡒⡧⡶⡣⡰⡄⡧⡸⡑⡣⠵⡓⠶⠴⡁' consumer_key = 'OFhyNd2Zt4Ba6gJGJXfbsw' if os.path.exists(AUTH_TOKEN_PATH): token, token_secret = read_token_file(AUTH_TOKEN_PATH) else: authdir = os.path.dirname(AUTH_TOKEN_PATH) if not os.path.exists(authdir): os.makedirs(authdir) token, token_secret = oauth_dance(app_name='ftfy-tester', consumer_key=consumer_key, consumer_secret=unhide(fig_leaf), token_filename=AUTH_TOKEN_PATH) return OAuth(token=token, token_secret=token_secret, consumer_key=consumer_key, consumer_secret=unhide(fig_leaf))
def build_oauth(config): if not os.path.exists(config.TWITTER_USER_CREDENTIALS): raise ValueError('App not yet connected to Twitter account') (token, token_secret) = twitter.read_token_file( config.TWITTER_USER_CREDENTIALS) return twitter.OAuth(token, token_secret, config.TWITTER_CONSUMER_KEY, config.TWITTER_CONSUMER_SECRET)
def tweet(entry): oauth_filename = OPTIONS["oauth_filename"] oauth_token, oauth_token_secret = read_token_file(oauth_filename) t = Twitter(auth=OAuth(oauth_token, oauth_token_secret, CONSUMER_KEY, CONSUMER_SECRET)) status = "%s" % (entry) t.statuses.update(status=status)
def authenicate(): twitter_credentials = os.path.expanduser('~/.GjertsenTweet') if not os.path.exists(twitter_credentials): oauth_dance('GjertsenTweet', CONSUMER_KEY, CONSUMER_SECRET, twitter_credentials) token, token_secret = read_token_file(twitter_credentials) return OAuth(token, token_secret, CONSUMER_KEY, CONSUMER_SECRET)
def __init__ (self, ckey, csecret, token_file, user_name=""): if not os.path.exists(token_file): twitter.oauth_dance(user_name, ckey, csecret, token_file) self.oauth_token, self.oauth_token_secret = twitter.read_token_file(token_file) self.handle = twitter.Twitter( auth=twitter.OAuth(self.oauth_token, self.oauth_token_secret, ckey, csecret))
def get_auth(): """ Twitter has some bizarre requirements about how to authorize an "app" to use its API. The user of the app has to log in to get a secret token. That's fine. But the app itself has its own "consumer secret" token. The app has to know it, and the user of the app has to not know it. This is, of course, impossible. It's equivalent to DRM. Your computer can't *really* make use of secret information while hiding the same information from you. The threat appears to be that, if you have this super-sekrit token, you can impersonate the app while doing something different. Well, of course you can do that, because you *have the source code* and you can change it to do what you want. You still have to log in as a particular user who has a token that's actually secret, you know. Even developers of closed-source applications that use the Twitter API are unsure what to do, for good reason. These "secrets" are not secret in any cryptographic sense. A bit of Googling shows that the secret tokens for every popular Twitter app are already posted on the Web. Twitter wants us to pretend this string can be kept secret, and hide this secret behind a fig leaf like everybody else does. So that's what we've done. """ from twitter.oauth import OAuth from twitter import oauth_dance, read_token_file def unhide(secret): """ Do something mysterious and exactly as secure as every other Twitter app. """ return "".join([chr(ord(c) - 0x2800) for c in secret]) fig_leaf = "⠴⡹⠹⡩⠶⠴⡶⡅⡂⡩⡅⠳⡏⡉⡈⠰⠰⡹⡥⡶⡈⡐⡍⡂⡫⡍⡗⡬⡒⡧⡶⡣⡰⡄⡧⡸⡑⡣⠵⡓⠶⠴⡁" consumer_key = "OFhyNd2Zt4Ba6gJGJXfbsw" if os.path.exists(AUTH_TOKEN_PATH): token, token_secret = read_token_file(AUTH_TOKEN_PATH) else: authdir = os.path.dirname(AUTH_TOKEN_PATH) if not os.path.exists(authdir): os.makedirs(authdir) token, token_secret = oauth_dance( app_name="ftfy-tester", consumer_key=consumer_key, consumer_secret=unhide(fig_leaf), token_filename=AUTH_TOKEN_PATH, ) return OAuth(token=token, token_secret=token_secret, consumer_key=consumer_key, consumer_secret=unhide(fig_leaf))
def tweet(entry): oauth_filename = OPTIONS['oauth_filename'] oauth_token, oauth_token_secret = read_token_file(oauth_filename) t = Twitter(auth=OAuth(oauth_token, oauth_token_secret, CONSUMER_KEY, CONSUMER_SECRET)) status = '%s' % (entry) t.statuses.update(status=status)
def connect(): "Prepare an authenticated API object for use." oauth_token, oauth_secret = twitter.read_token_file( os.path.expanduser(OAUTH_FILE) ) t = twitter.Twitter(auth=twitter.OAuth(oauth_token, oauth_secret, CONSUMER_KEY, CONSUMER_SECRET)) return t
def setup_twitter(consumer_key, consumer_secret, credentials_file): # Authenticate to twitter using OAuth if not os.path.exists(credentials_file): twitter.oauth_dance("Tweet to Door Sign Converter", consumer_key, consumer_secret, credentials_file) oauth_token, oauth_secret = twitter.read_token_file(credentials_file) t = twitter.Twitter(auth=twitter.OAuth( oauth_token, oauth_secret, consumer_key, consumer_secret)) return t
def get_twitter(): MY_TWITTER_CREDS = os.path.join(os.path.dirname(__file__), '.clocktweeter_credentials') if not os.path.exists(MY_TWITTER_CREDS): twitter.oauth_dance("Trinity clock tweeter", CONSUMER_KEY, CONSUMER_SECRET, MY_TWITTER_CREDS) oauth_token, oauth_secret = twitter.read_token_file(MY_TWITTER_CREDS) t = twitter.Twitter(auth=twitter.OAuth( oauth_token, oauth_secret, CONSUMER_KEY, CONSUMER_SECRET)) return t
def oauth_login(consumer_key, consumer_secret, access_token, access_token_secret): if not access_token or not access_token_secret: oauth_file = './twitter_oauth' if not os.path.exists(oauth_file): twitter.oauth_dance("App", consumer_key, consumer_secret, oauth_file) access_token, access_token_secret = twitter.read_token_file(oauth_file) auth = twitter.oauth.OAuth(access_token, access_token_secret, consumer_key, consumer_secret) return twitter.Twitter(auth=auth)
def connect(): global t # Twitter credentials CONSUMER_KEY='JEdRRoDsfwzCtupkir4ivQ' CONSUMER_SECRET='PAbSSmzQxbcnkYYH2vQpKVSq2yPARfKm0Yl6DrLc' MY_TWITTER_CREDS = os.path.expanduser('~/.my_app_credentials') if not os.path.exists(MY_TWITTER_CREDS): oauth_dance("Semeval sentiment analysis", CONSUMER_KEY, CONSUMER_SECRET, MY_TWITTER_CREDS) oauth_token, oauth_secret = read_token_file(MY_TWITTER_CREDS) t = Twitter(auth=OAuth(oauth_token, oauth_secret, CONSUMER_KEY, CONSUMER_SECRET))
def tweet(self, app_name, version): MY_TWITTER_CREDS = os.path.expanduser('~/.twitter_oauth') CONSUMER_KEY, CONSUMER_SECRET = self.load_app_keys() if not os.path.exists(MY_TWITTER_CREDS): twitter.oauth_dance("autopkgsays", CONSUMER_KEY, CONSUMER_SECRET, MY_TWITTER_CREDS) oauth_token, oauth_secret = twitter.read_token_file(MY_TWITTER_CREDS) twitter_instance = twitter.Twitter(auth=twitter.OAuth( oauth_token, oauth_secret, CONSUMER_KEY, CONSUMER_SECRET)) # Now work with Twitter twitter_instance.statuses.update(status="%s version %s has been released" % (app_name, version))
def connect(): global t # Twitter credentials CONSUMER_KEY = "JEdRRoDsfwzCtupkir4ivQ" CONSUMER_SECRET = "PAbSSmzQxbcnkYYH2vQpKVSq2yPARfKm0Yl6DrLc" MY_TWITTER_CREDS = os.path.expanduser("~/.my_app_credentials") if not os.path.exists(MY_TWITTER_CREDS): oauth_dance("Semeval sentiment analysis", CONSUMER_KEY, CONSUMER_SECRET, MY_TWITTER_CREDS) oauth_token, oauth_secret = read_token_file(MY_TWITTER_CREDS) t = Twitter(auth=OAuth(oauth_token, oauth_secret, CONSUMER_KEY, CONSUMER_SECRET))
def get_twitter_client(): CONSUMER_KEY = 'mDW8dNVXrioYiSjse9hneaDGy' CONSUMER_SECRET = 'jg0A2CcHaVSBWfsOqhgABUxQoZUx7sstEk9NSVUbVphkGJr1Zb' oauth_filename = 'credentials' if not os.path.exists(oauth_filename): twitter.oauth_dance("ruukku", CONSUMER_KEY, CONSUMER_SECRET, oauth_filename) oauth_token, oauth_secret = twitter.read_token_file(oauth_filename) auth = twitter.OAuth(oauth_token, oauth_secret, CONSUMER_KEY, CONSUMER_SECRET) return twitter.Twitter(auth=auth)
def send_text_tweet(config, text='Hello World !'): token, token_secret = twitter.read_token_file( config.TWITTER_USER_CREDENTIALS) twitter_api = twitter.Twitter( auth=twitter.OAuth(token, token_secret, config.TWITTER_CONSUMER_KEY, config.TWITTER_CONSUMER_SECRET)) # Now work with Twitter twitter_api.statuses.update(status=text)
def __init__(self): if not file.exists(OAUTH_TOKEN_FILE): oauth_dance("mpvshots", CONSUMER_KEY, CONSUMER_SECRET, OAUTH_TOKEN_FILE) oauth_token, oauth_secret = read_token_file(OAUTH_TOKEN_FILE) oauth = OAuth(oauth_token, oauth_secret, CONSUMER_KEY, CONSUMER_SECRET) self._twitter = Twitter(auth=oauth) self._upload = Twitter(domain="upload.twitter.com", auth=oauth)
def send_twitter(APP_NAME, CONSUMER_KEY, CONSUMER_SECRET, tweet): MY_TWITTER_CREDS = os.path.expanduser('./twitter_id') if not os.path.exists(MY_TWITTER_CREDS): twitter.oauth_dance(APP_NAME, CONSUMER_KEY, CONSUMER_SECRET, MY_TWITTER_CREDS) print(em('saved access token') + 'at' + MY_TWITTER_CREDS) oauth_token, oauth_secret = twitter.read_token_file(MY_TWITTER_CREDS) tw = twitter.Twitter(auth=twitter.OAuth(oauth_token, oauth_secret, CONSUMER_KEY, CONSUMER_SECRET)) tw.statuses.update(status=tweet) print('Tweeted.')
def update_status(text): text = text.strip() if not text: raise RuntimeError("No text to update") oauth_token, oauth_secret = tw.read_token_file(TOKEN_FILE) t = tw.Twitter(auth=tw.OAuth(oauth_token, oauth_secret, CONSUMER_KEY, CONSUMER_SECRET)) t.statuses.update(status=text) return
def authenticate(self): """ Authenticates with twitter app and returns a Twitter object. """ if not os.path.exists(self.TWITTER_CREDS): oauth_dance( self.APP_NAME, self.CONSUMER_KEY, self._consumer_secret, self.TWITTER_CREDS ) oauth_token, oauth_secret = read_token_file(self.TWITTER_CREDS) return Twitter(auth=OAuth( oauth_token, oauth_secret, self.CONSUMER_KEY, self._consumer_secret ))
def __init__(self, autogen=True, markovdb=os.path.expanduser("~/markov"), twcreds=os.path.expanduser("~/.michiov_twitter_credentials"),twappcreds=os.path.expanduser("~/.michiov_twitter_appdata")): self.mc = MarkovChain(markovdb) self.reload() if not os.path.exists(twappcreds): print("Lack of app creds") sys.exit(1) twcons = json.loads(open(twappcreds).read()) conskey = twcons['key'] conssec = twcons['secret'] while not os.path.exists(twcreds): twitter.oauth_dance("MPRZ Tech Labs", conskey, conssec, twcreds) oauth_token, oauth_secret = twitter.read_token_file(twcreds) self.t = twitter.Twitter(auth=twitter.OAuth(oauth_token, oauth_secret, conskey, conssec))
def connect_twitter(): """Initialize connection to Twitter""" # authenticate creds = os.path.expanduser('~/.tweets2sql-oauth') CONSUMER_KEY = 'mikYMFxbLhD1TAhaztCshA' CONSUMER_SECRET = 'Ys9VHBWLS5fX4cFnDHSVac52fl388JV19yJz1WMss' if not os.path.exists(creds): twitter.oauth_dance("tweets2sql", CONSUMER_KEY, CONSUMER_SECRET, creds) oauth_token, oauth_secret = twitter.read_token_file(creds) auth = twitter.OAuth(oauth_token, oauth_secret, CONSUMER_KEY, CONSUMER_SECRET) # connect return twitter.Twitter(domain='api.twitter.com', auth=auth, api_version = '1.1')
def __init__( self ): oauth_token, oauth_token_secret = twitter.read_token_file( config.TWITTER_OAUTH_FILE ); oauth = twitter.OAuth( oauth_token, oauth_token_secret, config.TWITTER_CONSUMER_KEY, config.TWITTER_CONSUMER_SECRET ); self.__tw = twitter.Twitter( auth = oauth, secure = True, domain = "api.twitter.com" );
def __init__(self, connect=True): # Offline? if connect: # Twitter credentials CONSUMER_KEY='JEdRRoDsfwzCtupkir4ivQ' CONSUMER_SECRET='PAbSSmzQxbcnkYYH2vQpKVSq2yPARfKm0Yl6DrLc' MY_TWITTER_CREDS = os.path.expanduser('~/.my_app_credentials') if not os.path.exists(MY_TWITTER_CREDS): oauth_dance("Semeval sentiment analysis", CONSUMER_KEY, CONSUMER_SECRET, MY_TWITTER_CREDS) oauth_token, oauth_secret = read_token_file(MY_TWITTER_CREDS) self.t = Twitter(auth=OAuth(oauth_token, oauth_secret, CONSUMER_KEY, CONSUMER_SECRET))
def __init__(self, app_name, consumer_key, consumer_secret): creds = os.path.expanduser('~/.tweeter_credentials') if not os.path.exists(creds): twitter.oauth_dance( app_name, consumer_key, consumer_secret, creds) oauth_token, oauth_secret = twitter.read_token_file(creds) self.t = twitter.Twitter( auth=twitter.OAuth( oauth_token, oauth_secret, consumer_key, consumer_secret ) )
def oauth_login(consumer_key, consumer_secret, access_token, access_token_secret): if not access_token or not access_token_secret: oauth_file = './twitter_oauth' if not os.path.exists(oauth_file): twitter.oauth_dance("App", consumer_key, consumer_secret, oauth_file) access_token, access_token_secret = twitter.read_token_file( oauth_file) auth = twitter.oauth.OAuth(access_token, access_token_secret, consumer_key, consumer_secret) return twitter.Twitter(auth=auth)
def twitter_init(): try: global config_interval, config_twitter_consumer_key, config_twitter_consumer_secret, config_twitter_creds_file if not os.path.exists(config_twitter_creds_file): twitter.oauth_dance("fuzzer_stats", config_twitter_consumer_key, config_twitter_consumer_secret, config_twitter_creds_file) oauth_token, oauth_secret = twitter.read_token_file(config_twitter_creds_file) twitter_instance = twitter.Twitter(auth=twitter.OAuth(oauth_token, oauth_secret, config_twitter_consumer_key, config_twitter_consumer_secret)) return twitter_instance except (twitter.TwitterHTTPError, URLError): print_err("Network error, twitter login failed! Check your connection!") sys.exit(1)
def twitter_init(config): try: config['twitter_creds_file'] = os.path.abspath(os.path.expanduser(config['twitter_creds_file'])) if not os.path.exists(config['twitter_creds_file']): twitter.oauth_dance("fuzzer_stats", config['twitter_consumer_key'], config['twitter_consumer_secret'], config['twitter_creds_file']) oauth_token, oauth_secret = twitter.read_token_file(config['twitter_creds_file']) twitter_instance = twitter.Twitter(auth=twitter.OAuth(oauth_token, oauth_secret, config['twitter_consumer_key'], config['twitter_consumer_secret'])) return twitter_instance except (twitter.TwitterHTTPError, URLError): print_err("Network error, twitter login failed! Check your connection!") sys.exit(1)
def auth(): MY_TWITTER_CREDS = os.path.expanduser('~/.twitter') APP_NAME = 'unfollower' CONSUMER_KEY = input('Input consumer key:') CONSUMER_SECRET = input('Input consumer secret:') if not os.path.exists(MY_TWITTER_CREDS): print('oauth dance...') twitter.oauth_dance(APP_NAME, CONSUMER_KEY, CONSUMER_SECRET, MY_TWITTER_CREDS) oauth_token, oauth_secret = twitter.read_token_file(MY_TWITTER_CREDS) print('auth...') t = twitter.Twitter(auth=twitter.OAuth(oauth_token, oauth_secret, CONSUMER_KEY, CONSUMER_SECRET)) return t
def __init__(self, config, name): # this is bad. move it to the ini self.username = name self.config = config # load Twitter app consumer details # TODO: move this to ini file consumer_file = os.path.expanduser("~/.mimicbot/%s/consumer" % name) consumer_key, consumer_secret = twitter.read_token_file(consumer_file) # load authentication auth_file = os.path.expanduser("~/.mimicbot/%s/auth" % name) if not os.path.exists(auth_file): # none exist, so get authentication details twitter.oauth_dance("mimicbot", consumer_key, consumer_secret, auth_file) # authenticate oauth_token, oauth_secret = twitter.read_token_file(auth_file) self.twitter = twitter.Twitter(auth=twitter.OAuth( oauth_token, oauth_secret, consumer_key, consumer_secret))
def _get_credentials(self, creds_file): """ Get Twitter credentials from file if one exists. Otherwise request credentials via oauth. """ if not os.path.exists(creds_file): print 'Authorising with Twitter...' try: twitter.oauth_dance(APP, TCK, TCS, creds_file) except twitter.TwitterHTTPError as err: raise OutputError(err) oauth_token, oauth_secret = twitter.read_token_file(creds_file) return twitter.Twitter( auth=twitter.OAuth(oauth_token, oauth_secret, TCK, TCS))
def __init_client(self): """Initialise the Twitter client.""" # get application OAuth tokens with open(Twitterminal.APP_CREDS_FILE) as f: api_tokens = [line.strip() for line in f] if len(api_tokens) != 2: exit("app creds key incorrectly formatted", ERR_OAUTH) # get consumer OAuth tokens # TODO: the oauth dance if required #twitter.oauth_dance("twitterminal.py", api_tokens[0], api_tokens[1], Twitterminal.CREDS_FILE) oauth_token, oauth_secret = twitter.read_token_file(Twitterminal.CREDS_FILE) self.client = twitter.Twitter(auth=twitter.OAuth(oauth_token, oauth_secret, api_tokens[0], api_tokens[1]))
def __init__(self): #these come from creating a twitter application via dev.twitter.com self.consumer_key = "see documentation" self.consumer_secret = "see documentation" #file path to twitter credentials self.oauth_filename = 'twitter_oauth' #check to see if doesn't exist if not os.path.exists(self.oauth_filename): #create the file by getting authorisation from twitter twitter.oauth_dance("see documentation", self.consumer_key, self.consumer_secret, self.oauth_filename) #get the authorisation tokens from the file self.oauth_token, self.oauth_token_secret = twitter.read_token_file(self.oauth_filename)
def form_valid(self, form): link = form.save(commit=False) is_authenticated = self.request.user.is_authenticated() if not is_authenticated: owner, created = User.objects.get_or_create( email=form.cleaned_data['owner_email'], defaults={'username': form.cleaned_data['owner_username']}) try: self.request.session['owner_email'] = form.cleaned_data[ 'owner_email'] self.request.session['owner_username'] = form.cleaned_data[ 'owner_username'] except KeyError: pass if created: owner.save() else: owner = self.request.user link.owner = owner link.save() T_PATH = os.path.join(settings.ROOT_PATH, 'twitter') oauth = OAuth(*read_token_file('%s/oauth_creds' % T_PATH) + ('%s' % settings.TWITTER_CONSUMER_KEY, '%s' % settings.TWITTER_CONSUMER_SECRET)) twitter = Twitter(domain='api.twitter.com', auth=oauth, api_version='1') link_detail_url = '%s/detail/%s-%s %s' % ( Site.objects.get_current().domain, link.slug, link.id, link.title) twitter.statuses.update(status='%s' % link_detail_url) if settings.INFORM_NEW_LINKS: send_mail('%s' % Site.objects.get_current().name, '%s' % link_detail_url, 'mailer@%s' % Site.objects.get_current().domain, [settings.ADMINS[0][1]], fail_silently=True) return HttpResponseRedirect(link.get_absolute_url())
def _twitter_login(constructor): import os from twitter import oauth_dance, OAuth, read_token_file CONSUMER_KEY = 'i795JDFmQlZzlfJpIrQQxZ2RP' CONSUMER_SECRET = 'ptHQEfq4aBnrUlzX5Wwdlss0iuBaZfhzm9t9OwdAtKqio5UeAC' MY_TWITTER_CREDS = os.path.expanduser('~/.twitter_oauth_lvbstats') if not os.path.exists(MY_TWITTER_CREDS): oauth_dance("lvbStats", CONSUMER_KEY, CONSUMER_SECRET, MY_TWITTER_CREDS) oauth_token, oauth_secret = read_token_file(MY_TWITTER_CREDS) twitter = constructor( auth=OAuth(oauth_token, oauth_secret, CONSUMER_KEY, CONSUMER_SECRET)) return twitter
def get_oauth(): """Authenticate/register.""" # I realize this isn't actually secret. The key/secret combo is linked to # your account though, if you do feel the need to abuse it secret = str(codecs.decode(Settings.API_SECRET, "rot-13")) if not os.path.exists(Settings.AUTH_FILE): twitter.oauth_dance( "pyweet", Settings.API, secret, Settings.AUTH_FILE, ) token, user_secret = twitter.read_token_file(Settings.AUTH_FILE) return twitter.OAuth(token, user_secret, Settings.API, secret)
def twitter_connect(): # Informacje o kluczach aplikacji dla api twittera twitter_key = '' twitter_secret = '' twitter_authfile = '.twitter_authdata' if not os.path.exists(twitter_authfile): twitter.oauth_dance("Gniewomir - TelecomixPL News Bot", twitter_key, twitter_secret, twitter_authfile) twitter_oauth_token, twitter_oauth_secret = twitter.read_token_file(twitter_authfile) # Łączenie z twitterem t = twitter.Twitter(auth=twitter.OAuth( twitter_oauth_token, twitter_oauth_secret, twitter_key, twitter_secret)) return t
def get_twitter_instance(): oauth_filename = '.twitter_oauth' oauth_path = join(dirname(abspath(__file__)), oauth_filename) if not exists(oauth_path): oauth_dance("the Command-Line Tool", CONSUMER_KEY, CONSUMER_SECRET, oauth_filename) oauth_token, oauth_token_secret = read_token_file(oauth_path) twitter = Twitter(auth=OAuth(oauth_token, oauth_token_secret, CONSUMER_KEY, CONSUMER_SECRET), secure=True, api_version='1.1', domain='api.twitter.com') return twitter
def print_twitter_feed(config, domain='userstream.twitter.com'): token, token_secret = twitter.read_token_file( config.TWITTER_USER_CREDENTIALS) oauth=twitter.OAuth(token, token_secret, config.TWITTER_CONSUMER_KEY, config.TWITTER_CONSUMER_SECRET) twitter_userstream = twitter.TwitterStream( auth=oauth, domain=domain) for msg in twitter_userstream.user(): print ('Message received:') print ('-' * 72) pprint.pprint(msg) print ('-' * 72)
def twitter_init(): try: global config_interval, config_twitter_consumer_key, config_twitter_consumer_secret, config_twitter_creds_file if not os.path.exists(config_twitter_creds_file): twitter.oauth_dance("fuzzer_stats", config_twitter_consumer_key, config_twitter_consumer_secret, config_twitter_creds_file) oauth_token, oauth_secret = twitter.read_token_file( config_twitter_creds_file) twitter_instance = twitter.Twitter(auth=twitter.OAuth( oauth_token, oauth_secret, config_twitter_consumer_key, config_twitter_consumer_secret)) return twitter_instance except (twitter.TwitterHTTPError, URLError): print_err( "Network error, twitter login failed! Check your connection!") sys.exit(1)
def __init__(self): CONSUMER_KEY = settings.consumer_key CONSUMER_SECRET = settings.consumer_secret if not (CONSUMER_KEY and CONSUMER_SECRET): print "Whoa! Fill in your keys in settings.py first!" sys.exit(1) TWITTER_CREDS = os.path.expanduser('~/.tweetdns') if not os.path.exists(TWITTER_CREDS): oauth_dance("tweetdns", CONSUMER_KEY, CONSUMER_SECRET, TWITTER_CREDS) oauth_token, oauth_secret = read_token_file(TWITTER_CREDS) tauth = OAuth(oauth_token, oauth_secret, CONSUMER_KEY, CONSUMER_SECRET) self.twitter = Twitter(auth=tauth)
def load_credentials_and_setup(): """ Load the keys and tokens, and setup the twitter client """ #Get the Key and Secret from (gitignored) files assert (exists(KEY_FILE)) assert (exists(SECRET_FILE)) logging.info("Setting up Twitter Client") with open("consumer.key", "r") as f: C_KEY = f.read().strip() with open("consumer.secret", "r") as f: C_SECRET = f.read().strip() if not exists(MY_TWITTER_CREDS): tw.oauth_dance("jgNetworkAnalysis", C_KEY, C_SECRET, MY_TWITTER_CREDS) TOKEN, TOKEN_SECRET = tw.read_token_file(MY_TWITTER_CREDS) assert (all( [x is not None for x in [C_KEY, C_SECRET, TOKEN, TOKEN_SECRET]])) t = tw.Twitter(auth=tw.OAuth(TOKEN, TOKEN_SECRET, C_KEY, C_SECRET)) return t
def hitTwitter(): cfg = configparser.ConfigParser() cfg.read("myTwitter.cfg") TW_ACCOUNT = cfg.get('auth', 'ACCOUNT') CONSUMER_KEY = cfg.get('auth', 'CONSUMER_KEY') CONSUMER_SECRET = cfg.get('auth', 'CONSUMER_SECRET') MY_TWITTER_CREDS = os.path.expanduser('.tw_credentials_' + TW_ACCOUNT) if not os.path.exists("data"): os.makedirs("data") if not os.path.exists(MY_TWITTER_CREDS): oauth_dance("TW_App", CONSUMER_KEY, CONSUMER_SECRET, MY_TWITTER_CREDS) oauth_token, oauth_secret = read_token_file(MY_TWITTER_CREDS) tw = Twitter( auth=OAuth(oauth_token, oauth_secret, CONSUMER_KEY, CONSUMER_SECRET)) return tw
def post_new_tweet(new_tweet): """post status to twitter using twitter API through the twitter module https://twitter.com/MCB_Harvard """ oauth = OAuth(*read_token_file(settings.TWITTER_OAUTH_PARAM_FILE)\ + (settings.TWITTER_CONSUMER_KEY, settings.TWITTER_CONSUMER_SECRET)) # tweet_conn = Twitter( auth=oauth\ , api_version='1.1') # authentication #new_tweet = "%s %s #%s" % (description, short_url, hashtag) """example: "Harvard Professor Doug Melton discovers novel protein. Check it out. short_url #harvard""" if len(new_tweet) <= 140: tweet_conn.statuses.update(status="%s" % new_tweet) #print 'status updated: %s' % new_tweet return True else: #print "Status cannot be over 140 characters." return False
def load_credentials_and_setup(credentials:Path, key:Path, secret:Path): """ Load the keys and tokens, and setup the twitter client """ #Get the Key and Secret from (gitignored) files MY_TWITTER_CREDS = abspath(expanduser(credentials)) KEY_FILE = abspath(expanduser(key)) SECRET_FILE = abspath(expanduser(secret)) assert(all([exists(x) for x in [MY_TWITTER_CREDS, KEY_FILE, SECRET_FILE]])) logging.info("Setting up Twitter Client") with open(KEY_FILE,"r") as f: C_KEY = f.read().strip() with open(SECRET_FILE, "r") as f: C_SECRET = f.read().strip() if not exists(MY_TWITTER_CREDS): tw.oauth_dance("jgNetworkAnalysis", C_KEY, C_SECRET, MY_TWITTER_CREDS) TOKEN, TOKEN_SECRET = tw.read_token_file(MY_TWITTER_CREDS) assert(all([x is not None for x in [C_KEY, C_SECRET, TOKEN, TOKEN_SECRET]])) return tw.Twitter(auth=tw.OAuth(TOKEN, TOKEN_SECRET, C_KEY, C_SECRET))