def oauth_url_dance(consumer_key, consumer_secret, callback_url,
                    oauth_verifier, pre_verify_token_filename,
                    verified_token_filename):
    # Verification happens in two stages...

    # 1) If we haven't done a pre-verification yet... Then we get credentials from Twitter
    # that will be used to sign our redirect to them, find the redirect, and instruct the Javascript
    # that called us to do the redirect.
    if not os.path.exists(CREDS_PRE_VERIFIY):
        twitter = Twitter(auth=OAuth('', '', consumer_key, consumer_secret),
                          format='',
                          api_version=None)
        oauth_token, oauth_token_secret = parse_oauth_tokens(
            twitter.oauth.request_token(oauth_callback=callback_url))
        write_token_file(pre_verify_token_filename, oauth_token,
                         oauth_token_secret)

        oauth_url = 'https://api.twitter.com/oauth/authorize?' + urllib.urlencode(
            {'oauth_token': oauth_token})
        return oauth_url

    # 2) We've done pre-verification, hopefully the user has authed us in Twitter
    # and we've been redirected to. Check we are and ask for the permanent tokens.
    oauth_token, oauth_token_secret = read_token_file(CREDS_PRE_VERIFIY)
    twitter = Twitter(auth=OAuth(oauth_token, oauth_token_secret, consumer_key,
                                 consumer_secret),
                      format='',
                      api_version=None)
    oauth_token, oauth_token_secret = parse_oauth_tokens(
        twitter.oauth.access_token(oauth_verifier=oauth_verifier))
    write_token_file(verified_token_filename, oauth_token, oauth_token_secret)
    return oauth_token, oauth_token_secret
示例#2
0
def get_twitter_tools(oauthfile):
    #--- register oauth tokens -------------------------------------------
    try:
        oauth_token, oauth_token_secret = read_token_file(oauthfile)
    except IOError:
        print 'OAuth file {} not found'.format(oauthfile)
        response = raw_input(
            'Do you want to initiate a new oauth dance (y or n)? ')
        if not (len(response) > 0 and response[0].upper() == 'Y'):
            oauth_token = oauth_token_secret = ''
        else:
            oauth_token, oauth_token_secret = oauth_dance(
                'Brilliant App',
                CONSUMER_KEY,
                CONSUMER_SECRET,
                token_filename=oauthfile)

    #--- t1 = Twitter Search API, t2 = Twitter REST API ------------------
    t1 = Twitter(domain='search.twitter.com')
    t2 = Twitter(auth=OAuth(oauth_token, oauth_token_secret, CONSUMER_KEY,
                            CONSUMER_SECRET),
                 secure=True,
                 api_version='1',
                 domain='api.twitter.com')
    return t1, t2
def run():
    """ Runs the bot it a loop, checking for questions and replying """

    # We use two twitter clients, one to search, another to update. Just
    # easier that way...
    twitter = Twitter(domain="search.twitter.com")
    twitter.uriparts = ()

    last_id_replied = ""

    # Fetch the last message replied to from disk to
    # ensure we don't answer the same question twice.
    try:
        with file(LAST_ID_FILE, "r") as content:
            last_id_replied = content.read()
    except IOError as ex:
        print(LAST_ID_FILE + " not found")

    poster = Twitter(
        auth=OAuth(ACCESS_TOKEN, ACCESS_TOKEN_SECRET, CONSUMER_KEY, CONSUMER_SECRET),
        secure=True,
        api_version="1",
        domain="api.twitter.com",
    )

    while True:
        results = twitter.search(q=TWITTER_USER, since_id=last_id_replied)["results"]

        for result in results:
            last_id_replied = str(result["id"])
            question = result["text"]

            # Only answer tweets with username at the beginning
            if REG_USER_BEGINNING.match(question) is None:
                continue

            # Remove our twitter name from the question.
            question = REG_USER_BEGINNING.sub("", question)
            asker = result["from_user"]
            print("<- {0} (@{1} {2})".format(question, asker, last_id_replied))

            # Get the answer from the bot
            bot_response = decisiverobot.snarkyanswer(question)

            # Add the twitter @address of the asker
            msg = "@{0} {1}".format(asker, bot_response)
            print("-> " + msg)

            # post reply to twitter
            poster.statuses.update(status=msg, in_reply_to_status_id=last_id_replied)

            # Write the last message replied to to disk
            try:
                with file(LAST_ID_FILE, "w") as writer:
                    writer.write(last_id_replied)
            except IOError as ex:
                print(ex)

        time.sleep(SLEEP_INTERVAL)
