How to use the twitter.OAuth function in twitter

To help you get started, we’ve selected a few twitter examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github nprapps / bestsongs14 / fabfile / data.py View on Github external
@task
def update_featured_social():
    """
    Update featured tweets
    """
    COPY = copytext.Copy(app_config.COPY_PATH)
    secrets = app_config.get_secrets()

    # Twitter
    print 'Fetching tweets...'

    twitter_api = Twitter(
        auth=OAuth(
            secrets['TWITTER_API_OAUTH_TOKEN'],
            secrets['TWITTER_API_OAUTH_SECRET'],
            secrets['TWITTER_API_CONSUMER_KEY'],
            secrets['TWITTER_API_CONSUMER_SECRET']
        )
    )

    tweets = []

    for i in range(1, 4):
        tweet_url = COPY['share']['featured_tweet%i' % i]

        if isinstance(tweet_url, copytext.Error) or unicode(tweet_url).strip() == '':
            continue

        tweet_id = unicode(tweet_url).split('/')[-1]
github wtsnjp / twoot.py / twoot.py View on Github external
def __twitter_questions(self):
        # ask questions
        print('\n#3 Tell me about your Twitter account.')
        print(
            'cf. You can get keys & tokens from https://developer.twitter.com/'
        )

        cs_key = input('API key: ')
        cs_secret = input('API secret key: ')
        ac_tok = input('Access token: ')
        ac_sec = input('Access token secret: ')

        # OAuth
        auth = Twitter.OAuth(ac_tok, ac_sec, cs_key, cs_secret)
        twitter = Twitter.Twitter(auth=auth)

        # set config
        self.config['twitter'] = {
            'consumer_key': cs_key,
            'consumer_secret': cs_secret,
            'access_token': ac_tok,
            'access_token_secret': ac_sec
        }

        return twitter
github heyrict / cindy-realtime / sui_hei / signals.py View on Github external
def add_twitter_on_best_of_month_determined(puzzle_list, useraward):
    try:
        from imaging import render
        auth = OAuth(TOKEN, TOKEN_SECRET, CONSUMER_KEY, CONSUMER_SECRET)
        t = Twitter(auth=auth)
        last_month = timezone.now() - timedelta(days=30)
        status_message = BOM_TWEET_MESSAGE % {
            'user_nickname': useraward.user.nickname,
            'award_name': useraward.award.name,
            'year': last_month.year,
            'month': last_month.month,
            'ranking': ''.join([
                BOM_RANKING_MESSAGE % {
                    'no': i + 1,
                    'user_nickname': puzzle_list[i].user.nickname,
                    'star__sum': puzzle_list[i].star__sum,
                    'star__count': puzzle_list[i].star__count,
                    'title': puzzle_list[i].title,
                    'id': puzzle_list[i].id,
                } for i in range(len(puzzle_list))
github esdalmaijer / markovbot / markovbot / markovbot35.py View on Github external
cons_key		-	String of your Consumer Key (API Key)

		cons_secret		-	String of your Consumer Secret (API Secret)

		access_token	-	String of your Access Token

		access_token_secret
					-	String of your Access Token Secret
		"""
		
		# Raise an Exception if the twitter library wasn't imported
		if not IMPTWITTER:
			self._error(u'twitter_login', u"The 'twitter' library could not be imported. Check whether it is installed correctly.")
		
		# Log in to a Twitter account
		self._oauth = twitter.OAuth(access_token, access_token_secret, \
			cons_key, cons_secret)
		self._t = twitter.Twitter(auth=self._oauth)
		self._ts = twitter.TwitterStream(auth=self._oauth)
		self._loggedin = True
		
		# Get the bot's own user credentials
		self._credentials = self._t.account.verify_credentials()
github hugovk / twitter-tools / best_tweets.py View on Github external
def best_tweets(username):
    global TWITTER
    if TWITTER is None:
        try:
            access_token = data["access_token"]
            access_token_secret = data["access_token_secret"]
        except KeyError:  # Older YAMLs
            access_token = data["oauth_token"]
            access_token_secret = data["oauth_token_secret"]
        TWITTER = twitter.Twitter(
            auth=twitter.OAuth(
                access_token,
                access_token_secret,
                data["consumer_key"],
                data["consumer_secret"],
            )
        )

    today = datetime.date.today()
    first_of_this_month = today.replace(day=1)
    print(first_of_this_month)
    last_of_last_month = first_of_this_month - datetime.timedelta(days=1)
    print(last_of_last_month)

    first_of_last_month = first_of_this_month - relativedelta(months=1)
    print(first_of_last_month)
github amorphic / braubuddy / braubuddy / output / twitterapi.py View on Github external
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))
github emencia / emencia-django-socialaggregator / socialaggregator / plugins / twitter_aggregator.py View on Github external
def init_connector(self):
        auth = OAuth(self.TOKEN, self.SECRET, self.CONSUMER_KEY,
                     self.CONSUMER_SECRET)
        self.connector = Twitter(auth=auth)
github CityOfPhiladelphia / myphillyrising / website / myphillyrising / services.py View on Github external
def get_app_oauth(self):
        return OAuth(
            settings.TWITTER_ACCESS_TOKEN,
            settings.TWITTER_ACCESS_SECRET,
            settings.TWITTER_CONSUMER_KEY,
            settings.TWITTER_CONSUMER_SECRET,
        )
github KonishchevDmitry / social-rss / social_rss / tw.py View on Github external
def get(self):
        """Handles the request."""

        if self.__credentials is None and not self.__get_credentials():
            return

        if config.OFFLINE_DEBUG_MODE or config.WRITE_OFFLINE_DEBUG:
            debug_path = os.path.join(config.OFFLINE_DEBUG_PATH, "twitter")

        if config.OFFLINE_DEBUG_MODE:
            with open(debug_path, "rb") as debug_response:
                timeline = json.loads(debug_response.read().decode())
        else:
            api = Twitter(auth=OAuth(self.__credentials["access_token_key"], self.__credentials["access_token_secret"],
                                     self.__credentials["consumer_key"], self.__credentials["consumer_secret"]))

            timeline = api.statuses.home_timeline(tweet_mode="extended", _timeout=config.API_TIMEOUT)

            if config.WRITE_OFFLINE_DEBUG:
                with open(debug_path, "wb") as debug_response:
                    debug_response.write(json.dumps(timeline).encode())

        try:
            feed = _get_feed(timeline)
        except Exception:
            LOG.exception("Failed to process Twitter timeline:%s", pprint.pformat(timeline))
            raise

        self._write_rss(feed)
github zaltoprofen / YoruProxy / yoru_proxy.py View on Github external
config.read('config.ini')

oauth_conf = dict(config['oauth'])
server_conf = dict(config['server'])
config.pop('oauth')
config.pop('server')

consumer_key = oauth_conf['consumer_key']
consumer_secret = oauth_conf['consumer_secret']

clients = {}
for section in config.sections():
    atoken = config[section]['access_token']
    asecret = config[section]['access_token_secret']
    clients[section.lower()] = \
        Twitter(auth=(OAuth(atoken, asecret, consumer_key, consumer_secret)))

app = Flask(__name__)


def update_with_media(client, status, media):
    twitter = clients[client.lower()]
    return twitter.statuses.update_with_media(**{'status': status,
                                                 'media[]': media})


@app.route('/', methods=['POST'])
def upload():
    msg = request.form['message']
    user = request.form['username']
    img = request.files['media'].stream.read()
    api_response = update_with_media(user, msg, img)