Ejemplo n.º 1
0
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...")
Ejemplo n.º 2
0
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)
Ejemplo n.º 3
0
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
Ejemplo n.º 4
0
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...")
Ejemplo n.º 5
0
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)
Ejemplo n.º 6
0
def oauthToken(oauth_filename=os.sep.join(
    [os.getenv('HOME'), ".twitter_oauth"])):
    if (not os.path.exists(oauth_filename)):
        oauth_dance("the Command-Line Tool", CLIENT_KEY, CLIENT_SECRET,
                    oauth_filename)
    oauth_token, oauth_token_secret = read_token_file(oauth_filename)
    return twitter.OAuth(oauth_token, oauth_token_secret, CLIENT_KEY,
                         CLIENT_SECRET)
Ejemplo n.º 7
0
def connect(consumer_key, consumer_secret):
    f = config.prepare_oauth_tokens_file()
    if not config.have_oauth_tokens():
        twitter.oauth_dance("Twema", consumer_key, consumer_secret, f)
    oauth_token, oauth_token_secret = twitter.oauth.read_token_file(f)
    oauth = twitter.oauth.OAuth(oauth_token, oauth_token_secret, consumer_key,
                                consumer_secret)
    return twitter.api.Twitter(auth=oauth)
Ejemplo n.º 8
0
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)
Ejemplo n.º 9
0
 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))
Ejemplo n.º 10
0
    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)
Ejemplo n.º 11
0
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
Ejemplo n.º 12
0
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 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
Ejemplo n.º 14
0
    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))
Ejemplo n.º 16
0
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 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))
Ejemplo n.º 18
0
    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)
Ejemplo n.º 19
0
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 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 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.')
Ejemplo n.º 22
0
    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))
Ejemplo n.º 23
0
 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))
Ejemplo n.º 24
0
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)
Ejemplo n.º 25
0
    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)
Ejemplo n.º 26
0
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)
Ejemplo n.º 27
0
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
Ejemplo n.º 28
0
 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
                                                 )
                              )
Ejemplo n.º 29
0
    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))
Ejemplo n.º 30
0
    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)
Ejemplo n.º 31
0
  def __init__(self, db_path, oauth_consumer_credentials):
    """
    @type db_path: str
    @module_signature: (name, features, feature_types)
    """
    super(Tweet, self).__init__(db_path, module_signature)

    self._oauth_consumer = oauth_consumer_credentials
    key, secret = self._oauth_consumer

    if not os.path.exists(oauth_filename):
      oauth_dance(u'Chitsapp', key, secret, oauth_filename)

    self._setup_twitter_stream()
    self._setup_twitter()
Ejemplo n.º 32
0
    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))
Ejemplo n.º 33
0
    def __init__(self, db_path, oauth_consumer_credentials):
        """
    @type db_path: str
    @module_signature: (name, features, feature_types)
    """
        super(Tweet, self).__init__(db_path, module_signature)

        self._oauth_consumer = oauth_consumer_credentials
        key, secret = self._oauth_consumer

        if not os.path.exists(oauth_filename):
            oauth_dance(u'Chitsapp', key, secret, oauth_filename)

        self._setup_twitter_stream()
        self._setup_twitter()
Ejemplo n.º 34
0
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)
Ejemplo n.º 35
0
def authorize_twitter():
  """
  Initiates authorizing via twitter apps site.
  Outputs authorization credentials to file 'credentials.txt':
    - app_name
    - consumer_key
    - consumer_secret
    - access_key
    - access-secret
  """
  app_name = "PennCryptoTrader"
  consumer_key = "QCBsCvQCaGnaLcs3l0WbmZpmE"
  consumer_secret = "OaBuumdCkfheLC2PfffpLtXZiRnMWYW3nAZ68p4dijDMao1HLK"

  print("[*] Authorizing application...")
  access_key, access_secret = twitter.oauth_dance(app_name, consumer_key, consumer_secret)
  print("[+]\tAuthorized")
  print("[+]\tApplication name: %s" % app_name)
  print("[+]\tconsumer_key: %s" % consumer_key)
  print("[+]\tconsumer_secret: %s" % consumer_secret)
  print("[+]\taccess_key: %s" % access_key)
  print("[+]\taccess_secret: %s" % access_secret)

  f = open('credentials.txt', 'w')
  f.write('app_name:%s\n' % app_name)
  f.write('consumer_key:%s\n' % consumer_key)
  f.write('consumer_secret:%s\n' % consumer_secret)
  f.write('access_key:%s\n' % access_key)
  f.write('access_secret:%s\n' % access_secret)
  f.close()