示例#4
0
    def postTweet(self):

        """Simple method to post a tweet"""

        oauth_token, oauth_secret = read_token_file(self.MY_TWITTER_CREDS)

        try:
            if self.check_graphical.checkState() == 2:
                t_up = Twitter(domain='upload.twitter.com',
                               auth=OAuth(oauth_token, oauth_secret,
                                          self.CONSUMER_KEY,
                                          self.CONSUMER_SECRET))

                with open(self.DATA_PATH + "/graphical_abstracts/{}".format(self.graphical), "rb") as image:
                    imagedata = image.read()

                id_img = t_up.media.upload(media=imagedata)["media_id_string"]
            else:
                self.l.debug("No image, check box not checked")
                id_img = None

        except AttributeError:
            self.l.debug("No image, no check box at all")
            id_img = None

        twitter = Twitter(auth=OAuth(oauth_token, oauth_secret,
                                     self.CONSUMER_KEY, self.CONSUMER_SECRET))

        text = self.text_tweet.toPlainText() + " #ChemBrows"

        if id_img is None:
            try:
                twitter.statuses.update(status=text)
            except Exception as e:
                QtWidgets.QMessageBox.critical(self, "Twitter error", "ChemBrows could not tweet that.\nYour tweet is probably too long: {} chara.".format(len(text)),
                                           QtWidgets.QMessageBox.Ok, defaultButton=QtWidgets.QMessageBox.Ok)
                self.l.error('postTweet: {}'.format(e), exc_info=True)
        else:
            try:
                twitter.statuses.update(status=text, media_ids=id_img)
            except Exception as e:
                QtWidgets.QMessageBox.critical(self, "Twitter error", "ChemBrows could not tweet that.\nYour tweet is probably too long: {} chara.".format(len(text)),
                                           QtWidgets.QMessageBox.Ok, defaultButton=QtWidgets.QMessageBox.Ok)
                self.l.error("postTweet: {}".format(e), exc_info=True)

        self.close()
示例#5
0
def twitter_global_status(content, live=False):
    """
    Twitter content via Civicbooms global feed
    
    In the future should maybe be linked to the Civicboom user, and all users could have twitter keys stored
    """
    #if isinstance(content, Content):
    #    content = content.to_dict('full')
    #content_dict = aggregation_dict(content, safe_strings=True)

    if live:
        link = tiny_url(content.__link__())
    else:
        link = 'http://tinyurl.com/xxxxxxx'

    title = strip_html_tags(content.title)
    content_preview = strip_html_tags(content.content)

    # Create Twitter message with tiny URL
    if len(title) > 70:
        title = truncate(title, length=70)
        content_preview = truncate(content_preview, length=30)
    else:
        content_preview = truncate(content_preview, length=100 - len(title))

    twitter_post = {}
    twitter_post['status'] = "%s: %s (%s)" % (title, content_preview, link)

    # Add location if avalable
    if content.location:
        twitter_post['lat'] = content.location.coords(Session)[1]
        twitter_post['long'] = content.location.coords(Session)[0]
        twitter_post['display_coordinates'] = True

    # Optional ideas
    # t['in_reply_to_status_id '] # If this is a reply to another tweet (could be good in the future if we can store master tweets)
    # t['trim_user'] = False? default?
    # t['place_id']  = "" #need reverse Geocode using the twitter api call geo/reverse_geocode
    # t['include_entities'] = True
    if live:

        twitter_post['status'] = twitter_post['status'].encode(
            'utf8', 'replace')
        t = Twitter(
            auth=OAuth(
                twitter_auth['oauth_token'],
                twitter_auth['oauth_token_secret'],
                twitter_auth['consumer_key'],
                twitter_auth['consumer_secret'],
            ),
            secure=True,
            api_version='1',
            domain='api.twitter.com',
        )
        t.statuses.update(**twitter_post)

    else:
        log.info('twitter_global aggregation disabled: \n%s' % twitter_post)
