Python twitter.Twitter() Examples

The following are 21 code examples of twitter.Twitter(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module twitter , or try the search function .
Example #1
Source File: main.py    From trump2cash with MIT License 6 votes vote down vote up
def twitter_callback(self, tweet):
        """Analyzes Trump tweets, trades stocks, and tweets about it."""

        # Initialize the Analysis, Logs, Trading, and Twitter instances inside
        # the callback to create separate httplib2 instances per thread.
        analysis = Analysis(logs_to_cloud=LOGS_TO_CLOUD)
        logs = Logs(name="main-callback", to_cloud=LOGS_TO_CLOUD)

        # Analyze the tweet.
        companies = analysis.find_companies(tweet)
        logs.info("Using companies: %s" % companies)
        if not companies:
            return

        # Trade stocks.
        trading = Trading(logs_to_cloud=LOGS_TO_CLOUD)
        trading.make_trades(companies)

        # Tweet about it.
        twitter = Twitter(logs_to_cloud=LOGS_TO_CLOUD)
        twitter.tweet(companies, tweet) 
Example #2
Source File: twitter.py    From ThreatIngestor with GNU General Public License v2.0 6 votes vote down vote up
def __init__(self, api_key, api_secret_key, access_token, access_token_secret, status, **kwargs):
        self.api = twitter.Twitter(auth=twitter.OAuth(access_token, access_token_secret, api_key, api_secret_key))
        self.status = status

        # Validate status, for better error handling.
        if not isinstance(self.status, str):
            raise threatingestor.exceptions.IngestorError(f"Invalid 'status' config: {self.status}")

        super(Plugin, self).__init__(kwargs.get('artifact_types'),
                                     kwargs.get('filter_string'),
                                     kwargs.get('allowed_sources'))
        self.artifact_types = kwargs.get('artifact_types') or [
            threatingestor.artifacts.URL,
            threatingestor.artifacts.Domain,
            threatingestor.artifacts.Hash,
            threatingestor.artifacts.IPAddress,
        ] 
Example #3
Source File: scraper.py    From RTA with Apache License 2.0 6 votes vote down vote up
def run_scrape(self, target):
        """
        Get all possible results for all the defined websites.

        """
        try:
            self.shodan(target)
        except Exception as e:
            # print("Exception occured: \n" + str(e))
            print("\033[91m" + "[+]Skipping Shodan since config file is not updated")
            pass

        try:
            self.twitter()
        except Exception as e:
            print("Exception occured: \n" + str(e))
            print("\033[91m" + "[+]Skipping Twitter since config file is not updated")
            pass

        self.slack.notify_slack(self.message)
        self.github()

        return 
Example #4
Source File: scraper.py    From RTA with Apache License 2.0 5 votes vote down vote up
def twitter(self):
        """
        Keywords based search on twitter and returns the recent results based on the same

        """
        message = ""
        count = self.collection.count()

        twitter = Twitter(auth = OAuth(self.access_key, self.access_secret, self.consumer_key, self.consumer_secret))
        for keyword in self.twitter_keywords:
            query = twitter.search.tweets(q = keyword)
            for result in query['statuses']:
                try:
                    data = {"id": count+1, "source": "twitter", "timestamp": datetime.now()}
                    data['tweet'] = result['text']
                    data['name'] = result["user"]["screen_name"]
                    data['url'] = "https://twitter.com/" + data["name"] + "/status/" + str(result['id'])
                    data['search_string'] = keyword
                    try:
                        dataid = self.collection.insert(data)
                    except DuplicateKeyError as e:
                        continue
                    count += 1

                    # Slack push notification
                    length = 82 - len(data['url'])
                    message += "\nURL: " + data['url'] + " search string: ".rjust(length) + keyword

                except Exception as e:
                    print(e)
                    pass
        
        if message:
            print(self.G + "[+] Twitter" + self.B + message + self.W + "\n")
            self.message += "\n*Twitter*:\n```"
            self.message += message
            self.message += "\n```\n*Github*:\n"

        return 
Example #5
Source File: twitter_tests.py    From trump2cash with MIT License 5 votes vote down vote up
def twitter():
    return Twitter(logs_to_cloud=False) 
Example #6
Source File: analysis.py    From trump2cash with MIT License 5 votes vote down vote up
def __init__(self, logs_to_cloud):
        self.logs = Logs(name="analysis", to_cloud=logs_to_cloud)
        self.language_client = language.LanguageServiceClient()
        self.twitter = Twitter(logs_to_cloud=logs_to_cloud) 
Example #7
Source File: analysis_tests.py    From trump2cash with MIT License 5 votes vote down vote up
def get_tweet(tweet_id):
    """Looks up data for a single tweet."""

    twitter = Twitter(logs_to_cloud=False)
    return twitter.get_tweet(tweet_id) 
Example #8
Source File: main.py    From trump2cash with MIT License 5 votes vote down vote up
def __init__(self):
        self.logs = Logs(name="main", to_cloud=LOGS_TO_CLOUD)
        self.twitter = Twitter(logs_to_cloud=LOGS_TO_CLOUD) 
Example #9
Source File: Basic.py    From twitterDataMining with GNU General Public License v3.0 5 votes vote down vote up
def oauth_login():
        # XXX: Go to https://apps.twitter.com/app/new to create an app and get values
        # for these credentials that you'll need to provide in place of these
        # empty string values that are defined as placeholders.

        CONSUMER_KEY = 'gtebC0hJOZNB0GVxWG2OLi8xh'
        CONSUMER_SECRET = 'pOmlze5jjl2KZjFLiDy2KfW6mRllHVP3sd3PHEXpLeZhPARIcv'
        OAUTH_TOKEN = '4649573330-IEiLE9gFzYEc6FoBqL2zZSyYKBOn86LdkHgtvid'
        OAUTH_TOKEN_SECRET = 'a0yTvCQ612TaMw9vcHaglxUtFWM9TfnwfAS5rFDwhLOUj'

        auth = twitter.oauth.OAuth(OAUTH_TOKEN, OAUTH_TOKEN_SECRET,
                                   CONSUMER_KEY, CONSUMER_SECRET)

        twitter_api = twitter.Twitter(auth=auth)
        return twitter_api 
Example #10
Source File: twitter_user_locations.py    From services-to-wordcloud with MIT License 5 votes vote down vote up
def authenticate(self):
        self.auth = twitter.Twitter(auth=twitter.OAuth(self.access_token, 
                    self.access_secret, self.consumer_key, 
                    self.consumer_secret))
        return bool(isinstance(self.auth, twitter.api.Twitter)) 
Example #11
Source File: twitter_timeline.py    From services-to-wordcloud with MIT License 5 votes vote down vote up
def authenticate(self):
        self.auth = twitter.Twitter(auth=twitter.OAuth(self.access_token, 
                    self.access_secret, self.consumer_key, 
                    self.consumer_secret))
        return bool(isinstance(self.auth, twitter.api.Twitter)) 
Example #12
Source File: api_wrapper.py    From gazouilloire with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, api_keys):
        self.oauth = OAuth(api_keys['OAUTH_TOKEN'], api_keys['OAUTH_SECRET'], api_keys['KEY'], api_keys['SECRET'])
        self.oauth2 = OAuth2(bearer_token=json.loads(Twitter(api_version=None, format="", secure=True, auth=OAuth2(api_keys['KEY'], api_keys['SECRET'])).oauth2.token(grant_type="client_credentials"))['access_token'])
        self.api = {
            'user': Twitter(auth=self.oauth),
            'app': Twitter(auth=self.oauth2)
        }
        self.waits = {}
        self.auth = {} 