Ejemplo n.º 36
0
def use_defaults_and_create(CONFIG_FILE):
    """
  This functions set the default options and generates
  a simple configuration file. The default application
  key and secret is not written on the generated config
  file, this forces this function to decode the keys on
  each call to the script.
  """
    config_vars = {'magicword': '#rpitwit', 'AppName': 'RPiTwit'}

    keys = load_config(build_secret(), fromString=True)

    import twitter
    config_vars['oauth_token'],config_vars['oauth_secret'] = \
      twitter.oauth_dance(
        config_vars['AppName'],
        keys['CONSUMER_KEY'],
        keys['CONSUMER_SECRET']
      )

    twitter_handler = twitter.Twitter(auth=twitter.OAuth(
        config_vars['oauth_token'], config_vars['oauth_secret'],
        keys['CONSUMER_KEY'], keys['CONSUMER_SECRET']))

    config_vars['follow'] = find_userids(twitter_handler)

    write_config(config_vars, CONFIG_FILE)

    config_vars = dict(config_vars.items() + keys.items())

    return config_vars
Ejemplo n.º 37
0
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
Ejemplo n.º 38
0
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
Ejemplo n.º 39
0
def oauth_and_get_twitter():
    config_parser = configparser.ConfigParser()
    config_parser.read(CONFIG_FILE)
    if len(config_parser) == 0:
        print("ERROR: no config file loaded")
        exit(1)

    app_name = config_parser.get('Login Parameters', 'app_name')
    api_key = config_parser.get('Login Parameters', 'api_key')
    api_secret = config_parser.get('Login Parameters', 'api_secret')
    oauth_token = config_parser.get('Login Parameters',
                                    'oauth_token',
                                    fallback='')
    oauth_secret = config_parser.get('Login Parameters',
                                     'oauth_secret',
                                     fallback='')

    if oauth_token == '' or oauth_secret == '':
        oauth_token, oauth_secret = twitter.oauth_dance(
            app_name, api_key, api_secret)
        config_parser['Login Parameters']['oauth_token'] = oauth_token
        config_parser['Login Parameters']['oauth_secret'] = oauth_secret
        with open(CONFIG_FILE, 'w') as configfile:
            config_parser.write(configfile)

    t = twitter.Twitter(
        auth=twitter.OAuth(oauth_token, oauth_secret, api_key, api_secret))
    return t
Ejemplo n.º 40
0
    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 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
Ejemplo n.º 42
0
def auth():
    '''
    authonticated the account and return twitter class
    '''
    # read app credentials
    app_creds = open('.app_credentials')
    app_key = app_creds.readline().rstrip()
    app_secret = app_creds.readline().rstrip()

    # read oauth credentials
    oauth_creds = open('.oauth_credentials')
    if not oauth_creds:
        oauth_dance("precure-today-cards", app_key, app_secret,
                    '.oauth_credentials')
    oauth_token = oauth_creds.readline().rstrip()
    oauth_secret = oauth_creds.readline().rstrip()
    return Twython(app_key, app_secret, oauth_token, oauth_secret)
Ejemplo n.º 43
0
    def dance(self):
        " Get OAauth params. "

        oauth_token, oauth_secret = oauth_dance(
            self.config.get('ACCOUNT'), self.config.get('CONSUMER_KEY'), self.config.get('CONSUMER_SECRET'))

        self.app.logger.info("OAUTH_TOKEN: %s", oauth_token)
        self.app.logger.info("OAUTH_SECRET: %s", oauth_secret)
Ejemplo n.º 44
0
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))
Ejemplo n.º 45
0
    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)
Ejemplo n.º 46
0
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)
Ejemplo n.º 47
0
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))
Ejemplo n.º 48
0
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
Ejemplo n.º 49
0
	def setUp(self):
		CONSUMER_KEY    = config.CONSUMER_KEY
		CONSUMER_SECRET = config.CONSUMER_SECRET

		CREDENTIAL_STORAGE = os.path.expanduser('~/.jtwitter')
		if not os.path.exists(CREDENTIAL_STORAGE):
			oauth_dance("JGoodridge's Tweet Generator", CONSUMER_KEY, CONSUMER_SECRET, CREDENTIAL_STORAGE)
			
		OAUTH_TOKEN, OAUTH_SECRET = read_token_file(CREDENTIAL_STORAGE)
		twitter = Twitter(auth=OAuth(OAUTH_TOKEN, OAUTH_SECRET, CONSUMER_KEY, CONSUMER_SECRET))
		timeline = twitter.statuses.user_timeline(screen_name="realDonaldTrump", tweet_mode="extended")


		for (i, t) in enumerate(timeline):
			try:
				tweet = t['retweeted_status']
			except KeyError:
				tweet = t
			self.tweetsOfUser += ' ' + (self.cleanUp(tweet['full_text']))
