本文整理汇总了Python中twython.Twython.lookup_user方法的典型用法代码示例。如果您正苦于以下问题:Python Twython.lookup_user方法的具体用法?Python Twython.lookup_user怎么用?Python Twython.lookup_user使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类twython.Twython
的用法示例。
在下文中一共展示了Twython.lookup_user方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: get_user_timeline
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import lookup_user [as 别名]
def get_user_timeline(screen_name, count=200):
"""Return list of most recent tweets posted by screen_name."""
# ensure count is valid
if count < 1 or count > 200:
raise RuntimeError("invalid count")
# ensure environment variables are set
if not os.environ.get("API_KEY"):
raise RuntimeError("API_KEY not set")
if not os.environ.get("API_SECRET"):
raise RuntimeError("API_SECRET not set")
# get screen_name's (or @screen_name's) most recent tweets
# https://dev.twitter.com/rest/reference/get/users/lookup
# https://dev.twitter.com/rest/reference/get/statuses/user_timeline
# https://github.com/ryanmcgrath/twython/blob/master/twython/endpoints.py
try:
twitter = Twython(os.environ.get("API_KEY"), os.environ.get("API_SECRET"))
user = twitter.lookup_user(screen_name=screen_name.lstrip("@"))
if user[0]["protected"]:
return None
tweets = twitter.get_user_timeline(screen_name=screen_name, count=count)
return [html.unescape(tweet["text"].replace("\n", " ")) for tweet in tweets]
except TwythonAuthError:
raise RuntimeError("invalid API_KEY and/or API_SECRET") from None
except TwythonRateLimitError:
raise RuntimeError("you've hit a rate limit") from None
except TwythonError:
return None
示例2: getDescriptions
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import lookup_user [as 别名]
def getDescriptions(credentials_list, users_data, directory):
if len(users_data) is 0:
print('Complete')
return
for credential in credentials_list:
users = users_data[0:100]
credentials = Twython(app_key=credential[0],
app_secret=credential[1],
oauth_token=credential[2],
oauth_token_secret=credential[3], oauth_version=1)
data = credentials.lookup_user(screen_name = users)
for dat in data:
profile = dat
handle = str(profile['id'])
time_zone = str(profile['time_zone'])
screen_name = profile['screen_name']
#utc_offset = profile['utc_offset']
description = profile['description'].replace("\t", " ")
with codecs.open(directory[:-4] + "_IDs.csv", 'a', encoding='utf-8') as out:
out.write(u''+ screen_name + '\t' + handle +'\n')
users_data = users_data[101:]
getDescriptions(credentials_list, users_data, directory)
示例3: get_usernames
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import lookup_user [as 别名]
def get_usernames(users, waiting):
twitter = Twython(APP_KEY, access_token=ACCESS_TOKEN)
screen_names = []
print "Finding screen names of users..."
for i in tqdm(range((len(users) - 1) / 100 + 1)):
while True:
try:
time.sleep(waiting)
# look up up to 100 users in one request (don't hit that rate limit!)
looking_up = ",".join(users[i * 100 : min((i+1) * 100, len(users))])
result = twitter.lookup_user(user_id=looking_up)
break
except TwythonAuthError as e:
print "TwythonAuthError..."
continue
except TwythonRateLimitError as e:
print "TwythonRateLimitError... Waiting for 3 minutes (may take multiple waits)"
for timer in tqdm(range(15*60)):
time.sleep(1)
twitter = Twython(APP_KEY, access_token=ACCESS_TOKEN)
continue
except TwythonError as e:
print "TwythonError: " + str(e.error_code) + "..."
continue
screen_names.extend(map(lambda x: x['screen_name'], result))
return screen_names
示例4: get_userids
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import lookup_user [as 别名]
def get_userids(cred,usernames):
print "usernames" + str(usernames)
batches = split_list_by(usernames, MAX_TERM_ALLOWED)
userids = []
notfound = []
for batch in batches:
#url = URL+','.join(batch)
#print url
try:
#f = urllib2.urlopen(url)
#j = json.loads(f.read())
twitter = Twython(cred['consumer_key'], cred['consumer_secret'],
cred['access_token_key'], cred['access_token_secret'])
j = twitter.lookup_user(screen_name=batch)
userids = userids + map(lambda x:x['id'] ,j)
found = sets.Set(map(lambda x:x['screen_name'].lower(), j))
for x in j:
print "caching"
print ((x['screen_name'], x['id']))
cache_userid(x['screen_name'], x['id'])
# f.close()
except Exception as e:
print "connection refused" + str(e)
found = sets.Set([])
notfound_this_round = sets.Set(map(lambda x:x.lower(), batch)) - found
print "missing" + str(notfound_this_round)
notfound = notfound + list(notfound_this_round)
print userids
return (userids, notfound)
示例5: screen_name_lookup
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import lookup_user [as 别名]
def screen_name_lookup(screen_names):
tw = Twython(CREDENTIALS['APP_KEY'],
CREDENTIALS['APP_SECRET'],
CREDENTIALS['ACCESS_KEY'],
CREDENTIALS['ACCESS_SECRET'])
users = tw.lookup_user(screen_name=screen_names)
return users
示例6: main
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import lookup_user [as 别名]
def main(args):
global twitter
#Get tweets for the user in the date range
user_timeline = get_timeline_in_range(args.handle, args.start_date, args.end_date)
#select 30 tweets randomly in this range
if len(user_timeline) > 30:
user_timeline = np.random.choice(user_timeline, 30, replace=False)
retweeter_ids = []
#for each tweet, collect the retweeters
for tweet in user_timeline:
time.sleep(3)
try:
result = twitter.get_retweeters_ids(id=tweet['id'], count=50)
retweeter_ids.extend(result['ids'])
print "...."
except TwythonAuthError as e:
print "TwythonAuthError..."
continue
except TwythonRateLimitError as e:
print "TwythonRateLimitError... Waiting for 240 seconds"
time.sleep(240)
twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
continue
except TwythonError as e:
print "TwythonError..."
#shuffle the retweeters to select random 50 retweeters as active followers
np.random.shuffle(retweeter_ids)
print "selecting 50 followers ..."
#select 50 followers
followers = set()
for id in retweeter_ids:
followers.add(id)
if len(followers) >= 50:
break
followers = map(lambda x: str(x), followers)
with open(args.follower_file, 'wb') as output:
for id in followers:
time.sleep(2)
try:
result = twitter.lookup_user(user_id=id)
except TwythonAuthError as e:
print "TwythonAuthError..."
continue
except TwythonError as e:
print "TwythonError..."
except TwythonRateLimitError as e:
print "TwythonRateLimitError... Waiting for 240 seconds"
time.sleep(240)
twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
continue
screen_name = result[0]['screen_name']
output.write(screen_name+"\n")
示例7: lookupUser
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import lookup_user [as 别名]
def lookupUser(names):
twitter = Twython(APP_KEY, APP_SECRET)
try:
users = twitter.lookup_user(screen_name = names)
except Exception as e:
logging.error("Error Occured while fetching the Users. Error = %s", e)
return None
return users
示例8: save
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import lookup_user [as 别名]
def save(self, *args, **kwargs):
self.username = self.username.strip("@")
account = StreamAccount.objects.get_default_account()
key = getattr(settings, "TWITTER_ACCESS_TOKEN")
secret = getattr(settings, "TWITTER_ACCESS_TOKEN_SECRET")
token, token_secret = account.auth_data()
twitter = Twython(key, secret, token, token_secret)
user = twitter.lookup_user(screen_name=self.username)
self.user_id = user[0]['id_str']
return super(FollowedUser, self).save(*args, **kwargs)
示例9: get_friends_from_twitter
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import lookup_user [as 别名]
def get_friends_from_twitter(screenname):
# get api key and the secret from Twitter site for developers
APP_KEY = 'enter-your-api-key'
APP_SECRET = 'enter-your-secret'
twitter = Twython(APP_KEY, APP_SECRET, oauth_version=2)
ACCESS_TOKEN = twitter.obtain_access_token()
twitter = Twython(APP_KEY, access_token=ACCESS_TOKEN)
results = twitter.lookup_user(screen_name=screenname)
# there should be only one result as we use only one screename
for result in results:
return result['friends_count']
示例10: get_twitter_id
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import lookup_user [as 别名]
def get_twitter_id():
app_key = 'o2364QzhfTxjCCwZ6guKTPN4i'
app_secret ='JGwxQzbtLGsIu2HXV4f2T1GALgKrNm7O7wdZs6xBzoMZVnWksZ'
oauth_token = '3568557440-z3V9Ki4eptgt09nAnUhCPtF8eYy3btN2jR9QNBM'
oauth_token_secret= 'qPR9BlhPcLxvnRO6AETMoBo0eZaF1DP0CF4fYbUqaN9E7'
twitter = Twython(app_key, app_secret, oauth_token, oauth_token_secret)
ids=request.form['scname']
output = twitter.lookup_user(screen_name=ids)
for user in output:
twitid=user["id_str"]
return render_template('twitter_main.html',var=twitid)
示例11: main
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import lookup_user [as 别名]
def main():
HANDLE = "darth"
# Look up user id for the target handle
twitter = Twython(
TWITTER_CONSUMER_KEY,
TWITTER_CONSUMER_SECRET,
TWITTER_ACCESS_TOKEN,
TWITTER_ACCESS_TOKEN_SECRET
)
user_id = twitter.lookup_user(screen_name=HANDLE)[0]["id_str"]
print "@"+HANDLE+",","id",user_id
# Set up the user stream and follow it
stream = UserStreamer(
HANDLE,
TWITTER_CONSUMER_KEY,
TWITTER_CONSUMER_SECRET,
TWITTER_ACCESS_TOKEN,
TWITTER_ACCESS_TOKEN_SECRET
)
stream.statuses.filter(follow=user_id)
示例12: Twython
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import lookup_user [as 别名]
import sys
import string
import simplejson as json
from twython import Twython
t = Twython(app_key='hHjgxpGc6OJnUS0ofo8pbZ44u',
app_secret='RTs2a3OJC1sVsFBaHUcZpffhF4Gf68MDDegiDDaYzNyeSAev8Q',
oauth_token='2458312922-JbBy5HKykN7tJ0atrY79evGE4f3Gcbt3IWMsO8g',
oauth_token_secret='Z6HmlPYdFttm76QE05Q37C7DLn8atcrsvsBbwOHDkYh9V')
entry1= raw_input("First user: ")
entry2= raw_input("Second user: ")
user1= t.lookup_user(screen_name=entry1)
for entry in user1:
statuses1= entry['statuses_count']
favourites1=entry['favourites_count']
followers1=entry['followers_count']
friends1=entry['friends_count']
user2= t.lookup_user(screen_name=entry2)
for entry in user2:
statuses2= entry['statuses_count']
favourites2=entry['favourites_count']
followers2=entry['followers_count']
friends2=entry['friends_count']
score1=0
score2=0
if statuses1>statuses2:
score1=score1+1
elif statuses2>statuses1:
score2=score2+1
if favourites1>favourites2:
score1=score1+1
elif favourites2>favourites1:
示例13: Twython
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import lookup_user [as 别名]
from twython import Twython, TwythonError
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
uid = sys.argv[1]
APP_KEY = "g1sBsjOkO6Ik2xQLWjPweg";
APP_SECRET = "RFADPSzcGEaPW3E5qQHxBiscydxrQkjqS2oPYgIIOzI";
OAUTH_TOKEN = "2359516250-RUL2dUtGx8PQzn3PPufVL5ZZZgB2yOEQAfg40AP";
OAUTH_TOKEN_SECRET ="v1WbJ44YQ5WYPPgXNDxe9P7E3HNtqdVKSjw1l7gMYIobJ";
usr = ""
username = ""
twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
output = twitter.lookup_user(user_id=uid)
data = output[0]
username=data["screen_name"]
browser = webdriver.Firefox()
#browser = webdriver.Chrome(executable_path="/home/santosh/Documents/chromedriver")
#browser.get("https://twitter.com/search?src=typd&q=%40BarackObama")
browser.get("https://twitter.com/"+username)
time.sleep(1)
elem = browser.find_element_by_tag_name("body")
no_of_pagedowns = 50
while no_of_pagedowns:
elem.send_keys(Keys.PAGE_DOWN)
示例14: TwythonEndpointsTestCase
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import lookup_user [as 别名]
#.........这里部分代码省略.........
@unittest.skip('skipping non-updated test')
def test_update_profile(self):
"""Test updating profile succeeds"""
self.api.update_profile(include_entities='true')
@unittest.skip('skipping non-updated test')
def test_update_profile_colors(self):
"""Test updating profile colors succeeds"""
self.api.update_profile_colors(profile_background_color='3D3D3D')
@unittest.skip('skipping non-updated test')
def test_list_blocks(self):
"""Test listing users who are blocked by the authenticated user
succeeds"""
self.api.list_blocks()
@unittest.skip('skipping non-updated test')
def test_list_block_ids(self):
"""Test listing user ids who are blocked by the authenticated user
succeeds"""
self.api.list_block_ids()
@unittest.skip('skipping non-updated test')
def test_create_block(self):
"""Test blocking a user succeeds"""
self.api.create_block(screen_name='justinbieber')
@unittest.skip('skipping non-updated test')
def test_destroy_block(self):
"""Test unblocking a user succeeds"""
self.api.destroy_block(screen_name='justinbieber')
@unittest.skip('skipping non-updated test')
def test_lookup_user(self):
"""Test listing a number of user objects succeeds"""
self.api.lookup_user(screen_name='twitter,justinbieber')
@unittest.skip('skipping non-updated test')
def test_show_user(self):
"""Test showing one user works"""
self.api.show_user(screen_name='twitter')
@unittest.skip('skipping non-updated test')
def test_search_users(self):
"""Test that searching for users succeeds"""
self.api.search_users(q='Twitter API')
@unittest.skip('skipping non-updated test')
def test_get_contributees(self):
"""Test returning list of accounts the specified user can
contribute to succeeds"""
self.api.get_contributees(screen_name='TechCrunch')
@unittest.skip('skipping non-updated test')
def test_get_contributors(self):
"""Test returning list of accounts that contribute to the
authenticated user fails because we are not a Contributor account"""
self.assertRaises(TwythonError, self.api.get_contributors,
screen_name=screen_name)
@unittest.skip('skipping non-updated test')
def test_remove_profile_banner(self):
"""Test removing profile banner succeeds"""
self.api.remove_profile_banner()
@unittest.skip('skipping non-updated test')
示例15: TwythonAPITestCase
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import lookup_user [as 别名]
#.........这里部分代码省略.........
def test_update_delivery_service(self):
'''Test updating delivery settings fails because we don't have
a mobile number on the account'''
self.assertRaises(TwythonError, self.api.update_delivery_service,
device='none')
def test_update_profile(self):
'''Test updating profile succeeds'''
self.api.update_profile(include_entities='true')
def test_update_profile_colors(self):
'''Test updating profile colors succeeds'''
self.api.update_profile_colors(profile_background_color='3D3D3D')
def test_list_blocks(self):
'''Test listing users who are blocked by the authenticated user
succeeds'''
self.api.list_blocks()
def test_list_block_ids(self):
'''Test listing user ids who are blocked by the authenticated user
succeeds'''
self.api.list_block_ids()
def test_create_block(self):
'''Test blocking a user succeeds'''
self.api.create_block(screen_name='justinbieber')
def test_destroy_block(self):
'''Test unblocking a user succeeds'''
self.api.destroy_block(screen_name='justinbieber')
def test_lookup_user(self):
'''Test listing a number of user objects succeeds'''
self.api.lookup_user(screen_name='twitter,justinbieber')
def test_show_user(self):
'''Test showing one user works'''
self.api.show_user(screen_name='twitter')
def test_search_users(self):
'''Test that searching for users succeeds'''
self.api.search_users(q='Twitter API')
def test_get_contributees(self):
'''Test returning list of accounts the specified user can
contribute to succeeds'''
self.api.get_contributees(screen_name='TechCrunch')
def test_get_contributors(self):
'''Test returning list of accounts that contribute to the
authenticated user fails because we are not a Contributor account'''
self.assertRaises(TwythonError, self.api.get_contributors,
screen_name=screen_name)
def test_remove_profile_banner(self):
'''Test removing profile banner succeeds'''
self.api.remove_profile_banner()
def test_get_profile_banner_sizes(self):
'''Test getting list of profile banner sizes fails because
we have not uploaded a profile banner'''
self.assertRaises(TwythonError, self.api.get_profile_banner_sizes)
# Suggested Users