Example #13
Source File: get_info_account.py    From Learning-Python-Networking-Second-Edition with MIT License 5 votes vote down vote up
def twitter_connection(file):
	'''Create the object from which the Twitter API will be consumed,
	reading the credentials from a file, defined in path parameter.'''
	(CONSUMER_KEY,
     CONSUMER_SECRET,
     OAUTH_TOKEN,
     OAUTH_TOKEN_SECRET) = open(file, 'r').read().splitlines()
	auth = twitter.oauth.OAuth(OAUTH_TOKEN,
                               OAUTH_TOKEN_SECRET,
                               CONSUMER_KEY,
                               CONSUMER_SECRET)
	return twitter.Twitter(auth=auth) 
Example #14
Source File: twitter_search.py    From Learning-Python-Networking-Second-Edition with MIT License 5 votes vote down vote up
def twitter_connection(file):
	'''Create the object from which the Twitter API will be consumed,
	reading the credentials from a file, defined in path parameter.'''
	(CONSUMER_KEY,
     CONSUMER_SECRET,
     OAUTH_TOKEN,
     OAUTH_TOKEN_SECRET) = open(file, 'r').read().splitlines()
	auth = twitter.oauth.OAuth(OAUTH_TOKEN,
                               OAUTH_TOKEN_SECRET,
                               CONSUMER_KEY,
                               CONSUMER_SECRET)
	return twitter.Twitter(auth=auth) 
