本文整理汇总了Python中tweepy.API属性的典型用法代码示例。如果您正苦于以下问题:Python tweepy.API属性的具体用法?Python tweepy.API怎么用?Python tweepy.API使用的例子?那么恭喜您, 这里精选的属性代码示例或许可以为您提供帮助。您也可以进一步了解该属性所在类tweepy
的用法示例。
在下文中一共展示了tweepy.API属性的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: import tweepy [as 别名]
# 或者: from tweepy import API [as 别名]
def __init__(self, id, params):
super(Twitter, self).__init__(id, params)
try:
self.consumer_key = params["consumer_key"]
self.consumer_secret = params["consumer_secret"]
self.access_token = params["access_token"]
self.access_token_secret = params["access_token_secret"]
self.recipients = [rec.strip() for rec in params["recipients"].split(",")]
except KeyError as ke:
logging.error("Twitter: Error while trying to initialize notifier, it seems there is a config parameter missing: %s" % ke)
self.corrupted = True
return
try:
auth = tweepy.OAuthHandler(self.consumer_key, self.consumer_secret)
auth.set_access_token(self.access_token, self.access_token_secret)
self.api = tweepy.API(auth)
except Exception as e:
logging.error("Twitter: Error while trying to initialize notifier: %s" % e)
self.corrupted = True
return
logging.info("Twitter: Notifier initialized")
示例2: sendTweet
# 需要导入模块: import tweepy [as 别名]
# 或者: from tweepy import API [as 别名]
def sendTweet(item,color,link, size):
# line 102
auth = tweepy.OAuthHandler(C_KEY, C_SECRET)
auth.set_access_token(A_TOKEN, A_TOKEN_SECRET)
api = tweepy.API(auth)
tweet = item+"\n"
tweet += color+'\n'
tweet += size.title()+'\n'
tweet += link+'\n'
tweet += "Restock!"+'\n'
tweet += str(datetime.utcnow().strftime('%H:%M:%S.%f')[:-3])
try:
api.update_status(tweet)
print(tweet)
except:
print("Error sending tweet!")
示例3: getTwitterConfig
# 需要导入模块: import tweepy [as 别名]
# 或者: from tweepy import API [as 别名]
def getTwitterConfig(api):
# Check for cached configuration, no more than a day old
if os.path.isfile("twitter_config.dat"):
mtime = os.stat("twitter_config.dat").st_mtime
if time.time() - mtime < 24 * 60 * 60:
with open("twitter_config.dat", "r") as f:
return json.load(f)
# Otherwise, query the Twitter API and cache the result
config = api.configuration()
with open("twitter_config.dat", "w") as f:
json.dump(config, f)
return config
# Read our list of feeds from file
示例4: __init__
# 需要导入模块: import tweepy [as 别名]
# 或者: from tweepy import API [as 别名]
def __init__(self, bot):
self.bot = bot
self.twitter_client = None
self.listener = None
if self.bot:
self.bot.socket_manager.add_handler("twitter.follow", self.on_twitter_follow)
self.bot.socket_manager.add_handler("twitter.unfollow", self.on_twitter_unfollow)
if "twitter" not in bot.config:
return
twitter_config = bot.config["twitter"]
self.use_twitter_stream = "streaming" in twitter_config and twitter_config["streaming"] == "1"
try:
self.twitter_auth = tweepy.OAuthHandler(twitter_config["consumer_key"], twitter_config["consumer_secret"])
self.twitter_auth.set_access_token(twitter_config["access_token"], twitter_config["access_token_secret"])
self.twitter_client = tweepy.API(self.twitter_auth)
except:
log.exception("Twitter authentication failed.")
self.twitter_client = None
示例5: image_upload
# 需要导入模块: import tweepy [as 别名]
# 或者: from tweepy import API [as 别名]
def image_upload(self, filename, *args, **kwargs):
""" :reference: https://dev.twitter.com/rest/reference/post/media/upload
:allowed_param:
"""
f = kwargs.pop('file', None)
headers, post_data = API._pack_image(filename, self.max_size_standard, form_field='media', f=f)
kwargs.update({'headers': headers, 'post_data': post_data})
return bind_api(
api=self,
path='/media/upload.json',
method='POST',
payload_type='media',
allowed_param=[],
require_auth=True,
upload_api=True
)(*args, **kwargs)
示例6: cmd_verify
# 需要导入模块: import tweepy [as 别名]
# 或者: from tweepy import API [as 别名]
def cmd_verify(bot, update, args, chat):
if not chat.twitter_request_token:
bot.reply(update, "Use /auth command first")
return
if len(args) < 1:
bot.reply(update, "No verifier code specified")
return
verifier_code = args[0]
auth = OAuthHandler(bot.tw.auth.consumer_key, bot.tw.auth.consumer_secret)
auth.request_token = json.loads(chat.twitter_request_token)
try:
auth.get_access_token(verifier_code)
except TweepError:
bot.reply(update, "Invalid verifier code. Use /auth again")
return
chat.twitter_token = auth.access_token
chat.twitter_secret = auth.access_token_secret
chat.save()
bot.reply(update, "Access token setup complete")
api = tweepy.API(auth)
settings = api.get_settings()
tz_name = settings.get("time_zone", {}).get("tzinfo_name")
cmd_set_timezone(bot, update, [tz_name])
示例7: last_tweet
# 需要导入模块: import tweepy [as 别名]
# 或者: from tweepy import API [as 别名]
def last_tweet(self, ctx):
# Secret twitter API key.
creds = [cred.replace("\n", "") for cred in open(file_twitter_cred, "r")]
# Auth & get.
auth = tweepy.OAuthHandler(creds[0], creds[1])
auth.set_access_token(creds[2], creds[3])
api = tweepy.API(auth)
tryhackme_tweets = api.user_timeline(
screen_name='RealTryHackMe', count=20, include_rts=False)
# Sends first found tweet. (and not reply.)
for tweet in tryhackme_tweets:
if not tweet.in_reply_to_screen_name:
await ctx.send("https://twitter.com/RealTryHackMe/status/" + str(tweet.id))
break
示例8: twitter_url
# 需要导入模块: import tweepy [as 别名]
# 或者: from tweepy import API [as 别名]
def twitter_url(match, conn):
# Find the tweet ID from the URL
tweet_id = match.group(1)
# Get the tweet using the tweepy API
tw_api = container.api
if tw_api is None:
return
try:
tweet = tw_api.get_status(tweet_id, tweet_mode=get_tweet_mode(conn))
except tweepy.TweepError as e:
if e.api_code in IGNORE_ERRORS:
return
raise
user = tweet.user
return format_tweet(tweet, user)
示例9: me
# 需要导入模块: import tweepy [as 别名]
# 或者: from tweepy import API [as 别名]
def me(self):
"""
Returns a dataframe with just one row, which has all of the data avilable about the user tied to the API key.
:return:
"""
data = self.client.me()
# page through it and parse results
ds = [self._flatten_dict(data._json, layers=3, drop_deeper=True)]
# form the dataframe
df = pd.DataFrame(ds)
return df
# #################################################################
# ##### Timeline Methods #####
# #################################################################
示例10: saved_searches
# 需要导入模块: import tweepy [as 别名]
# 或者: from tweepy import API [as 别名]
def saved_searches(self):
"""
Returns saved search attributes for the user tied to the API keys,
as a Pandas DataFrame that contains created_at, id, id_str,
name, position, query as columns
:return:
"""
data = self.client.saved_searches()
ds = []
# loop through SavedSearch objects return from the API
for saved_search in data:
# remove _api attribute
saved_search.__dict__.pop('_api')
# flatten the dictionary attribute of the object
ds.append(self._flatten_dict(saved_search.__dict__, layers=3))
# convert the flattened dictionaries to a dataframe
df = pd.DataFrame(ds)
return df
示例11: exists_friendship
# 需要导入模块: import tweepy [as 别名]
# 或者: from tweepy import API [as 别名]
def exists_friendship(self, source_id=None, source_screen_name=None, target_id=None, target_screen_name=None):
"""
Checks if a friendship exists between two users. Will return True if user_a follows user_b, otherwise False.
:param source_id: Specifies the ID or screen name of the source user.
:param source_screen_name: Specifies the screen name of the source user. Helpful for disambiguating when a valid screen name is also a user ID.
:param target_id: Specifies the ID or screen name of the target user.
:param target_screen_name: Specifies the screen name of the target user. Helpful for disambiguating when a valid screen name is also a user ID.
:return:
"""
# get friendship from the API
data = self.retry_call(
self.client.show_friendship,
5,
source_id=source_id,
source_screen_name=source_screen_name,
target_id=target_id,
target_screen_name=target_screen_name
)
# return value of following attribute for user_a
return data[0].following
示例12: __init__
# 需要导入模块: import tweepy [as 别名]
# 或者: from tweepy import API [as 别名]
def __init__(self):
self.consumer_key = settings.TWITTER_KEY
self.consumer_secret = settings.TWITTER_SECRET
self.token = settings.TWITTER_ACCESS_TOKEN
self.token_secret = settings.TWITTER_TOKEN_SECRET
auth = tweepy.OAuthHandler(self.consumer_key,
self.consumer_secret)
auth.set_access_token(self.token, self.token_secret)
self.api = tweepy.API(auth)
示例13: initialize
# 需要导入模块: import tweepy [as 别名]
# 或者: from tweepy import API [as 别名]
def initialize():
with open('data/config.json') as config_data:
config = json.load(config_data)
auth = tweepy.OAuthHandler(config['consumer_key'], config['consumer_secret'])
auth.set_access_token(config['access_token'], config['access_token_secret'])
api = tweepy.API(auth)
stream = TwitterStreamListener()
twitter_stream = tweepy.Stream(auth = api.auth, listener=stream)
twitter_stream.filter(track=['iphone'], async=True)
示例14: scrape
# 需要导入模块: import tweepy [as 别名]
# 或者: from tweepy import API [as 别名]
def scrape(self, wait_on_rate_limit=True, learn_retweets=False):
auth = self._auth()
api = tweepy.API(auth, wait_on_rate_limit=wait_on_rate_limit)
if self.scraper_status.since_id == 0:
tweets = tweepy.Cursor(api.user_timeline, screen_name=self.screen_name, count=100,
lang="en").items()
else:
tweets = tweepy.Cursor(api.user_timeline, screen_name=self.screen_name, count=100,
lang="en", since_id=self.scraper_status.since_id).items()
for tweet in tweets:
tweet_row = self.session.query(Tweet).filter(Tweet.status_id == tweet.id).first()
if tweet_row is None:
if not tweet.retweeted or (tweet.retweeted and learn_retweets):
tweet_row = Tweet(status_id=tweet.id, user_id=tweet.author.id,
in_reply_to_status_id=tweet.in_reply_to_status_id,
in_reply_to_user_id=tweet.in_reply_to_user_id, retweeted=tweet.retweeted,
timestamp=tweet.created_at, text=tweet.text.encode())
self.session.add(tweet_row)
# Store the highest ID so we can set it to since_id later
if self._latest_tweet_processed_id is None or tweet.id > self._latest_tweet_processed_id:
self._latest_tweet_processed_id = tweet.id
# Normally it would be asinine to commit every insert, but we are rate limited by twitter anyway
self.session.commit()
# Complete scraper progress
self.scraper_status.since_id = self._latest_tweet_processed_id
self.session.commit()
示例15: __init__
# 需要导入模块: import tweepy [as 别名]
# 或者: from tweepy import API [as 别名]
def __init__(self, frontend_worker: 'TwitterWorker', credentials: TwitterApiCredentials,
retweet_replies_to_ids: List[int]):
tweepy.StreamListener.__init__(self)
self._worker = frontend_worker
auth = tweepy.OAuthHandler(credentials.consumer_key, credentials.consumer_secret)
auth.set_access_token(credentials.access_token, credentials.access_token_secret)
self._api = tweepy.API(auth)
self._retweet_replies_to_ids = retweet_replies_to_ids
self._logger = logging.getLogger(self.__class__.__name__)