本文整理匯總了Python中twitter.Twitter方法的典型用法代碼示例。如果您正苦於以下問題:Python twitter.Twitter方法的具體用法?Python twitter.Twitter怎麽用?Python twitter.Twitter使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類twitter
的用法示例。
在下文中一共展示了twitter.Twitter方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: __init__
# 需要導入模塊: import twitter [as 別名]
# 或者: from twitter import Twitter [as 別名]
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,
]
示例2: run_scrape
# 需要導入模塊: import twitter [as 別名]
# 或者: from twitter import Twitter [as 別名]
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
示例3: twitter_callback
# 需要導入模塊: import twitter [as 別名]
# 或者: from twitter import Twitter [as 別名]
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)
示例4: _tweet
# 需要導入模塊: import twitter [as 別名]
# 或者: from twitter import Twitter [as 別名]
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
示例5: __init__
# 需要導入模塊: import twitter [as 別名]
# 或者: from twitter import Twitter [as 別名]
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
示例6: show_info
# 需要導入模塊: import twitter [as 別名]
# 或者: from twitter import Twitter [as 別名]
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("")
示例7: twitter_init
# 需要導入模塊: import twitter [as 別名]
# 或者: from twitter import Twitter [as 別名]
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)
示例8: fetch_stats
# 需要導入模塊: import twitter [as 別名]
# 或者: from twitter import Twitter [as 別名]
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 + ")")
示例9: main
# 需要導入模塊: import twitter [as 別名]
# 或者: from twitter import Twitter [as 別名]
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)
示例10: twitter_connection
# 需要導入模塊: import twitter [as 別名]
# 或者: from twitter import Twitter [as 別名]
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)
示例11: twitter
# 需要導入模塊: import twitter [as 別名]
# 或者: from twitter import Twitter [as 別名]
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
示例12: __init__
# 需要導入模塊: import twitter [as 別名]
# 或者: from twitter import Twitter [as 別名]
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 = {}
示例13: authenticate
# 需要導入模塊: import twitter [as 別名]
# 或者: from twitter import Twitter [as 別名]
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))
示例14: oauth_login
# 需要導入模塊: import twitter [as 別名]
# 或者: from twitter import Twitter [as 別名]
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
示例15: __init__
# 需要導入模塊: import twitter [as 別名]
# 或者: from twitter import Twitter [as 別名]
def __init__(self):
self.logs = Logs(name="main", to_cloud=LOGS_TO_CLOUD)
self.twitter = Twitter(logs_to_cloud=LOGS_TO_CLOUD)