Example #15
Source File: afl_stats.py    From afl-utils with Apache License 2.0 5 votes vote down vote up
def main(argv):
    parser = argparse.ArgumentParser(description="Post selected contents of fuzzer_stats to Twitter.",
                                     usage="afl-stats [-h] [-c config] [-d database] [-t]\n")

    parser.add_argument("-c", "--config", dest="config_file",
                        help="afl-stats config file (Default: afl-stats.conf)!", default="afl-stats.conf")
    parser.add_argument("-d", "--database", dest="database_file",
                        help="Dump stats history into database.")
    parser.add_argument('-t', '--twitter', dest='twitter', action='store_const', const=True,
                        help='Post stats to twitter (Default: off).', default=False)
    parser.add_argument('-q', '--quiet', dest='quiet', action='store_const', const=True,
                        help='Suppress any output (Default: off).', default=False)

    args = parser.parse_args(argv[1:])

    if not args.quiet:
        show_info()

    if args.database_file:
        db_file = os.path.abspath(os.path.expanduser(args.database_file))
    else:
        db_file = None

    if db_file:
        lite_db = con_sqlite.sqliteConnector(db_file, verbose=False)
    else:
        lite_db = None

    config_settings = read_config(args.config_file)

    if lite_db:
        dump_stats(config_settings, lite_db)
        lite_db.commit_close()

    if args.twitter:
        twitter_inst = twitter_init(config_settings)
    else:
        twitter_inst = None

    fetch_stats(config_settings, twitter_inst) 
Example #16
Source File: afl_stats.py    From afl-utils with Apache License 2.0 5 votes vote down vote up
def fetch_stats(config_settings, twitter_inst):
    stat_dict = dict()
    for fuzzer in config_settings['fuzz_dirs']:
        stats = load_stats(fuzzer)

        if not stats:
            continue

        sum_stats = summarize_stats(stats)

        try:
            with open('.afl_stats.{}'.format(os.path.basename(fuzzer)), 'r') as f:
                old_stats = json.load(f)
        except FileNotFoundError:
            old_stats = sum_stats.copy()

        # initialize/update stat_dict
        stat_dict[fuzzer] = (sum_stats, old_stats)

        stat_change = diff_stats(sum_stats, old_stats)

        with open('.afl_stats.{}'.format(os.path.basename(fuzzer)), 'w') as f:
            json.dump(sum_stats, f)

        print(prettify_stat(sum_stats, stat_change, True))

        tweet = prettify_stat(sum_stats, stat_change, False)

        l = len(tweet)
        c = clr.LRD if l > 140 else clr.LGN

        if twitter_inst:
            print_ok("Tweeting status (%s%d" % (c, l) + clr.RST + " chars)...")
            try:
                twitter_inst.statuses.update(status=shorten_tweet(tweet))
            except (twitter.TwitterHTTPError, URLError):
                print_warn("Problem connecting to Twitter! Tweet not sent!")
            except Exception as e:
                print_err("Sending tweet failed (Reason: " + clr.GRA + "%s" % e.__cause__ + clr.RST + ")") 