示例#6
0
def twitter_authorize():
    twitter = Twitter(
        auth=OAuth(session['oauth_token'], session['oauth_token_secret'],
                   app.config['TWITTER_CONSUMER_KEY'],
                   app.config['TWITTER_CONSUMER_SECRET']
                   ),
        format='', api_version=None)
    oauth_token, oauth_token_secret = parse_oauth_tokens(
        twitter.oauth.access_token(
            oauth_verifier=request.args.get('oauth_verifier'))
    )
    if oauth_token and oauth_token_secret:
        t = Twitter(
            auth=OAuth(oauth_token,
                       oauth_token_secret,
                       app.config['TWITTER_CONSUMER_KEY'],
                       app.config['TWITTER_CONSUMER_SECRET'])
        )
        user_info = t.account.settings()
        user = TwitterAccount.query\
            .filter_by(username=user_info['screen_name'])\
            .first()
        if user:
            user.oauth_token = oauth_token
            user.oauth_secret = oauth_token_secret
            db.session.commit()
            return '@' + user_info['screen_name'] + ' was updated.'
        else:
            new_user = TwitterAccount(
                username=user_info['screen_name'],
                oauth_token=oauth_token,
                oauth_secret=oauth_token_secret
            )
            db.session.add(new_user)
            db.session.commit()
            return '@' + user_info['screen_name'] + ' was added.'
    else:
        return 'Twitter Account was not added.'
示例#7
0
def twitter_login():
    twitter = Twitter(
        auth=OAuth('', '',
                   app.config['TWITTER_CONSUMER_KEY'],
                   app.config['TWITTER_CONSUMER_SECRET']
                   ),
        format='', api_version=None)
    session['oauth_token'], session['oauth_token_secret'] = parse_oauth_tokens(
        twitter.oauth.request_token(
            oauth_callback=app.config['TWITTER_CALLBACK'])
    )
    oauth_url = ('https://api.twitter.com/oauth/authorize?oauth_token=' +
                 session['oauth_token'])
    return '<a href="' + oauth_url + '">Login with Twitter</a>'
示例#8
0
def get_twitter(need_auth=False):
    if need_auth:
        oauth_token, oauth_token_secret = read_token_file(OAUTH_FILENAME)
        auth = OAuth(oauth_token, oauth_token_secret, CONSUMER_KEY,
                     CONSUMER_SECRET)
    else:
        auth = None

    twitter = Twitter(auth=auth,
                      secure=True,
                      api_version='1',
                      domain='api.twitter.com')

    return twitter
示例#9
0
 def api(self):
     auth = OAuth(token=self.oauth_token,
                  token_secret=self.oauth_token_secret,
                  consumer_key=self.config['consumer_key'],
                  consumer_secret=self.config['consumer_secret'])
     kwargs = {'auth': auth}
     try:
         kwargs['domain'] = self.config['host']
     except KeyError:
         pass
     try:
         kwargs['secure'] = asbool(self.config['secure'])
     except KeyError:
         pass
     return Twitter(**kwargs)
示例#10
0
 def __init__(self):
     self.stream = TwitterStream(
         auth=OAuth(ACCESS_KEY,
                    ACCESS_SECRET,
                    CONSUMER_KEY,
                    CONSUMER_SECRET),
         api_version='1.1')
     self.twitter = Twitter(
         auth=OAuth(ACCESS_KEY,
                    ACCESS_SECRET,
                    CONSUMER_KEY,
                    CONSUMER_SECRET),
         api_version='1.1')
     self.tmblr = tumblpy.Tumblpy(app_key=TUMBLR_KEY,
                                  app_secret=TUMBLR_SECRET,
                                  oauth_token=TOKEN_KEY,
                                  oauth_token_secret=TOKEN_SECRET
                                  )
示例#11
0
 def __init__(self):
     self.stream = TwitterStream(
         auth=OAuth(ACCESS_KEY,
                    ACCESS_SECRET,
                    CONSUMER_KEY,
                    CONSUMER_SECRET),
         api_version='1.1')
     self.twitter = Twitter(
         auth=OAuth(ACCESS_KEY,
                    ACCESS_SECRET,
                    CONSUMER_KEY,
                    CONSUMER_SECRET),
         api_version='1.1')
     self.tmblr = tumblpy.Tumblpy(app_key=TUMBLR_KEY,
                                  app_secret=TUMBLR_SECRET,
                                  oauth_token=TOKEN_KEY,
                                  oauth_token_secret=TOKEN_SECRET
                                  )
示例#12
0
import eliza


CONSUMER_KEY='uS6hO2sV6tDKIOeVjhnFnQ'
CONSUMER_SECRET='MEYTOS97VvlHX7K1rwHPEqVpTSqZ71HtvoK4sVuYk'

# The very first arg, if present, is the last id replied to.

