本文整理汇总了Python中tweepy.API类的典型用法代码示例。如果您正苦于以下问题:Python API类的具体用法?Python API怎么用?Python API使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了API类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: tweet
def tweet(title, url, location=None, parsed_location=None):
auth = OAuthHandler(app.config['TWITTER_CONSUMER_KEY'], app.config['TWITTER_CONSUMER_SECRET'])
auth.set_access_token(app.config['TWITTER_ACCESS_KEY'], app.config['TWITTER_ACCESS_SECRET'])
api = API(auth)
urllength = 23 # Current Twitter standard for HTTPS (as of Oct 2014)
maxlength = 140 - urllength - 1 # == 116
locationtag = u''
if parsed_location:
locationtags = []
for token in parsed_location.get('tokens', []):
if 'geoname' in token and 'token' in token:
locname = token['token'].strip()
if locname:
locationtags.append(u'#' + locname.title().replace(u' ', ''))
locationtag = u' '.join(locationtags)
if locationtag:
maxlength -= len(locationtag) + 1
if not locationtag and location:
# Make a hashtag from the first word in the location. This catches
# locations like 'Anywhere' which have no geonameid but are still valid
locationtag = u'#' + re.split('\W+', location)[0]
maxlength -= len(locationtag) + 1
if len(title) > maxlength:
text = title[:maxlength-1] + u'…'
else:
text = title[:maxlength]
text = text + ' ' + url # Don't shorten URLs, now that there's t.co
if locationtag:
text = text + ' ' + locationtag
api.update_status(text)
示例2: authenticate
def authenticate(self, access_token_key='', access_token_secret='', consumer_key='', consumer_secret=''):
handler = OAuthHandler(consumer_key, consumer_secret)
handler.set_access_token(access_token_key, access_token_secret)
api = API(handler)
twitter_user = api.verify_credentials()
try:
twitter_id = twitter_user.id
except AttributeError:
user = None
else:
try:
user = User.objects.get(username=twitter_id)
except User.DoesNotExist:
user = User.objects.create_user(twitter_id)
profile = user.get_profile()
profile.access_token_key = handler.access_token.key
profile.access_token_secret = handler.access_token.secret
profile.save()
return user
示例3: testbasicauth
def testbasicauth(self):
auth = BasicAuthHandler(username, password)
# test accessing twitter API
api = API(auth)
s = api.update_status('test %i' % random.randint(1, 1000))
api.destroy_status(s.id)
示例4: get_tweets
def get_tweets(count=5):
try:
consumer_key = environ['TWITTER_CONSUMER_KEY']
access_token = environ['TWITTER_ACCESS_TOKEN']
consumer_secret = environ['TWITTER_CONSUMER_SECRET']
access_secret = environ['TWITTER_ACCESS_SECRET']
except KeyError:
error("No Twitter credentials were found.")
# We don't have login stuff, bail.
return []
auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_secret)
api = API(auth_handler=auth)
try:
statuses = api.user_timeline('pythonglasgow', count=count)
except TweepError:
error("Failed to read timelime.")
return []
tweets = [(status, twitterfy(status.text)) for status in statuses]
return tweets
示例5: unwrapped_callback
def unwrapped_callback(self, resp):
if resp is None:
raise LoginCallbackError(_("You denied the request to login"))
# Try to read more from the user's Twitter profile
auth = TwitterOAuthHandler(self.consumer_key, self.consumer_secret)
if self.access_key is not None and self.access_secret is not None:
auth.set_access_token(self.access_key, self.access_secret)
else:
auth.set_access_token(resp['oauth_token'], resp['oauth_token_secret'])
api = TwitterAPI(auth)
try:
twinfo = api.lookup_users(user_ids=[resp['user_id']])[0]
fullname = twinfo.name
avatar_url = twinfo.profile_image_url_https.replace('_normal.', '_bigger.')
except TweepError:
fullname = None
avatar_url = None
return {'userid': resp['user_id'],
'username': resp['screen_name'],
'fullname': fullname,
'avatar_url': avatar_url,
'oauth_token': resp['oauth_token'],
'oauth_token_secret': resp['oauth_token_secret'],
'oauth_token_type': None, # Twitter doesn't have token types
}
示例6: TwitterPlayer
class TwitterPlayer(player.Player):
def __init__(self, model, code, access_token, access_token_secret, opponent):
player.Player.__init__(self, model, code)
self._opponent = opponent
self._last_id = None
self._auth = OAuthHandler(auth.consumer_key, auth.consumer_secret)
self._auth.set_access_token(access_token, access_token_secret)
self._api = API(self._auth)
self._listener = TwitterListener(self, self._api)
self._stream = Stream(self._auth, self._listener)
@property
def username(self):
return self._auth.get_username()
def allow(self):
print 'This is the opponent\'s turn...'
self._stream.userstream()
def update(self, event):
if event.player == self.code:
return
message = '@%s %s' % (self._opponent, self._model.events[-1][1])
self.tweet(message)
def tweet(self, message):
if self._last_id is None:
self._api.update_status(message)
else:
self._api.update_status(message, self._last_id)
示例7: unwrapped_callback
def unwrapped_callback(self, resp):
if resp is None:
raise LoginCallbackError(_("You denied the request to login"))
# Try to read more from the user's Twitter profile
auth = TwitterOAuthHandler(self.consumer_key, self.consumer_secret)
auth.set_access_token(resp['oauth_token'], resp['oauth_token_secret'])
api = TwitterAPI(auth)
try:
twinfo = api.verify_credentials(include_entities='false', skip_status='true', include_email='true')
fullname = twinfo.name
avatar_url = twinfo.profile_image_url_https.replace('_normal.', '_bigger.')
email = getattr(twinfo, 'email', None)
except TweepError:
fullname = None
avatar_url = None
email = None
return {'email': email,
'userid': resp['user_id'],
'username': resp['screen_name'],
'fullname': fullname,
'avatar_url': avatar_url,
'oauth_token': resp['oauth_token'],
'oauth_token_secret': resp['oauth_token_secret'],
'oauth_token_type': None, # Twitter doesn't have token types
}
示例8: tweet
def tweet(title, url, location=None, parsed_location=None, username=None):
auth = OAuthHandler(app.config["TWITTER_CONSUMER_KEY"], app.config["TWITTER_CONSUMER_SECRET"])
auth.set_access_token(app.config["TWITTER_ACCESS_KEY"], app.config["TWITTER_ACCESS_SECRET"])
api = API(auth)
urllength = 23 # Current Twitter standard for HTTPS (as of Oct 2014)
maxlength = 140 - urllength - 1 # == 116
if username:
maxlength -= len(username) + 2
locationtag = u""
if parsed_location:
locationtags = []
for token in parsed_location.get("tokens", []):
if "geoname" in token and "token" in token:
locname = token["token"].strip()
if locname:
locationtags.append(u"#" + locname.title().replace(u" ", ""))
locationtag = u" ".join(locationtags)
if locationtag:
maxlength -= len(locationtag) + 1
if not locationtag and location:
# Make a hashtag from the first word in the location. This catches
# locations like 'Anywhere' which have no geonameid but are still valid
locationtag = u"#" + re.split("\W+", location)[0]
maxlength -= len(locationtag) + 1
if len(title) > maxlength:
text = title[: maxlength - 1] + u"…"
else:
text = title[:maxlength]
text = text + " " + url # Don't shorten URLs, now that there's t.co
if locationtag:
text = text + " " + locationtag
if username:
text = text + " @" + username
api.update_status(text)
示例9: get
def get(self, request, *args, **kwargs):
"""
The GET method controller for the API endpoint and saves the results
to a CSV file.
Accepts query strings:
- keyword: the keyword that searched for
- count: number of results retrieved (default = 100)
"""
keyword = request.GET.get('keyword')
count = request.GET.get('count', 100)
if not keyword:
return Response(HTTP_400_BAD_REQUEST)
auth = twitter_auth()
api = API(auth, parser=JSONParser())
data = []
results = api.search(q=keyword, count=count)
filename = 'search_{}_{}.csv'.format(
keyword, datetime.now().isoformat()
)
for result in results['statuses']:
data.append({
'user': parse_tweet(result['user']['name']),
'tweet': parse_tweet(result['text'])
})
save_to_csv(filename, data)
response_text = 'Saved {} objects.'.format(
results['search_metadata']['count']
)
return Response(response_text)
示例10: unwrapped_callback
def unwrapped_callback(self, resp):
if resp is None:
raise LoginCallbackError(_("You denied the request to login"))
# Try to read more from the user's Twitter profile
auth = TwitterOAuthHandler(self.consumer_key, self.consumer_secret)
if self.access_key is not None and self.access_secret is not None:
auth.set_access_token(self.access_key, self.access_secret)
else:
auth.set_access_token(resp["oauth_token"], resp["oauth_token_secret"])
api = TwitterAPI(auth)
try:
twinfo = api.lookup_users(user_ids=[resp["user_id"]])[0]
fullname = twinfo.name
avatar_url = twinfo.profile_image_url_https.replace("_normal.", "_bigger.")
except TweepError:
fullname = None
avatar_url = None
return {
"userid": resp["user_id"],
"username": resp["screen_name"],
"fullname": fullname,
"avatar_url": avatar_url,
"oauth_token": resp["oauth_token"],
"oauth_token_secret": resp["oauth_token_secret"],
"oauth_token_type": None, # Twitter doesn't have token types
}
示例11: __init__
def __init__(self, term='', oauthfile=''):
threading.Thread.__init__(self)
self.searchterm = term
self.name = term
self.consume = True
listener = MongoDBListener()
try:
oauth = json.loads(open(oauthfile, 'r').read())
if 'consumer_key' in oauth:
auth = OAuthHandler(oauth['consumer_key'], oauth['consumer_secret'])
auth.set_access_token(oauth['access_token'], oauth['access_token_secret'])
api = API(auth)
if not api.verify_credentials():
raise Exception("Invalid credentials")
else:
auth = BasicAuthHandler(oauth['username'], oauth['password'])
except:
print "Error logging to Twitter"
raise
self.stream = Stream(auth, listener, timeout=60)
示例12: FaveRetweeter
class FaveRetweeter(object):
def __init__(self, consumer_key, consumer_secret, access_token, access_token_secret):
self.consumer_key = consumer_key
self.consumer_secret = consumer_secret
self.access_token = access_token
self.access_token_secret = access_token_secret
self._authorize()
def _authorize(self):
oauth_handler = OAuthHandler(self.consumer_key, self.consumer_secret)
oauth_handler.set_access_token(self.access_token, self.access_token_secret)
self.tweepy = API(oauth_handler)
def retweet_fave(self):
me = self.tweepy.me()
favorite_count = me.favourites_count
page = randrange(favorite_count)
favorites = self.tweepy.favorites(count=1, page=page)
favorite = favorites[0]
_retweet(favorite, me)
示例13: get_tweets
def get_tweets(tweeter_id, from_id = None):
#Setup
#l = StdOutListener()
auth = OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = API(auth)
#Get tweets (status) from Twitter A
if from_id == None:
status = api.user_timeline(user_id = tweeter_id, count=amont_of_tweets)
else:
status = api.user_timeline(user_id = tweeter_id, count=amont_of_tweets, max_id = from_id)
status.pop(0) #Remove duplicate first tweet, max_id not included.
tweetlist = []
last_id = 0
#print("Cleaning tweets from :", status.user.screen_name, "id: ", tweeter_id)
for items in status:
tweet = {}
tweet["id"] = items.id
tweet["user_id"] = tweeter_id
tweet["nickname"] = items.user.screen_name
tweet["realname"] = items.user.name
tweet["date"] = datetime.strptime(str(items.created_at), "%Y-%m-%d %H:%M:%S")
tweet["text"] = items.text
tweetlist.append(tweet)
last_id = items.id
print("Last ID: ", last_id, "\n")
return tweetlist, last_id
示例14: FeedTwitter
def FeedTwitter():
auth = OAuthHandler(CONSUMER_KEY_TWITTER, CONSUMER_SECRET_TWITTER)
auth.set_access_token(ACCESS_TOKEN_TWITTER, ACCESS_TOKEN_SECRET_TWITTER)
api = API(auth)
feed = api.user_timeline(screen_name=CONST_USER_TWITTER, count=COUNT_NUMBER_POST, page=1, include_rts=True)
tweets = []
for t in feed:
if t.in_reply_to_status_id == None:
try:
tweet = {"text": t.text, "text_encoded": t.text, "type": "tweet", "created_time": t.created_at,
"link":"https://twitter.com/"+CONST_USER_LINK_TWITTER+"/status/" + str(t.id),
"link_encoded":urllib.quote_plus("https://twitter.com/"+CONST_USER_LINK_TWITTER+"/status/" + str(t.id)),
"user": {"name": t.user.name, "screen_name": "@" + t.user.screen_name,"profile_image":t.user.profile_image_url}}
if "media" in t.entities:
if t.entities['media'][0]['type'] == 'photo':
tweet["image"] = t.entities['media'][0]['media_url']
else:
pass
#print t.entities['media'][0]['type']
else:
pass
#tweet["image"] = get_randon_image()
tweets.append(tweet)
except Exception, e:
#print(str(e))
pass
示例15: StreamConsumerThreadClass
class StreamConsumerThreadClass(threading.Thread):
def __init__(self, term="", oauthfile="", follow=False, user=False, track=False):
threading.Thread.__init__(self)
self.searchterm = term
self.name = term
self.consume = True
self.follow = follow
self.user = user
self.track = track
listener = MongoDBListener()
try:
oauth = json.loads(open(oauthfile, "r").read())
if "consumer_key" in oauth:
auth = OAuthHandler(oauth["consumer_key"], oauth["consumer_secret"])
auth.set_access_token(oauth["access_token"], oauth["access_token_secret"])
self.api = API(auth)
if not self.api.verify_credentials():
raise Exception("Invalid credentials")
self.stream = Stream(auth, listener, timeout=60)
except:
print "Error logging to Twitter"
raise
def stop_consume(self):
self.stream.disconnect()
def run(self):
now = datetime.datetime.now()
if self.user:
print "Twitter Stream of the OAuth user: started at: %s" % (now)
else:
print "Twitter Stream with terms: %s started at: %s" % (self.getName(), now)
connected = False
while True:
try:
if not connected:
connected = True
if self.user:
self.stream.userstream(_with="followings")
elif self.follow:
user_ids = []
for user in self.api.lookup_users([], self.searchterm.split(","), False):
user_ids.append(user.id)
self.stream.filter(follow=[",".join("{0}".format(n) for n in user_ids)])
elif self.track:
self.stream.filter(track=[self.searchterm])
except SSLError, sse:
print sse
connected = False
except Exception, e:
print "Stream error"
raise e