Example #17
Source File: afl_stats.py    From afl-utils with Apache License 2.0 5 votes vote down vote up
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) 
Example #18
Source File: afl_stats.py    From afl-utils with Apache License 2.0 5 votes vote down vote up
def show_info():
    print(clr.CYA + "afl-stats " + clr.BRI + "%s" % afl_utils.__version__ + clr.RST + " by %s" % afl_utils.__author__)
    print("Send stats of afl-fuzz jobs to Twitter.")
    print("") 
Example #19
Source File: twitter.py    From ThreatIngestor with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, name, api_key, api_secret_key, access_token, access_token_secret, defanged_only=True, **kwargs):
        self.name = name
        self.api = twitter.Twitter(auth=twitter.OAuth(access_token, access_token_secret, api_key, api_secret_key))

        # Let the user decide whether to include non-obfuscated URLs or not.
        self.include_nonobfuscated = not defanged_only

        # Support for full tweet
        tweet_param = {'tweet_mode': 'extended'}
        kwargs.update(tweet_param)

        # Forward kwargs.
        # NOTE: No validation is done here, so if the config is wrong, expect bad results.
        self.kwargs = kwargs

        # Decide which endpoint to use based on passed arguments.
        # If slug and owner_screen_name, use List API.
        # If screen_name or user_id, use User Timeline API.
        # If q is set, use Search API.
        # Otherwise, default to mentions API.
        self.endpoint = self.api.statuses.mentions_timeline
        if kwargs.get('slug') and kwargs.get('owner_screen_name'):
            self.endpoint = self.api.lists.statuses
        elif kwargs.get('screen_name') or kwargs.get('user_id'):
            self.endpoint = self.api.statuses.user_timeline
        elif kwargs.get('q'):
            self.endpoint = self.api.search.tweets 
Example #20
Source File: twitter.py    From ThreatIngestor with GNU General Public License v2.0 5 votes vote down vote up
def _tweet(self, status, quote_tweet=None):
        """Send content to Twitter as a status update."""
        try:
            return self.api.statuses.update(status=status,
                                            attachment_url=quote_tweet,
                                            tweet_mode='extended')
        except twitter.api.TwitterHTTPError as e:
            logger.warning(f"Twitter API Error: {e}")
            return None 
Example #21
Source File: twitter.py    From ThreatIngestor with GNU General Public License v2.0 4 votes vote down vote up
def run(self, saved_state):
        # Modify kwargs to insert since_id.
        if saved_state:
            self.kwargs['since_id'] = saved_state

        # Pull new tweets.
        try:
            response = self.endpoint(**self.kwargs)
        except twitter.api.TwitterHTTPError as e:
            # API error; log and return early.
            logger.warning(f"Twitter API Error: {e}")

            return saved_state, []

        # Correctly handle responses from different endpoints.
        try:
            tweet_list = response['statuses']
        except TypeError:
            tweet_list = response

        tweets = [{
            'content': s['full_text'],
            'id': s['id_str'],
            'user': s['user']['screen_name'],
            'entities': s.get('entities', {}),
        } for s in tweet_list]

        artifacts = []
        # Traverse in reverse, old to new.
        tweets.reverse()
        for tweet in tweets:
            # Expand t.co links.
            for url in tweet['entities'].get('urls', []):
                try:
                    tweet['content'] = tweet['content'].replace(url['url'], url['expanded_url'])
                except KeyError:
                    # No url/expanded_url, continue without expanding.
                    pass

            # Process tweet.
            saved_state = tweet['id']
            artifacts += self.process_element(tweet['content'],
                                              TWEET_URL.format(user=tweet['user'], id=tweet['id']),
                                              include_nonobfuscated=self.include_nonobfuscated)

        return saved_state, artifacts