if __name__ == '__main__':
    oauth_filename = os.environ.get('HOME', '') + os.sep + '.twitter_oauth'
    oauth_token, oauth_token_secret = read_token_file(oauth_filename)

    # We use two twitter clients, one to search, another to update. Just
    # easier that way...
    twitter = Twitter(domain='search.twitter.com')
    twitter.uriparts=()

    last_id_replied = ''

    print '###### args = ', sys.argv

    if len(sys.argv) > 1:
        last_id_replied = sys.argv[1]

    last_id_file = 'last_id_replied'
    if (os.path.exists(last_id_file)):
        last_id_replied = int(open(last_id_file).read())
        print 'Using last id from file ', last_id_replied

    doctor = eliza.eliza()
示例#13
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)
        auths = get_auths_data()
        random_index = random.randint(0, len(auths) - 1)
        print('Using the number %d oauth user' % random_index)
        auth = OAuth(auths[random_index][0], auths[random_index][1],
                     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

    # 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
        user_id = twitter.users.lookup(screen_name=user)[0]['id']
        # print('%d\n' % user_id)
        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, user_id)
        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)))
示例#14
0
import eliza


CONSUMER_KEY='uS6hO2sV6tDKIOeVjhnFnQ'
CONSUMER_SECRET='MEYTOS97VvlHX7K1rwHPEqVpTSqZ71HtvoK4sVuYk'

# The very first arg, if present, is the last id replied to.