Ejemplo n.º 50
0
def main(args=sys.argv[1:]):
    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)

    twitter = Twitter(auth=auth, api_version='1.1', domain='api.twitter.com')

    # rate_limit_status(twitter)

    todo_user_list = get_value(db, "TODO_USER_LIST")
    if not todo_user_list:
        todo_user_list = deque(("Stupid_ET", ))
    print "[todo_user_list] %s" % todo_user_list
    start_crawler(twitter, todo_user_list)
Ejemplo n.º 51
0
    def _wizard(self, tokens):
        if not tokens['consumer_key'] or not tokens['consumer_secret']:
            raise InvalidTokens('Tokens are insufficient to run wizard')

        retries = 0
        token, token_secret = None, None
        while not token or not token_secret and retries > 3:
            token, token_secret = twitter.oauth_dance('zizi twitter module', tokens['consumer_key'], tokens['consumer_secret'])
            retries += 1

        tokens['token'] = token
        tokens['token_secret'] = token_secret
Ejemplo n.º 52
0
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
Ejemplo n.º 53
0
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))
Ejemplo n.º 54
0
 def __init__(self):
     secrets = Secrets()
     api_key = secrets.get(self.CONFIG_SECTION, 'api_key')
     api_secret = secrets.get(self.CONFIG_SECTION, 'api_secret')
     oauth_token = secrets.get(self.CONFIG_SECTION, 'oauth_token')
     oauth_secret = secrets.get(self.CONFIG_SECTION, 'oauth_secret')
     if not oauth_token or not oauth_secret:
         oauth_token, oauth_secret = oauth_dance('irregular_stock_bot',
                                                 api_key, api_secret)
     self.twitter = Twitter(auth=OAuth(oauth_token, oauth_secret, api_key,
                                       api_secret),
                            retry=True)
Ejemplo n.º 55
0
def _check_twitter_oauth():
    if not (config.has_option('twitter', 'oauth_token') and
            config.has_option('twitter', 'oauth_secret')):
        oauth_token, oauth_secret = twitter.oauth_dance('releasetool',
                                                        config.get('twitter', 'api_key'),
                                                        config.get('twitter', 'api_secret'))
        _add_tokens_to_config(oauth_token, oauth_secret)
    else:
        oauth_token = config.get('twitter', 'oauth_token')
        oauth_secret = config.get('twitter', 'oauth_secret')

    return oauth_token, oauth_secret
def connect_to_twitter():
    # 'QdrOrGTx0JqAzTSAZkeF8ZCxT',
    # '5TNSrWNfOq2ek55HMAjKbgmd24NSUY8fbWhmZeHNyQ6ELVEl4b',
    # '1606571954-nQrQ4iQaOku7NcABsB44y1bp1ukSkYGumZNMeE8',
    # 'dzMLIjhcnABo3fCJITbyOhoNh84eOM6Kh289bilVxSXx2'

    CONSUMER_KEY = 'QdrOrGTx0JqAzTSAZkeF8ZCxT'
    CONSUMER_SECRET = '5TNSrWNfOq2ek55HMAjKbgmd24NSUY8fbWhmZeHNyQ6ELVEl4b'

    oauth_token, oauth_token_secret = oauth_dance("Test Bot", CONSUMER_KEY, CONSUMER_SECRET)
    t = Twitter(auth=OAuth(oauth_token, oauth_token_secret, CONSUMER_KEY, CONSUMER_SECRET))

    return t
Ejemplo n.º 57
0
    def postTwitter(msg, tweetId, username): 
        MY_TWITTER_CREDS = os.path.expanduser('~/.my_app_credentials')
        if not os.path.exists(MY_TWITTER_CREDS):
            tw.oauth_dance("SkunkWorks140", 
                        app.config['TWITTER_CONSUMER_KEY'], 
                        app.config['TWITTER_CONSUMER_SECRET'],
                        MY_TWITTER_CREDS)

        # authenticate twitter session
        oauth_token, oauth_secret = tw.read_token_file(MY_TWITTER_CREDS) 
        
        twitter = tw.Twitter(auth=tw.OAuth(
        oauth_token, 
        oauth_secret, 
        app.config['TWITTER_CONSUMER_KEY'], 
        app.config['TWITTER_CONSUMER_SECRET']))
        
        msg=cap(msg,140)

        twitter.statuses.update(status="@{} {}".format(username, msg))

        print "@{} {}".format(username, msg)
Ejemplo n.º 58
0
    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))