本文整理汇总了Python中twython.Twython.get_followers_ids方法的典型用法代码示例。如果您正苦于以下问题:Python Twython.get_followers_ids方法的具体用法?Python Twython.get_followers_ids怎么用?Python Twython.get_followers_ids使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类twython.Twython
的用法示例。
在下文中一共展示了Twython.get_followers_ids方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: fetch_twitter_followers
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import get_followers_ids [as 别名]
def fetch_twitter_followers(self):
twitter = Twython(APP_KEY_TWITTER, APP_SECRET_TWITTER,
OAUTH_TOKEN_TWITTER, OAUTH_TOKEN_SECRET_TWITTER)
twitter_obj = twitter.get_followers_ids()
twitter_followers = len(twitter_obj['ids'])
twitter_followers = '{:,}'.format(int(twitter_followers))
self.twitter = twitter_followers
示例2: login
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import get_followers_ids [as 别名]
def login():
# Go to http://twitter.com/apps/new to create an app and get these items
# See also http://dev.twitter.com/pages/oauth_single_token
server = couchdb.Server()
db = server['tweepsnigeria_followers']
db2= server['tweetsoccupynigeria']
APP_NAME = 'traffic_ug'
TWITTER_APP_KEY = 'U31NQIxZ1HcKeKTUtTW1w' #supply the appropriate value
TWITTER_APP_KEY_SECRET = 'bZBtxjQurHUfjDvK8Pl5iJWhgvzejvC2HJHSN1E'
TWITTER_ACCESS_TOKEN = '1548279967-gDMrGBaZIb3jofVekP25SnpWZrnhxSSFra7GgRV'
TWITTER_ACCESS_TOKEN_SECRET = 'zLwSwgsMZxtH0tlB2x1UU217nq0ujlpkzP8SCXa07u8'
t = Twython(app_key=TWITTER_APP_KEY,
app_secret=TWITTER_APP_KEY_SECRET,
oauth_token=TWITTER_ACCESS_TOKEN,
oauth_token_secret=TWITTER_ACCESS_TOKEN_SECRET)
names=[]
in_file=open('tweeps_no_followers.txt','rb')
count=1
count2=1
for row in in_file:
name=row.strip()
if (count>=608):
print count, row
profile=t.get_followers_ids(screen_name=name)
db[name] = profile
count2+=1
count+=1
if((count2%16)==0):
time.sleep(15*60)
count2=1
in_file.close()
示例3: get_followers_following
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import get_followers_ids [as 别名]
def get_followers_following(usr_id):
index = 0
print "GETTING FOLLOWERS AND FOLLOWING: " + str(usr_id)
friend_cursor = -1
follower_cursor = -1
APP_KEY = APP_KEYS[index]
APP_SECRET = APP_SECRETS[index]
OAUTH_TOKEN = OAUTH_TOKENS[index]
OAUTH_TOKEN_SECRET = OAUTH_TOKEN_SECRETS[index]
while (1==1):
try:
twitter = Twython (APP_KEY, APP_SECRET)
auth = twitter.get_authentication_tokens()
twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
friends = ""
while (friend_cursor != 0):
following = twitter.get_friends_ids(id = usr_id, cursor = friend_cursor)
for ID in following['ids']:
friends += str(ID) + " "
friend_cursor = following["next_cursor"]
friends = friends[:-1]
if len(friends) == 0:
friends = "null"
follow = ""
while (follower_cursor != 0):
followers = twitter.get_followers_ids(id = usr_id,cursor= follower_cursor)
for ID in followers['ids']:
follow += str(ID) + " "
follower_cursor = followers["next_cursor"]
follow= follow[:-1]
if len(follow) == 0:
follow = "null"
return (friends,follow)
except Exception as e:
print e
if "429 (Too Many Requests)" in str(e):
#global index
index += 1
if index == len(APP_KEYS):
index = 0
print "sleepy time - 15 minutes"
print datetime.datetime.now()
time.sleep(910)
return get_followers_following(usr_id)
elif "401 (Unauthorized)" in str(e):
print "401 error"
return ("null","null")
elif "404 (Not Found)" in str(e):
print "404 error"
return ("null","null")
else:
print e
return ("null","null")
示例4: main
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import get_followers_ids [as 别名]
def main(argv):
os.system('clear')
print 'Queue Processor v.'+VERSION+'\n'
print 'Starting the "friending" procedure for:'
for q in Queue.objects.filter(is_processed=False):
q.processing = True
q.save()
user = q.user
profile = Profile.objects.get(user=user)
target = q.requested_twitter_user_handle
processing = q.processing
is_processed = q.is_processed
if(is_processed): continue
print '\nOur target:',color.BOLD + '@' + target + color.END + '\n'
oauth_token = profile.oauth_token
oauth_token_secret = profile.oauth_secret
twitter = Twython(APP_KEY, APP_SECRET, oauth_token, oauth_token_secret)
try:
followers = twitter.get_followers_ids(screen_name = target, count=300)
except:
print 'Skipping this one...'
q.is_processed = True
q.save()
continue
count = 1
for follower_id in followers['ids']:
print count, '..befriending', color.GREEN + 'id_' + str(follower_id) + color.END
try:
twitter.create_friendship(screen_name=target, follow="true")
except TwythonError as e:
print target
print '\n', e
sleep_time = random.randint(12,90)
print '..sleeping for',sleep_time,'seconds (180 request in 15 mins = 1 request at minimum of 12 seconds)'
time.sleep(sleep_time)
count+=1
q.is_processed = 1
q.save()
示例5: Command
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import get_followers_ids [as 别名]
class Command(BaseCommand):
def __init__(self):
self.twitter = Twython(CONSUMER_KEY, CONSUMER_SECRET)
def handle(self, *args, **options):
current_users = [user.twitter_id for user in TwitterUser.objects.all()]
# Update DB with latest followers
for user_id in self.twitter.get_followers_ids(screen_name='John_DM')["ids"]:
if user_id not in current_users:
TwitterUser.objects.create(twitter_id = user_id)
# Prioritises users who signed up most recently
# Should work through backlog if we dont get > 100 followers/day
users_to_follow = TwitterUser.objects.filter(created__lte=timezone.now() - timedelta(days=3), followed__isnull=True).order_by('-created')[:100]
for target in users_to_follow:
self.twitter.create_friendship(user_id=target.twitter_id, follow="true")
target.follow()
time.sleep(61) # Is there a better way to do rate limiting?
示例6: getFollowers
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import get_followers_ids [as 别名]
def getFollowers(screen_name):
consumer_key = "MLGdNZCfmzGthHTAyJU4KFvbU"
consumer_secret ="Tfp7DIZcJLbnS8BR5CWQmZklrhsbtc3fMfssKPT4SZoYsPiQKw"
access_token ="2383540880-s2C8xPgA4ITF7QnLRFnHK1es2UEbmW8qHQ87sX5"
access_token_secret ="kLYgBTPeslLgaFugCx0PoiBpPIKnyCBEVfqqJCkjsSKpP"
twitter = Twython(consumer_key, consumer_secret,access_token,access_token_secret )
while(True):
try:
followers = twitter.get_followers_ids(screen_name = screen_name)
followers_id = followers['ids']
return followers_id
except TwythonRateLimitError:
print("Fall asleep")
sleep(300)
pass
except wythonError:
print("404 not found")
return []
except TwythonAuthError:
print("Bad Authentication")
return []
示例7: TwitterHelper
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import get_followers_ids [as 别名]
#.........这里部分代码省略.........
place = result["result"]["places"][0]
location.place_id_twitter = place["id"]
return location
else:
return None
@retry(**retry_args)
def update_profile_image(self, file_path):
if file_path:
logger.info("updating profile image %s" % file_path)
with open(file_path, 'rb') as file:
self.twitter.update_profile_image(image=file)
@retry(**retry_args)
def update_profile_banner_image(self, file_path):
if file_path:
logger.info("updating banner image %s" % file_path)
with open(file_path, 'rb') as file:
try:
self.twitter.update_profile_banner_image(banner=file)
except TwythonError as ex:
if "Response was not valid JSON" in str(ex):
# twython issue i think
logger.warning(ex)
else:
raise
@retry(**retry_args)
def update_profile(self, **kwargs):
return self.twitter.update_profile(**kwargs)
@retry(**retry_args)
def get_list_statuses(self, **kwargs):
return self.twitter.get_list_statuses(**kwargs)
@retry(**retry_args)
def get_user_suggestions_by_slug(self, **kwargs):
return self.twitter.get_user_suggestions_by_slug(**kwargs)
@retry(**retry_args)
def get_user_suggestions(self, **kwargs):
return self.twitter.get_user_suggestions(**kwargs)
@retry(**retry_args)
def lookup_status(self, **kwargs):
return self.twitter.lookup_status(**kwargs)
@retry(**retry_args)
def get_followers(self, **kwargs):
kwargs["stringify_ids"] = True
followers = set()
cursor = -1
while cursor != "0":
kwargs["cursor"] = cursor
logger.info("getting followers")
response = self.twitter.get_followers_ids(**kwargs)
cursor = response["next_cursor_str"]
followers = followers.union(set(response["ids"]))
return followers
@retry(**retry_args)
def get_following(self, **kwargs):
kwargs["stringify_ids"] = True
following = set()
cursor = -1
while cursor != "0":
kwargs["cursor"] = cursor
logger.info("getting following")
response = self.twitter.get_friends_ids(**kwargs)
cursor = response["next_cursor_str"]
following = following.union(set(response["ids"]))
return following
@retry(**retry_args)
def update_rate_limits(self):
data = self.twitter.get_application_rate_limit_status()
self.rates = RateLimits(data)
logger.info("Updated rate limits for {}: {}".format(self.identity.screen_name, self.rates.display()))
def _rate_limit(self, limit_name, func, *args, **kwargs):
if self.rates.can(limit_name):
try:
return func(*args, **kwargs)
except Exception as ex:
logger.warning(ex)
return None
else:
logger.warning("{} limit exceeded".format(limit_name))
return None
@retry(**retry_args)
def get_statuses(self, id_strs):
id_strs_csv = ",".join(id_strs)
return self.twitter.lookup_status(id=id_strs_csv)
@retry(**retry_args)
def get_status(self, id_str):
return self.twitter.show_status(id=id_str)
示例8: get_following_to_db
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import get_followers_ids [as 别名]
def get_following_to_db(dbpath, sn_table = "tweets9_users"):
distinct = get_D_UsrID(dbpath,sn_table )
index=0
num_checked = 0
rate_ex = 0
ind = 0
already_checked = False
follower_cursor = -1
friend_cursor = -1
print "Starting @ %d"%(ind)
print datetime.datetime.now()
while ind < len(distinct):
#for i in distinct:
i = distinct[ind][0]
APP_KEY = APP_KEYS[index]
APP_SECRET = APP_SECRETS[index]
OAUTH_TOKEN = OAUTH_TOKENS[index]
OAUTH_TOKEN_SECRET = OAUTH_TOKEN_SECRETS[index]
try:
#twitter = Twython (APP_KEY, APP_SECRET)
#auth = twitter.get_authentication_tokens()
twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
#friend_results = twitter.cursor(twitter.get_friends_ids, id = i, cursor= friend_cursor)
friends = ""
while (friend_cursor):
following = twitter.get_friends_ids(id = i,cursor= friend_cursor)
for ID in following['ids']:
friends += str(ID) + " "
friend_cursor = following["next_cursor"]
num_checked += 1
friends = friends[:-1]
if len(friends) == 0:
friends = "null"
follow = ""
while (follower_cursor):
followers = twitter.get_followers_ids(id = i,cursor= follower_cursor)
for ID in followers['ids']:
follow += str(ID) + " "
follower_cursor = followers["next_cursor"]
num_checked += 1
follow= follow[:-1]
if len(follow) == 0:
follow = "null"
conn = sqlite3.connect(dbpath)
cursor = conn.cursor()
query = "UPDATE %s SET Following = '%s' where Usr_ID = '%s'"% (sn_table, friends, i)
cursor.execute(query)
#print query
print "____________________ %dth following updated ________ %d" % (ind, i)
conn.commit()
query = "UPDATE %s SET Followers = '%s' where Usr_ID = '%s' "% (sn_table, follow, i)
cursor.execute(query)
#print query
conn.commit()
conn.close()
print "%dth follower updated_______________________ %d" % (ind, i)
print num_checked
print
follower_cursor = -1
friend_cursor = -1
ind+=1
except Exception as e:
print e
if "429 (Too Many Requests)" in str(e):
index += 1
if index == len(APP_KEYS):
index = 0
print "sleepy time - 15 minutes"
print datetime.datetime.now()
time.sleep(910)
elif "401 (Unauthorized)" in str(e):
print "401 error"
f = open("skipped.txt", "a")
f.write("skipped %dth element, ID: %d\n"%(ind, i))
f.write("__________________________________________"+str(datetime.datetime.now()) + "\n")
f.close()
print "401 nulled %d"%ind
conn = sqlite3.connect(dbpath)
cursor = conn.cursor()
query = "UPDATE %s SET Following = 'null', Followers = 'null' where Usr_ID = '%s'"% (sn_table, i)
cursor.execute(query)
conn.commit()
conn.close()
ind+=1
time.sleep(1)
elif "404 (Not Found)" in str(e):
print "404 error"
f = open("skipped.txt", "a")
f.write("404: skipped %dth element, ID: %d \n"%(ind, i))
f.write("__________________________________________"+str(datetime.datetime.now()) + "\n")
f.close()
#.........这里部分代码省略.........
示例9: TwythonAPITestCase
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import get_followers_ids [as 别名]
#.........这里部分代码省略.........
self.api.get_direct_messages()
def test_get_sent_messages(self):
"""Test getting the authenticated users direct messages they've
sent succeeds"""
self.api.get_sent_messages()
def test_send_get_and_destroy_direct_message(self):
"""Test sending, getting, then destory a direct message succeeds"""
message = self.api.send_direct_message(screen_name=protected_twitter_1,
text='Hey d00d! %s' % int(time.time()))
self.api.get_direct_message(id=message['id_str'])
self.api.destroy_direct_message(id=message['id_str'])
def test_send_direct_message_to_non_follower(self):
"""Test sending a direct message to someone who doesn't follow you
fails"""
self.assertRaises(TwythonError, self.api.send_direct_message,
screen_name=protected_twitter_2, text='Yo, man!')
# Friends & Followers
def test_get_user_ids_of_blocked_retweets(self):
"""Test that collection of user_ids that the authenticated user does
not want to receive retweets from succeeds"""
self.api.get_user_ids_of_blocked_retweets(stringify_ids=True)
def test_get_friends_ids(self):
"""Test returning ids of users the authenticated user and then a random
user is following succeeds"""
self.api.get_friends_ids()
self.api.get_friends_ids(screen_name='twitter')
def test_get_followers_ids(self):
"""Test returning ids of users the authenticated user and then a random
user are followed by succeeds"""
self.api.get_followers_ids()
self.api.get_followers_ids(screen_name='twitter')
def test_lookup_friendships(self):
"""Test returning relationships of the authenticating user to the
comma-separated list of up to 100 screen_names or user_ids provided
succeeds"""
self.api.lookup_friendships(screen_name='twitter,ryanmcgrath')
def test_get_incoming_friendship_ids(self):
"""Test returning incoming friendship ids succeeds"""
self.api.get_incoming_friendship_ids()
def test_get_outgoing_friendship_ids(self):
"""Test returning outgoing friendship ids succeeds"""
self.api.get_outgoing_friendship_ids()
def test_create_friendship(self):
"""Test creating a friendship succeeds"""
self.api.create_friendship(screen_name='justinbieber')
def test_destroy_friendship(self):
"""Test destroying a friendship succeeds"""
self.api.destroy_friendship(screen_name='justinbieber')
def test_update_friendship(self):
"""Test updating friendships succeeds"""
self.api.update_friendship(screen_name=protected_twitter_1,
retweets='true')
示例10: updateFollowerFollowings
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import get_followers_ids [as 别名]
def updateFollowerFollowings(dbpath, user_table = "users"):
distinct = get_D_UsrID(dbpath,sn_table )
conn = sqlite3.connect(dbpath)
cursor = conn.cursor()
query = "select Usr_ID from %s where Following is null or Followers is null"
cursor.execute(query)
distinct = cursor.fetchall()
follower_cursor = -1
friend_cursor = -1
print "Starting @ %d"%(ind)
print datetime.datetime.now()
while ind < len(distinct):
#for i in distinct:
i = distinct[ind][0] # Usr_ID
APP_KEY = APP_KEYS[index]
APP_SECRET = APP_SECRETS[index]
OAUTH_TOKEN = OAUTH_TOKENS[index]
OAUTH_TOKEN_SECRET = OAUTH_TOKEN_SECRETS[index]
try:
#twitter = Twython (APP_KEY, APP_SECRET)
#auth = twitter.get_authentication_tokens()
twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
friends = ""
while (friend_cursor):
following = twitter.get_friends_ids(id = i,cursor= friend_cursor)
for ID in following['ids']:
friends += str(ID) + " "
friend_cursor = following["next_cursor"]
num_checked += 1
friends = friends[:-1]
if len(friends) == 0:
friends = "null"
follow = ""
while (follower_cursor):
followers = twitter.get_followers_ids(id = i,cursor= follower_cursor)
for ID in followers['ids']:
follow += str(ID) + " "
follower_cursor = followers["next_cursor"]
num_checked += 1
follow= follow[:-1]
if len(follow) == 0:
follow = "null"
conn = sqlite3.connect(dbpath)
cursor = conn.cursor()
query = "UPDATE %s SET Following = '%s', Followers = '%s', NumFollowing = '%d', NumFollowers = '%d' where Usr_ID = '%s'"% (sn_table, friends,follow, len(friends.split(" ")), len(follow.split(" ")), i)
cursor.execute(query)
#print query
conn.close()
print "____________________ %dth following and friends and their corresponding counts updated ________ %d" % (ind, i)
follower_cursor = -1
friend_cursor = -1
ind+=1
except Exception as e:
print e
if "429 (Too Many Requests)" in str(e):
index += 1
if index == len(APP_KEYS):
index = 0
print "sleepy time; pausing for 15 minutes for APP Keys to renew"
print datetime.datetime.now()
#time.sleep(910)
print "App Rate Limits has been exceeded- we will wait for next runtime before running rest of followers and followings"
return
elif "401 (Unauthorized)" in str(e):
print "401 Unauthorized Error nulling %d________________Usr_ID:%d"%(ind,i)
conn = sqlite3.connect(dbpath)
cursor = conn.cursor()
query = "UPDATE %s SET Following = 'null', Followers = 'null' where Usr_ID = '%s'"% (sn_table, i)
cursor.execute(query)
conn.commit()
conn.close()
ind+=1
elif "404 (Not Found)" in str(e):
print "404 Not Found Error nulling %d________________Usr_ID:%d"%(ind,i)
conn = sqlite3.connect(dbpath)
cursor = conn.cursor()
query = "UPDATE %s SET Following = 'null', Followers = 'null' where Usr_ID = '%s'"% (sn_table, i)
cursor.execute(query)
conn.commit()
conn.close()
ind+=1
else:
print e
示例11: get_followers
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import get_followers_ids [as 别名]
def get_followers():
distinct = getScreenname.getDistinctScreenames("all_tweets_dict_fully_checked")
index=0
num_checked = 0
rate_ex = 0
for sname in distinct:
file = open("followers.txt", "r+")
already_checked = False
for line in file:
words = line.split('\t')
if words[0] == sname:
already_checked = True
if index >= 7:
break
APP_KEY = APP_KEYS[index]
APP_SECRET = APP_SECRETS[index]
OAUTH_TOKEN = OAUTH_TOKENS[index]
OAUTH_TOKEN_SECRET = OAUTH_TOKEN_SECRETS[index]
if not already_checked:
try:
twitter = Twython (APP_KEY, APP_SECRET)
auth = twitter.get_authentication_tokens()
twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET)
followers = twitter.get_followers_ids(screen_name=sname)
print sname
file.write (sname)
file.write ("\t")
for ID in followers['ids']:
file.write(str(ID) + " ")
file.write("\n")
num_checked += 1
except Exception as e:
if "429 (Too Many Requests)" in str(e):
print "\nchanging apps!\n"
index += 1
if "401 (Unauthorized)" in str(e):
print "401 error"
file.write(sname)
file.write("\t")
file.write("Unauthorized")
file.write("\n")
if "404 (Not Found)" in str(e):
print "404 error"
file.write(sname)
file.write("\t")
file.write("NotFound")
file.write("\n")
else:
print e
rate_ex += 1
file.close()
if (num_checked != 0 or rate_ex !=0):
print "sleepy time"
time.sleep(860)
get_followers()
示例12: Twython
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import get_followers_ids [as 别名]
timeout = 10 * 60
idnum = '0' # a tweet ID can be put in here to limit searches
count = 0
# your twitter consumer and access information goes here
apiKey = '****'
apiSecret = '****'
accessToken = '****'
accessTokenSecret = '****'
twitter = Twython(apiKey,apiSecret,accessToken,accessTokenSecret)
while True:
#auto follow back function
try:
followers = twitter.get_followers_ids(screen_name = "Botrack Obama") #Enter twitter handle here
for followers_ids in followers['ids']:
twitter.create_friendship(user_id=followers_ids)
except TwythonError as e:
print(e)
search_results = twitter.search(q="thanksobama", since_id = idnum, count=20)
#searchs a hashtag from after a certian tweet with a max of 20 results
count = 0
for tweet in search_results["statuses"]:
try:
rannum = random.randrange(1,5)
print(rannum)
if rannum == 2:
#Below line retweets the statuses
twitter.retweet(id = tweet["id_str"])
示例13: Twython
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import get_followers_ids [as 别名]
accessToken = '***'
accessTokenSecret = '***'
api = Twython(apiKey,apiSecret,accessToken,accessTokenSecret)
while True:
#opens a txt file containing tweets and imports it into a list
tweetStr = open("tweetsexample.txt").readlines()
listlength = len(tweetStr)
for i in range(listlength):
# Auto Following function
try:
followers = api.get_followers_ids(screen_name = "Twitter Handle goes here")
for followers_ids in followers['ids']:
api.create_friendship(user_id=followers_ids)
except TwythonError as e:
print(e)
#Trys to post the next tweet in the list, if it fails it will continue to the next one
try:
api.update_status(status=tweetStr[i])
print ("Tweeted: " + tweetStr[i])
time.sleep(timeout)
except TwythonError as e:
print ("Failed: " + tweetStr[i])
time.sleep(30)
i = 0
示例14: TwythonAPITestCase
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import get_followers_ids [as 别名]
#.........这里部分代码省略.........
self.api.get_direct_messages()
def test_get_sent_messages(self):
'''Test getting the authenticated users direct messages they've
sent succeeds'''
self.api.get_sent_messages()
def test_send_get_and_destroy_direct_message(self):
'''Test sending, getting, then destory a direct message succeeds'''
message = self.api.send_direct_message(screen_name=protected_twitter_1,
text='Hey d00d!')
self.api.get_direct_message(id=message['id_str'])
self.api.destroy_direct_message(id=message['id_str'])
def test_send_direct_message_to_non_follower(self):
'''Test sending a direct message to someone who doesn't follow you
fails'''
self.assertRaises(TwythonError, self.api.send_direct_message,
screen_name=protected_twitter_2, text='Yo, man!')
# Friends & Followers
def test_get_user_ids_of_blocked_retweets(self):
'''Test that collection of user_ids that the authenticated user does
not want to receive retweets from succeeds'''
self.api.get_user_ids_of_blocked_retweets(stringify_ids='true')
def test_get_friends_ids(self):
'''Test returning ids of users the authenticated user and then a random
user is following succeeds'''
self.api.get_friends_ids()
self.api.get_friends_ids(screen_name='twitter')
def test_get_followers_ids(self):
'''Test returning ids of users the authenticated user and then a random
user are followed by succeeds'''
self.api.get_followers_ids()
self.api.get_followers_ids(screen_name='twitter')
def test_lookup_friendships(self):
'''Test returning relationships of the authenticating user to the
comma-separated list of up to 100 screen_names or user_ids provided
succeeds'''
self.api.lookup_friendships(screen_name='twitter,ryanmcgrath')
def test_get_incoming_friendship_ids(self):
'''Test returning incoming friendship ids succeeds'''
self.api.get_incoming_friendship_ids()
def test_get_outgoing_friendship_ids(self):
'''Test returning outgoing friendship ids succeeds'''
self.api.get_outgoing_friendship_ids()
def test_create_friendship(self):
'''Test creating a friendship succeeds'''
self.api.create_friendship(screen_name='justinbieber')
def test_destroy_friendship(self):
'''Test destroying a friendship succeeds'''
self.api.destroy_friendship(screen_name='justinbieber')
def test_update_friendship(self):
'''Test updating friendships succeeds'''
self.api.update_friendship(screen_name=protected_twitter_1,
retweets='true')
示例15: get_active_users_around
# 需要导入模块: from twython import Twython [as 别名]
# 或者: from twython.Twython import get_followers_ids [as 别名]
def get_active_users_around(center, start_date, end_date, threshold, num_friends, num_followers, waiting):
twitter = Twython(APP_KEY, access_token=ACCESS_TOKEN)
user_ids = []
all_tweets = []
# get friends and followers around a central user
print "Getting users..."
while True:
try:
following = twitter.get_friends_ids(screen_name=center, count=5000)
time.sleep(0.1)
followers = twitter.get_followers_ids(screen_name=center, count=5000)
break
except TwythonAuthError as e:
print "TwythonAuthError..."
time.sleep(waiting)
continue
except TwythonRateLimitError as e:
print "TwythonRateLimitError... Waiting for 3 minutes (may take multiple waits)"
for timer in tqdm(range(3*60)):
time.sleep(1)
twitter = Twython(APP_KEY, access_token=ACCESS_TOKEN)
time.sleep(waiting)
continue
except TwythonError as e:
print "TwythonError: " + str(e.error_code) + "..."
time.sleep(waiting)
continue
# choose out random friends and followers from the previous list, with a safety factor of 2 times as many as asked for to account for the fact that some users will not be active
following = map(lambda x: str(x), np.random.choice(following['ids'], min(int(num_friends * 2), len(following['ids'])), replace=False))
followers = map(lambda x: str(x), np.random.choice(followers['ids'], min(int(num_followers * 2), len(followers['ids'])), replace=False))
following = get_usernames(following, waiting)
followers = get_usernames(followers, waiting)
# figure out how many tweets are necessary to deem a user "active"
start = datetime.strptime(start_date, "%Y-%m-%d")
end = datetime.strptime(end_date, "%Y-%m-%d")
threshold = abs(end-start).days * threshold
# collect out as many active followed users from the central user (and their tweets) as we can, up to a limit of the number asked for
collected_friends = []
for user in following:
user_timeline = get_timeline_in_range(user, start_date, end_date, waiting)
if len(user_timeline) >= threshold:
collected_friends.append(user)
all_tweets.extend(user_timeline)
if len(collected_friends) >= num_friends:
break
# collect out as many active followers from the central user (and their tweets) as we can, up to a limit of the number asked for
collected_followers = []
for user in followers:
user_timeline = get_timeline_in_range(user, start_date, end_date, waiting)
if len(user_timeline) >= threshold:
collected_followers.append(user)
all_tweets.extend(user_timeline)
if len(collected_followers) >= num_followers:
break
# return our list of users and their tweets from the time period in question
user_ids.extend(collected_friends)
user_ids.extend(collected_followers)
return (user_ids, all_tweets)