if __name__ == '__main__':
    oauth_filename = os.environ.get('HOME', '') + os.sep + '.twitter_oauth'
    oauth_token, oauth_token_secret = read_token_file(oauth_filename)

    # We use two twitter clients, one to search, another to update. Just
    # easier that way...
    twitter = Twitter(domain='search.twitter.com')
    twitter.uriparts=()

    last_id_replied = ''

    print '###### args = ', sys.argv

    if len(sys.argv) > 1:
        last_id_replied = sys.argv[1]

    doctor = eliza.eliza()

    poster = Twitter(
        auth=OAuth(
            oauth_token, oauth_token_secret, CONSUMER_KEY, CONSUMER_SECRET),
        secure=True,
示例#15
0
	except IOError:
		print "[!] ERROR could not open", filename


#These are the keys from the twitter tools for python library.
CONSUMER_KEY = 'uS6hO2sV6tDKIOeVjhnFnQ'
CONSUMER_SECRET = 'MEYTOS97VvlHX7K1rwHPEqVpTSqZ71HtvoK4sVuYk'

#make sure you authenticate using the commandline tool. This will create a file called .twitter_oauth in your ~

if __name__ == "__main__":
	oauth_file = os.environ.get("HOME",'')+os.sep+'.twitter_oauth'
	oa_token , oa_token_secret = read_token_file(oauth_file)

	#twitter client to search
	sbird = Twitter(domain='search.twitter.com')
	#make sure this guy is a tuple
	sbird.uriparts =()


	#anyone talking to us?
	last_id_replied = ''

	#we serialize into a file in ~/.twitter_last_reply. check if this file is present and read value.
	last_file = os.environ.get("HOME",'')+os.sep+'.twitter_last_reply'
	if os.path.exists(last_file):
		try:
			id_file=file(last_file , 'r')
			id = id_file.readline()
			last_id_replied = id.strip()
			print "[+] Read last_reply_id", last_id_replied
示例#16
0
def wanted_generator(settings: 'Settings', attrs: QuerySet):
    own_settings = settings.providers[constants.provider_name]

    def process_wani_tweets(current_tweets: list[dict[str, Any]]):
        publisher = 'wanimagazine'

        yield ('Parsing of {} tweets starting...'.format(len(current_tweets)))

        for tweet in current_tweets:

            cover_url = None
            if 'media' in tweet['entities']:
                for media in tweet['entities']['media']:
                    cover_url = media['media_url']

            tweet_obj, tweet_created = TweetPost.objects.get_or_create(
                tweet_id=tweet['id'],
                defaults={
                    'text':
                    tweet['text'],
                    'user':
                    publisher,
                    'posted_date':
                    datetime.strptime(tweet['created_at'],
                                      "%a %b %d %H:%M:%S %z %Y"),
                    'media_url':
                    cover_url
                })

            if not tweet_created:
                continue

            yield from utilities.match_tweet_with_wanted_galleries(
                tweet_obj, settings, own_settings)

    if not all([getattr(own_settings, x) for x in CREDENTIALS]):
        logger.error(
            'Cannot work with Twitter unless all credentials are set.')
        return

    t = Twitter(auth=OAuth(
        own_settings.token,
        own_settings.token_secret,
        own_settings.consumer_key,
        own_settings.consumer_secret,
    ))
    tweet_posts = TweetPost.objects.all()
    if tweet_posts:
        max_id = tweet_posts.aggregate(Max('tweet_id'))['tweet_id__max']
        while True:
            logger.info("Fetching since tweet id: {}".format(max_id))
            tweets = t.statuses.user_timeline(screen_name='wanimagazine',
                                              include_rts=False,
                                              exclude_replies=True,
                                              trim_user=True,
                                              count=200,
                                              since_id=max_id)
            if not tweets:
                logger.info("No more tweets to fetch, ending")
                break
            new_max_id = max(tweets, key=lambda x: x['id'])['id']
            for message in process_wani_tweets(tweets):
                logger.info(message)
            if new_max_id == max_id:
                logger.info(
                    "No more new tweets fetched, stopping at: {}".format(
                        max_id))
                break
            else:
                max_id = new_max_id
    else:
        min_id = None
        while True:
            if min_id:
                logger.info(
                    "Fetching backwards with max id: {}".format(min_id))
                tweets = t.statuses.user_timeline(screen_name='wanimagazine',
                                                  include_rts=False,
                                                  exclude_replies=True,
                                                  trim_user=True,
                                                  count=200,
                                                  max_id=min_id)
            else:
                logger.info("Starting from newer tweet.")
                tweets = t.statuses.user_timeline(screen_name='wanimagazine',
                                                  include_rts=False,
                                                  exclude_replies=True,
                                                  trim_user=True,
                                                  count=200)
            if not tweets:
                logger.info("No more tweets to fetch, ending")
                break
            new_min_id = min(tweets, key=lambda x: x['id'])['id']
            for message in process_wani_tweets(tweets):
                logger.info(message)
            if new_min_id == min_id:
                logger.info(
                    "No more new tweets fetched, stopping at: {}".format(
                        min_id))
                break
            else:
                min_id = new_min_id
示例#17
0
        # We append part of the ID to avoid duplicates.
        try:
            response_string = random_message()
            msg = '@{0} {1}'.format(user, response_string)
            poster.statuses.update(status=msg,
                                   in_reply_to_status_id=result['id'])
        except (TwitterError, TwitterHTTPError):
            print 'Error connecting to the Twitter API'
            pass

    return last_id


if __name__ == '__main__':
    # Twitter client for searching
    twitter = Twitter(domain='search.twitter.com')
    twitter.uriparts = ()

    # Getting the last id replied (for not answering the same accounts)
    f = open("lastids")
    last_id_replied = f.readline().replace('\n', '')
    f.close()

    # Twitter client for posting
    poster = Twitter(
        auth=OAuth(OAUTH_TOKEN, OAUTH_TOKEN_SECRET,
                   CONSUMER_KEY, CONSUMER_SECRET),
        secure=True,
        api_version='1',
        domain='api.twitter.com'
    )
示例#18
0
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:
            e
示例#19
0
import time
import sys

#import any other natual processing libs

CONSUMER_KEY = 'o2EVUpU1Qn3zBRxyQ7xSxQ'
CONSUMER_SECRET = 'u46YiTorqOCF0qmgpUSdeg2hxH77Cv6epTOdP869xI'

#make sure you authenticate using the commandline tool. This will create a file called .twitter_oauth in your ~

if __name__ == "__main__":
    oauth_file = os.environ.get("HOME", '') + os.sep + '.twitter_oauth'
    oa_token, oa_token_secret = read_token_file(oauth_file)

    #twitter client to search
    sbird = Twitter(domain='search.twitter.com')
    #make sure this guy is a tuple
    sbird.uriparts = ()

    #anyone talking to us?
    last_id_replied = ''

    #twitter client to post. Posting requires oAuth schutff
    pbird = Twitter(auth=OAuth(oa_token, oa_token_secret, CONSUMER_KEY,
                               CONSUMER_SECRET),
                    secure=True,
                    api_version='1',
                    domain="api.twitter.com")

    #main loop. Just keep searching anyone talking to us
    while True:
示例#20
0
    def openAuthPage(self):

        """Method to open the web page which gives the PIN code for
        authentication. When done, verify the pin code and write the
        keys into a local file. The user won't have to do the dance each
        time he wants to tweet"""

        twitter = Twitter(auth=OAuth('', '', self.CONSUMER_KEY,
                                     self.CONSUMER_SECRET),
                          format='', api_version=None)

        token, token_secret = self.parseOauthTokens(twitter.oauth.request_token(oauth_callback="oob"))

        self.l.debug("Opening authentication URL")

        oauth_url = ('https://api.twitter.com/oauth/authorize?oauth_token=' + token)

        try:
            r = webbrowser.open(oauth_url)

            # Sometimes the last command can print some
            # crap. Wait a bit so it doesn't mess up the next
            # prompt.
            time.sleep(2)

            if not r:
                raise Exception()
        except Exception as e:
            QtWidgets.QMessageBox.critical(self, "Authentication", "ChemBrows could not open a web page.\nVisit {} to get the PIN code".format(oauth_url),
                                           QtWidgets.QMessageBox.Ok,defaultButton=QtWidgets.QMessageBox.Ok)
            self.l.error("Authentication URL not opened")
            self.l.error("openAuthPage: {}".format(e), exc_info=True)
            return False


        pin = QtWidgets.QInputDialog.getText(self, "PIN verification","Enter the PIN to authenticate yourself")

        # If OK wasn't pressed, exit
        if not pin[1]:
            return False

        oauth_verifier = pin[0]
        twitter = Twitter(auth=OAuth(token, token_secret, self.CONSUMER_KEY,
                                     self.CONSUMER_SECRET),
                          format='', api_version=None)

        try:
            oauth_token, oauth_secret = self.parseOauthTokens(twitter.oauth.access_token(oauth_verifier=oauth_verifier))
        except Exception as e:
            QtWidgets.QMessageBox.critical(self, "Authentication", "Impossible to obtain tokens",
                                           QtWidgets.QMessageBox.Ok, defaultButton=QtWidgets.QMessageBox.Ok)
            self.l.error("openAuthPage, no tokens : {}".format(e),
                         exc_info=True)
            return False

        self.l.debug("Writing authentication file")
        write_token_file(self.MY_TWITTER_CREDS, oauth_token, oauth_secret)

        self.twitter = Twitter(auth=OAuth(oauth_token, oauth_secret,
                               self.CONSUMER_KEY, self.CONSUMER_SECRET))

        return True
示例#21
0
def search_client():
    client = Twitter(domain='search.twitter.com')
    client.uriparts = ()
    return client
            yield element
    else:
        for element in iterable:
            k = key(element)
            if k not in seen:
                seen_add(k)
                yield element

if __name__ == "__main__":

    parser = OptionParser()
    parser.add_option("-d", "--database", dest="dbname", help="Name of database to create")
    parser.add_option("-f", "--followers", dest="followers", help="Extra users for whom we should retrieve followers")
    (options, args) = parser.parse_args()

    search = Twitter(domain="search.twitter.com")
    twitter = Twitter()

    conn = httplib.HTTPConnection(dbhost,dbport)

    # Create the DB before continuing
    create_database(conn,options.dbname)

    searchresults = search.search(q=searchquery,rpp=100)
    tweets = searchresults["results"]
    def create_tweet(tweet):
        doc = tweet
        doc['resource'] = 'tweet'
        tmp = create_document(conn,options.dbname,"tweet.%s" % tweet["id"],doc)
        return (tweet["id"],tmp)
    tweetmap = dict(map(create_tweet,tweets))
示例#23
0
def oauth2(keys):
    BEARER_TOKEN = oauth2_dance(keys['ConsumerKey'], keys['ConsumerSecret'])
    return Twitter(auth=OAuth2(keys['AccessToken'], keys['AccessTokenSecret'],
                               BEARER_TOKEN))
示例#24
0
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)
        auths = get_auths_data()
        random_index = random.randint(0, len(auths) - 1)
        err('Using the number %d oauth user' % random_index)
        auth = OAuth(auths[random_index][0], auths[random_index][1], 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 = [], {}
        user_id = twitter.users.lookup(screen_name=user)[0]['id']
        try:
            user_ids = follow(twitter, user, options['followers'])
            users = lookup(twitter, user_ids)
        except KeyboardInterrupt as e:
            err()
            err("Interrupted.")
            raise SystemExit(1)
        print(''.join([
            '%d' % user_id,
            '\t',
            '%d' % len(user_ids)
            ]))

        for uid in user_ids:
            if options['show_id']:
              try:
                print('following' + '\t' + 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)))
示例#25
0
def twitter():
    return Twitter()
示例#26
0
class TwitterHandler(object):
    """
    The TwitterHandler object handles non-stream interactions with twitter.
    This includes retrieving specific tweets, posting tweets, and sending dms.
    It also now includes a basic tumblr posting utility function.
    """

    def __init__(self):
        self.stream = TwitterStream(
            auth=OAuth(ACCESS_KEY,
                       ACCESS_SECRET,
                       CONSUMER_KEY,
                       CONSUMER_SECRET),
            api_version='1.1')
        self.twitter = Twitter(
            auth=OAuth(ACCESS_KEY,
                       ACCESS_SECRET,
                       CONSUMER_KEY,
                       CONSUMER_SECRET),
            api_version='1.1')
        self.tmblr = tumblpy.Tumblpy(app_key=TUMBLR_KEY,
                                     app_secret=TUMBLR_SECRET,
                                     oauth_token=TOKEN_KEY,
                                     oauth_token_secret=TOKEN_SECRET
                                     )

    def stream_iter(self):
        """returns a stream iterator."""
        # this is still here because it is ocassionally used for testing.
        # streaming is now handled by StreamHandler.
        return self.stream.statuses.sample(language='en', stall_warnings='true')

    def fetch_tweet(self, tweet_id):
        """
        attempts to retrieve the specified tweet. returns False on failure.
        """
        try:
            tweet = self.twitter.statuses.show(
                id=str(tweet_id),
                include_entities='false')
            return tweet
        except httplib.IncompleteRead as err:
            # print statements for debugging
            logging.debug(err)
            print(err)
            return False
        except TwitterError as err:
            logging.debug('error fetching tweet %i' % tweet_id)
            try:
                if err.e.code == 404:
                    # we reraise 404s, and return false on other exceptions.
                    # 404 means we should not use this resource any more.
                    raise
            except AttributeError:
                pass
            return False
        except Exception as err:
            print('unhandled exception suppressed in fetch_tweet', err)

    def retweet(self, tweet_id):
        try:
            success = self.twitter.statuses.retweet(id=tweet_id)
        except TwitterError as err:
            logging.debug(err)
            return False
        if success:
            return True
        else:
            return False

    def delete_last_tweet(self):
        try:
            tweet = self.twitter.statuses.user_timeline(count="1")[0]
        except TwitterError as err:
            logging.debug(err)
            return False
        try:
            success = self.twitter.statuses.destroy(id=tweet['id_str'])
        except TwitterError as err:
            print(err)
            return False

        if success:
            return True
        else:
            return False

    def url_for_tweet(self, tweet_id):
        tweet = self.fetch_tweet(tweet_id)
        if tweet:
            username = tweet.get('user').get('screen_name')
            return('https://www.twitter.com/%s/status/%s'
                   % (username, str(tweet_id)))
        return False

    def oembed_for_tweet(self, tweet_id):
        return (self.twitter.statuses.oembed(_id=tweet_id))

    def retweet_hit(self, hit):
        """
        handles retweeting a pair of tweets & various possible failures
        """
        if not self.retweet(hit['tweet_one']['tweet_id']):
            return False
        if not self.retweet(hit['tweet_two']['tweet_id']):
            self.delete_last_tweet()
            return False
        return True

    def tumbl_tweets(self, tweetone, tweettwo):
        """
        posts a pair of tweets to tumblr. for url needs real tweet from twitter
        """
        sn1 = tweetone.get('user').get('screen_name')
        sn2 = tweettwo.get('user').get('screen_name')
        oembed1 = self.oembed_for_tweet(tweetone.get('id_str'))
        oembed2 = self.oembed_for_tweet(tweettwo.get('id_str'))
        post_title = "@%s vs @%s" % (sn1, sn2)
        post_content = '<div class="tweet-pair">%s<br /><br />%s</div>' % (oembed1['html'], oembed2['html'])
        post = self.tmblr.post('post',
                               blog_url=TUMBLR_BLOG_URL,
                               params={'type': 'text',
                                       'title': post_title,
                                       'body': post_content
                                       })
        if not post:
            return False
        return True

    def post_hit(self, hit):
        try:
            t1 = self.fetch_tweet(hit['tweet_one']['tweet_id'])
            t2 = self.fetch_tweet(hit['tweet_two']['tweet_id'])
        except TwitterHTTPError as err:
            print('error posting tweet', err)
            return False
        if not t1 or not t2:
            print('failed to fetch tweets')
            # tweet doesn't exist or is unavailable
            # TODO: better error handling here
            return False
        # retewet hits
        if not self.retweet_hit(hit):
            print('failed to retweet hits')
            return False
        if not self.tumbl_tweets(t1, t2):
            # if a tumblr post fails in a forest and nobody etc
            logging.warning('tumblr failed with hit', hit)
        return True

    # send a DM to a responsible human
    def send_message(self, message):
        if len(message) > 140:
            message = message[:140]

        self.twitter.direct_messages.new(
            user=BOSS_USERNAME,
            text=message
            )

    def handle_directs(self):
        try:
            dms = self.twitter.direct_messages()
            handled_dm = False
            for d in dms:
                sender = d.get('sender_screen_name')
                if sender == BOSS_USERNAME:
                    if not handled_dm:
                        response = self._private_update_function()
                        self.send_message(response)
                        handled_dm = True
                    self.twitter.direct_messages.destroy(id=d.get("id_str"))
        except URLError as err:
            logging.error(str(err))


    # this is a silly way for me to update my ddns server
    def _private_update_function(self):
        response = requests.get(PRIVATE_POST_URL)
        if response.status_code == 200:
            return "update successful"
        return "update returned response %d" % response.status_code
示例#27
0
from twitter.api import Twitter
from twitter import *
import oauth
from secrets import *
import requests
import Algorithmia

client = Algorithmia.client(ALGO_CLIENT)
algo = client.algo('besirkurtulmus/talk2city/0.1.0')

auth = OAuth(consumer_key=C_KEY,
             consumer_secret=C_SECRET,
             token=A_TOKEN,
             token_secret=A_TOKEN_SECRET)

twitter_service = Twitter(auth=auth)
twitter_userstream = TwitterStream(auth=auth, domain='userstream.twitter.com')


def get_target_handle(text):
    print("Sending to Algorithmia")
    input = {"tweet": text}
    return algo.pipe(input).result['twitter_handle'].split("/")[-1]


def limit_to_140(text):
    return text[:140]


def create_reply_text(text, tgt_handle):
    return "Your message will be passed to @%s" % tgt_handle
示例#28
0
    #Configure Logger
    logging.basicConfig(filename='RobBot.log',level=logging.DEBUG,format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')
    
    
    #Load keystore file from the HOME directory
    keystore_file = os.environ.get('HOME', '') + os.sep + '.rob_bot_keystore'
    
    #Read the API keys and other settings into variables
    OAUTH_TOKEN,OAUTH_TOKEN_SECRET,TWITTER_CONSUMER_KEY,TWITTER_CONSUMER_SECRET,AI_SECRET_KEY,AI_API_KEY,TWITTER_NAME,CHAT_BOT_ID,SNOOZE_TIME= file.readlines(open(keystore_file))
    
    if float(SNOOZE_TIME) < float(10):
        e= Exception("The SNOOZE_TIME IN YOUR keystore file has to be at least 10!!!") 
        logging.warning("Error: %s" % e)
        raise e
    
    twitter = Twitter(domain='search.twitter.com')
    twitter.uriparts=()

    last_id_replied = ''

    poster = Twitter(
        auth=OAuth(
            OAUTH_TOKEN.rstrip(), OAUTH_TOKEN_SECRET.rstrip(), TWITTER_CONSUMER_KEY.rstrip(), TWITTER_CONSUMER_SECRET.rstrip()),
        secure=True,
        api_version='1',
        domain='api.twitter.com')

    #Infinite loop to monitor the twitter account
    while True:
        try:
            results = twitter.search(q=TWITTER_NAME, since_id=last_id_replied)['results']
示例#29
0
                    .filter_by(reddit_id=thread.id)\
                    .first()
                if tweet is None:
                    tweet_text = create_tweet(thread.title, thread.permalink)
                    new_tweet = Tweet(reddit_id=thread.id,
                                      date_posted=thread.created_utc,
                                      tweet=tweet_text,
                                      twitter_user_id=user.id,
                                      source_id=source.id)
                    db.session.add(new_tweet)

    next_tweet = Tweet.query\
        .filter_by(twitter_user_id=user.id)\
        .filter_by(tweeted=False)\
        .order_by(Tweet.date_posted.asc())\
        .first()

    if next_tweet is not None:

        try:
            t = Twitter(auth=OAuth(user.oauth_token, user.oauth_secret,
                                   app.config['TWITTER_CONSUMER_KEY'],
                                   app.config['TWITTER_CONSUMER_SECRET']))
            tweet_response = t.statuses.update(status=next_tweet.tweet)
            if tweet_response.headers.get('status') == '200 OK':
                next_tweet.tweeted = True
        except:
            continue

    db.session.commit()