def twitteradd(request, usertoadd): #usertoadd = User.get(username=uidtofollow) twitterauth = UserSocialAuth.objects.get(user=request.user, provider="twitter") if twitterauth is None: return False oauth_consumer_key = settings.SOCIAL_AUTH_TWITTER_KEY oauth_token = twitterauth.extra_data['access_token']['oauth_token'] #oauth_nonce = "91227c2566963d6ae01eb72f974e964a" oauth_nonce = "".join([random.choice(string.letters) for i in xrange(32)]) oauth_signature = "eGxVJXIYoG%2B9ay0A4E7QxnBHHrI%3D" #currenttime = "1381017251" currenttime = str(int(time.time())) #user_to_follow = "15378324" from twython import Twython twitter = Twython(settings.SOCIAL_AUTH_TWITTER_KEY, settings.SOCIAL_AUTH_TWITTER_SECRET, twitterauth.extra_data['access_token']['oauth_token'], twitterauth.extra_data['access_token']['oauth_token_secret']) try: useridtofollow = UserSocialAuth.objects.get(user=usertoadd, provider="twitter").extra_data['id'] except: return False try: twitter.create_friendship(user_id=useridtofollow) except: return False return True
def on_success(self, data): if 'event' in data and 'target' in data and 'source' in data: if data['event'] == 'follow' and data['target']['screen_name'] == 'FutureDiaryBot': twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET) try: twitter.create_friendship(user_id = data['source']['id']) print 'auto followed @' + data['source']['screen_name'] except TwythonError as error: print error
def on_success(self, data): if "event" in data and "target" in data and "source" in data: if data["event"] == "follow" and data["target"]["screen_name"] == "FutureDiaryBot": twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET) try: twitter.create_friendship(user_id=data["source"]["id"]) print "auto followed @" + data["source"]["screen_name"] except TwythonError as error: print error
def main(episodenumber, live_tweet, testmode): import sqlite3 as lite from twython import Twython import os import warnings warnings.filterwarnings("ignore") dir = os.path.dirname(__file__) filename = os.path.join(dir, '../tweets.db') con = lite.connect(filename) import twitterconfig twitter = Twython(twitterconfig.APP_KEY, twitterconfig.APP_SECRET, twitterconfig.OAUTH_TOKEN, twitterconfig.OAUTH_TOKEN_SECRET) top_tweets = '' tweet = '#Tatort Twitter-SEK: ' with con: cur = con.cursor() command = 'SELECT screen_name, count(tweet) FROM tatorttweets WHERE lfd = ' + str(episodenumber) + ' GROUP BY screen_name ORDER BY count(tweet) desc LIMIT 10 ' cur.execute(command) rows = cur.fetchall() for row in rows: try: twitter.create_friendship(screen_name=row[0]) except Exception as e: if testmode: print e stringrow = '<a href="http://twitter.com/' + row[0] + '">@' + row[0] + '</a>' + ' (' + str(row[1]) + ')' top_tweets += stringrow + " <br />\n" newtweet = tweet + ' \n@' + row[0] if not len(newtweet) > 140: tweet = newtweet toptweetsfilename = os.path.join(dir, "../FlaskWebProject/templates/top_tweets/top_tweets_" + str(episodenumber) + ".txt") toptweetsfile = open(toptweetsfilename, "w") if testmode: print top_tweets print >> toptweetsfile, top_tweets toptweetsfile.close() # cmd = "scp -P 50001 " + toptweetsfilename + " [email protected]:../public/tatorttweets//FlaskWebProject/templates/top_tweets/top_tweets_" + str(episodenumber) + ".txt" # print cmd # os.system(cmd) if testmode: print if testmode: print tweet if testmode: print len(tweet) if live_tweet: try: twitter.update_status(status=tweet) except Exception as e: if testmode: print e
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()
def twitter(): tpath = os.path.join(os.path.dirname(os.path.realpath('fiverr.exe')), 'tweets.txt') tweetstosend = open(tpath).readlines() newUsers = [] config = ConfigParser.ConfigParser() config.read(path) current_action = config.get("Settings", "Action") # --------------------------------Twython Authorization----------------------------------- t = Twython(app_key=consumer_key, app_secret=consumer_secret, oauth_token=access_token_key, oauth_token_secret=access_token_secret) # --------------------------------Hashtag Parsing----------------------------------- actions = [] current_hashtag = config.get("Settings", "Hashtag") current_action = config.get("Settings", "Action") current_action = current_action[1:len(current_action)-1].split(',') #current_action = current_action.split(',') for i in current_action: actions.append(i.lstrip()) print actions search = t.search(q='#'+current_hashtag,count=100) tweets = search['statuses'] for tweet in tweets: username = str(tweet['user']['screen_name']) if username not in users and username not in newUsers: #Has the user been accounted for? newUsers.append(username) print 'User added: ' + username print actions try: for action in actions: print action if action == ("'Retweet'"): t.retweet(id = tweet['id_str']) print 'retweeted' if action == "'Favorite'": t.create_favorite(id = tweet['id_str']) print 'favorited' if action == "'Tweet'": t.update_status(status="@{0} {1}".format(username, random.choice(tweetstosend))) print 'tweeted' if action == "'Follow'": t.create_friendship(screen_name = username) print 'followed' except: print "NULL" tweetedUsers = "\n".join(newUsers) file = open(uLpath, 'a') file.write(tweetedUsers + '\n') file.close() time.sleep(1800)
def follow_twitter_user(log, id): log.debug(" Following %s", id) check_twitter_config() logging.captureWarnings(True) old_level = log.getEffectiveLevel() log.setLevel(logging.ERROR) twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET) try: twitter.create_friendship(screen_name=id) except TwythonAuthError, e: log.setLevel(old_level) log.exception(" Problem trying to follow twitter user") twitter_auth_issue(e) raise
def follow_twitter_user(log, id): log.debug(" Following %s", id) check_twitter_config() logging.captureWarnings(True) old_level = log.getEffectiveLevel() log.setLevel(logging.ERROR) twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET) try: twitter.create_friendship(screen_name=id) except TwythonAuthError as e: log.setLevel(old_level) log.exception(" Problem trying to follow twitter user") twitter_auth_issue(e) raise except: raise log.setLevel(old_level)
class Twitter: def __init__(self, consumer_key, consumer_secret, access_token, access_token_secret): try: self.twitter = Twython(consumer_key, consumer_secret, access_token, access_token_secret) except: raise Exception("twitter could not authenticate these tokens!") def get_user_object(self, screen_name): try: user = self.twitter.show_user(screen_name=screen_name) print("got the user object..") return user except: raise Exception("user with this screen_name doesnt exist!") def send_DM(self, screen_name, message): user = self.get_user_object(screen_name) recipient_id = user['id'] event_data = { "event": { "type": "message_create", "message_create": { "target": { "recipient_id": recipient_id }, "message_data": { "text": message } } } } try: event = self.twitter.send_direct_message(**event_data) print("message sent..") return event except: raise Exception("could not DM this person!") def follow(self, to_follow): try: event = self.twitter.create_friendship(screen_name=to_follow) print("followed the user " + to_follow) return event except: raise Exception("could not follow this person!") def unfollow(self, to_unfollow): try: event = self.twitter.destroy_friendship(screen_name=to_unfollow) print("unfollowed the user " + to_unfollow) return event except: raise Exception("could not follow this person!")
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?
def retweet(event, context): twitter = Twython(config.APP_KEY, config.APP_SECRET, config.OAUTH_TOKEN, config.OAUTH_TOKEN_SECRET) search_results = twitter.search(q='#Quote', result_type='mixed', lang='en') message = "" for tweet in search_results['statuses']: try: twitter.retweet(id=tweet['id']) message = f"Retweeted \"{tweet['text']}\" by {tweet['user']['name']}" twitter.create_friendship(id=tweet['user']['id']) break except TwythonError: pass body = {"message": message, "input": event} response = {"statusCode": 200, "body": json.dumps(body)} return response
def massfollow(request): OAUTH_TOKEN = request.GET.get('oauth_token', '') OAUTH_TOKEN_SECRET = request.session['oauth_token_secret'] twitter = Twython(settings.APP_KEY, settings.APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET) oauth_verifier = request.GET.get('oauth_verifier', '') final_step = twitter.get_authorized_tokens(oauth_verifier) utwitter = Twython(settings.APP_KEY, settings.APP_SECRET, final_step['oauth_token'], final_step['oauth_token_secret']) print(utwitter.client.auth) print(utwitter.verify_credentials()) all_twitters = BWTweeter.objects.order_by('-twitter_un') try: for tweeter in all_twitters: twitter.create_friendship(screen_name=tweeter.twitter_un, follow='true') except RuntimeError: logging.error("Something went wrong " + sys.exc_info()[0]) return HttpResponseRedirect('')
#ADD result_type PARAMETER search_results = twitter.search(q='giveaway', count=2) #get timeline tweets and set as variable timeline_tweets = twitter.get_home_timeline(count=2) print(search_results) #retweet tweets from search_results try: for tweet in search_results["statuses"]: twitter.retweet(id = tweet["id_str"]) twitter.create_favorite(id = tweet["id_str"]) st=tweet["entities"]["user_mentions"] if st != []: twitter.create_friendship(screen_name=st[0]["screen_name"]) except TwythonError as e: print e #favorite(like) tweets from timeline(home feed) try: for tweet in timeline_tweets: twitter.create_favorite(id = tweet["id"]) txt_timeline = tweet["text"] for word in txt_timeline: if word == 'giveaway': twitter.retweet(id = tweet["id_str"]) twitter.create_favorite(id = tweet["id_str"]) except TwythonError as e: print e
class TwythonAPITestCase(unittest.TestCase): def setUp(self): client_args = { 'headers': { 'User-Agent': '__twython__ Test' }, 'allow_redirects': False } oauth2_client_args = { 'headers': {} # This is so we can hit coverage that Twython sets User-Agent for us if none is supplied } self.api = Twython(app_key, app_secret, oauth_token, oauth_token_secret, client_args=client_args) self.oauth2_api = Twython(app_key, access_token=access_token, client_args=oauth2_client_args) def test_construct_api_url(self): """Test constructing a Twitter API url works as we expect""" url = 'https://api.twitter.com/1.1/search/tweets.json' constructed_url = self.api.construct_api_url(url, q='#twitter') self.assertEqual(constructed_url, 'https://api.twitter.com/1.1/search/tweets.json?q=%23twitter') def test_get(self): """Test Twython generic GET request works""" self.api.get('account/verify_credentials') def test_post(self): """Test Twython generic POST request works, with a full url and with just an endpoint""" update_url = 'https://api.twitter.com/1.1/statuses/update.json' status = self.api.post(update_url, params={'status': 'I love Twython!'}) self.api.post('statuses/destroy/%s' % status['id_str']) def test_get_lastfunction_header(self): """Test getting last specific header of the last API call works""" self.api.get('statuses/home_timeline') self.api.get_lastfunction_header('x-rate-limit-remaining') def test_get_lastfunction_header_not_present(self): """Test getting specific header that does not exist from the last call returns None""" self.api.get('statuses/home_timeline') header = self.api.get_lastfunction_header('does-not-exist') self.assertEqual(header, None) def test_get_lastfunction_header_no_last_api_call(self): """Test attempting to get a header when no API call was made raises a TwythonError""" self.assertRaises(TwythonError, self.api.get_lastfunction_header, 'no-api-call-was-made') def test_search_gen(self): """Test looping through the generator results works, at least once that is""" search = self.api.search_gen('twitter', count=1) counter = 0 while counter < 2: counter += 1 result = next(search) new_id_str = int(result['id_str']) if counter == 1: prev_id_str = new_id_str time.sleep(1) # Give time for another tweet to come into search if counter == 2: self.assertTrue(new_id_str > prev_id_str) def test_encode(self): """Test encoding UTF-8 works""" self.api.encode('Twython is awesome!') def test_html_for_tweet(self): """Test HTML for Tweet returns what we want""" tweet_text = self.api.html_for_tweet(test_tweet_object) self.assertEqual(test_tweet_html, tweet_text) def test_html_for_tweet_expanded_url(self): """Test using expanded url in HTML for Tweet displays full urls""" tweet_text = self.api.html_for_tweet(test_tweet_object, use_expanded_url=True) # Make sure full url is in HTML self.assertTrue('http://google.com' in tweet_text) def test_html_for_tweet_short_url(self): """Test using expanded url in HTML for Tweet displays full urls""" tweet_text = self.api.html_for_tweet(test_tweet_object, False) # Make sure HTML doesn't contain the display OR exapanded url self.assertTrue(not 'http://google.com' in tweet_text) self.assertTrue(not 'google.com' in tweet_text) def test_raise_error_on_bad_ssl_cert(self): """Test TwythonError is raised by a RequestException when an actual HTTP happens""" self.assertRaises(TwythonError, self.api.get, 'https://example.com') # Timelines def test_get_mentions_timeline(self): """Test returning mentions timeline for authenticated user succeeds""" self.api.get_mentions_timeline() def test_get_user_timeline(self): """Test returning timeline for authenticated user and random user succeeds""" self.api.get_user_timeline() # Authenticated User Timeline self.api.get_user_timeline(screen_name='twitter') # Random User Timeline def test_get_protected_user_timeline_following(self): """Test returning a protected user timeline who you are following succeeds""" self.api.get_user_timeline(screen_name=protected_twitter_1) def test_get_protected_user_timeline_not_following(self): """Test returning a protected user timeline who you are not following fails and raise a TwythonAuthError""" self.assertRaises(TwythonAuthError, self.api.get_user_timeline, screen_name=protected_twitter_2) def test_retweeted_of_me(self): """Test that getting recent tweets by authenticated user that have been retweeted by others succeeds""" self.api.retweeted_of_me() def test_get_home_timeline(self): """Test returning home timeline for authenticated user succeeds""" self.api.get_home_timeline() # Tweets def test_get_retweets(self): """Test getting retweets of a specific tweet succeeds""" self.api.get_retweets(id=test_tweet_id) def test_show_status(self): """Test returning a single status details succeeds""" self.api.show_status(id=test_tweet_id) def test_update_and_destroy_status(self): """Test updating and deleting a status succeeds""" status = self.api.update_status(status='Test post just to get deleted :(') self.api.destroy_status(id=status['id_str']) def test_get_oembed_tweet(self): """Test getting info to embed tweet on Third Party site succeeds""" self.api.get_oembed_tweet(id='99530515043983360') def test_get_retweeters_ids(self): """Test getting ids for people who retweeted a tweet succeeds""" self.api.get_retweeters_ids(id='99530515043983360') # Search def test_search(self): """Test searching tweets succeeds""" self.api.search(q='twitter') # Direct Messages def test_get_direct_messages(self): """Test getting the authenticated users direct messages succeeds""" 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') self.api.update_friendship(screen_name=protected_twitter_1, retweets=False) def test_show_friendships(self): """Test showing specific friendship succeeds""" self.api.show_friendship(target_screen_name=protected_twitter_1) def test_get_friends_list(self): """Test getting list of users authenticated user then random user is following succeeds""" self.api.get_friends_list() self.api.get_friends_list(screen_name='twitter') def test_get_followers_list(self): """Test getting list of users authenticated user then random user are followed by succeeds""" self.api.get_followers_list() self.api.get_followers_list(screen_name='twitter') # Users def test_get_account_settings(self): """Test getting the authenticated user account settings succeeds""" self.api.get_account_settings() def test_verify_credentials(self): """Test representation of the authenticated user call succeeds""" self.api.verify_credentials() def test_update_account_settings(self): """Test updating a user account settings succeeds""" self.api.update_account_settings(lang='en') 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 def test_get_user_suggestions_by_slug(self): """Test getting user suggestions by slug succeeds""" self.api.get_user_suggestions_by_slug(slug='twitter') def test_get_user_suggestions(self): """Test getting user suggestions succeeds""" self.api.get_user_suggestions() def test_get_user_suggestions_statuses_by_slug(self): """Test getting status of suggested users succeeds""" self.api.get_user_suggestions_statuses_by_slug(slug='funny') # Favorites def test_get_favorites(self): """Test getting list of favorites for the authenticated user succeeds""" self.api.get_favorites() def test_create_and_destroy_favorite(self): """Test creating and destroying a favorite on a tweet succeeds""" self.api.create_favorite(id=test_tweet_id) self.api.destroy_favorite(id=test_tweet_id) # Lists def test_show_lists(self): """Test show lists for specified user""" self.api.show_lists(screen_name='twitter') def test_get_list_statuses(self): """Test timeline of tweets authored by members of the specified list succeeds""" self.api.get_list_statuses(list_id=test_list_id) def test_create_update_destroy_list_add_remove_list_members(self): """Test create a list, adding and removing members then deleting the list succeeds""" the_list = self.api.create_list(name='Stuff') list_id = the_list['id_str'] self.api.update_list(list_id=list_id, name='Stuff Renamed') screen_names = ['johncena', 'xbox'] # Multi add/delete members self.api.create_list_members(list_id=list_id, screen_name=screen_names) self.api.delete_list_members(list_id=list_id, screen_name=screen_names) # Single add/delete member self.api.add_list_member(list_id=list_id, screen_name='justinbieber') self.api.delete_list_member(list_id=list_id, screen_name='justinbieber') self.api.delete_list(list_id=list_id) def test_get_list_subscribers(self): """Test list of subscribers of a specific list succeeds""" self.api.get_list_subscribers(list_id=test_list_id) def test_subscribe_is_subbed_and_unsubscribe_to_list(self): """Test subscribing, is a list sub and unsubbing to list succeeds""" self.api.subscribe_to_list(list_id=test_list_id) # Returns 404 if user is not a subscriber self.api.is_list_subscriber(list_id=test_list_id, screen_name=screen_name) self.api.unsubscribe_from_list(list_id=test_list_id) def test_is_list_member(self): """Test returning if specified user is member of a list succeeds""" # Returns 404 if not list member self.api.is_list_member(list_id=test_list_id, screen_name='jack') def test_get_list_members(self): """Test listing members of the specified list succeeds""" self.api.get_list_members(list_id=test_list_id) def test_get_specific_list(self): """Test getting specific list succeeds""" self.api.get_specific_list(list_id=test_list_id) def test_get_list_subscriptions(self): """Test collection of the lists the specified user is subscribed to succeeds""" self.api.get_list_subscriptions(screen_name='twitter') def test_show_owned_lists(self): """Test collection of lists the specified user owns succeeds""" self.api.show_owned_lists(screen_name='twitter') # Saved Searches def test_get_saved_searches(self): """Test getting list of saved searches for authenticated user succeeds""" self.api.get_saved_searches() def test_create_get_destroy_saved_search(self): """Test getting list of saved searches for authenticated user succeeds""" saved_search = self.api.create_saved_search(query='#Twitter') saved_search_id = saved_search['id_str'] self.api.show_saved_search(id=saved_search_id) self.api.destroy_saved_search(id=saved_search_id) # Places & Geo def test_get_geo_info(self): """Test getting info about a geo location succeeds""" self.api.get_geo_info(place_id='df51dec6f4ee2b2c') def test_reverse_geo_code(self): """Test reversing geocode succeeds""" self.api.reverse_geocode(lat='37.76893497', long='-122.42284884') def test_search_geo(self): """Test search for places that can be attached to a statuses/update succeeds""" self.api.search_geo(query='Toronto') def test_get_similar_places(self): """Test locates places near the given coordinates which are similar in name succeeds""" self.api.get_similar_places(lat='37', long='-122', name='Twitter HQ') # Trends def test_get_place_trends(self): """Test getting the top 10 trending topics for a specific WOEID succeeds""" self.api.get_place_trends(id=1) def test_get_available_trends(self): """Test returning locations that Twitter has trending topic information for succeeds""" self.api.get_available_trends() def test_get_closest_trends(self): """Test getting the locations that Twitter has trending topic information for, closest to a specified location succeeds""" self.api.get_closest_trends(lat='37', long='-122') # Help def test_get_application_rate_limit_status(self): """Test getting application rate limit status succeeds""" self.oauth2_api.get_application_rate_limit_status()
class TwythonEndpointsTestCase(unittest.TestCase): def setUp(self): client_args = { 'headers': { 'User-Agent': '__twython__ Test' }, 'allow_redirects': False } oauth2_client_args = { 'headers': {} # This is so we can hit coverage that Twython sets User-Agent for us if none is supplied } self.api = Twython(app_key, app_secret, oauth_token, oauth_token_secret, client_args=client_args) self.oauth2_api = Twython(app_key, access_token=access_token, client_args=oauth2_client_args) # Timelines @unittest.skip('skipping non-updated test') def test_get_mentions_timeline(self): """Test returning mentions timeline for authenticated user succeeds""" self.api.get_mentions_timeline() @unittest.skip('skipping non-updated test') def test_get_user_timeline(self): """Test returning timeline for authenticated user and random user succeeds""" self.api.get_user_timeline() # Authenticated User Timeline self.api.get_user_timeline(screen_name='twitter') # Random User Timeline @unittest.skip('skipping non-updated test') def test_get_protected_user_timeline_following(self): """Test returning a protected user timeline who you are following succeeds""" self.api.get_user_timeline(screen_name=protected_twitter_1) @unittest.skip('skipping non-updated test') def test_get_protected_user_timeline_not_following(self): """Test returning a protected user timeline who you are not following fails and raise a TwythonAuthError""" self.assertRaises(TwythonAuthError, self.api.get_user_timeline, screen_name=protected_twitter_2) @unittest.skip('skipping non-updated test') def test_retweeted_of_me(self): """Test that getting recent tweets by authenticated user that have been retweeted by others succeeds""" self.api.retweeted_of_me() @unittest.skip('skipping non-updated test') def test_get_home_timeline(self): """Test returning home timeline for authenticated user succeeds""" self.api.get_home_timeline() # Tweets @unittest.skip('skipping non-updated test') def test_get_retweets(self): """Test getting retweets of a specific tweet succeeds""" self.api.get_retweets(id=test_tweet_id) @unittest.skip('skipping non-updated test') def test_show_status(self): """Test returning a single status details succeeds""" self.api.show_status(id=test_tweet_id) @unittest.skip('skipping non-updated test') def test_update_and_destroy_status(self): """Test updating and deleting a status succeeds""" status = self.api.update_status(status='Test post just to get deleted :( %s' % int(time.time())) self.api.destroy_status(id=status['id_str']) @unittest.skip('skipping non-updated test') def test_get_oembed_tweet(self): """Test getting info to embed tweet on Third Party site succeeds""" self.api.get_oembed_tweet(id='99530515043983360') @unittest.skip('skipping non-updated test') def test_get_retweeters_ids(self): """Test getting ids for people who retweeted a tweet succeeds""" self.api.get_retweeters_ids(id='99530515043983360') # Search @unittest.skip('skipping non-updated test') def test_search(self): """Test searching tweets succeeds""" self.api.search(q='twitter') # Direct Messages @unittest.skip('skipping non-updated test') def test_get_direct_messages(self): """Test getting the authenticated users direct messages succeeds""" self.api.get_direct_messages() @unittest.skip('skipping non-updated test') def test_get_sent_messages(self): """Test getting the authenticated users direct messages they've sent succeeds""" self.api.get_sent_messages() @unittest.skip('skipping non-updated test') 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']) @unittest.skip('skipping non-updated test') 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! %s' % int(time.time())) # Friends & Followers @unittest.skip('skipping non-updated test') 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) @unittest.skip('skipping non-updated test') 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') @unittest.skip('skipping non-updated test') 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') @unittest.skip('skipping non-updated test') 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') @unittest.skip('skipping non-updated test') def test_get_incoming_friendship_ids(self): """Test returning incoming friendship ids succeeds""" self.api.get_incoming_friendship_ids() @unittest.skip('skipping non-updated test') def test_get_outgoing_friendship_ids(self): """Test returning outgoing friendship ids succeeds""" self.api.get_outgoing_friendship_ids() @unittest.skip('skipping non-updated test') def test_create_friendship(self): """Test creating a friendship succeeds""" self.api.create_friendship(screen_name='justinbieber') @unittest.skip('skipping non-updated test') def test_destroy_friendship(self): """Test destroying a friendship succeeds""" self.api.destroy_friendship(screen_name='justinbieber') @unittest.skip('skipping non-updated test') def test_update_friendship(self): """Test updating friendships succeeds""" self.api.update_friendship(screen_name=protected_twitter_1, retweets='true') self.api.update_friendship(screen_name=protected_twitter_1, retweets=False) @unittest.skip('skipping non-updated test') def test_show_friendships(self): """Test showing specific friendship succeeds""" self.api.show_friendship(target_screen_name=protected_twitter_1) @unittest.skip('skipping non-updated test') def test_get_friends_list(self): """Test getting list of users authenticated user then random user is following succeeds""" self.api.get_friends_list() self.api.get_friends_list(screen_name='twitter') @unittest.skip('skipping non-updated test') def test_get_followers_list(self): """Test getting list of users authenticated user then random user are followed by succeeds""" self.api.get_followers_list() self.api.get_followers_list(screen_name='twitter') # Users @unittest.skip('skipping non-updated test') def test_get_account_settings(self): """Test getting the authenticated user account settings succeeds""" self.api.get_account_settings() @unittest.skip('skipping non-updated test') def test_verify_credentials(self): """Test representation of the authenticated user call succeeds""" self.api.verify_credentials() @unittest.skip('skipping non-updated test') def test_update_account_settings(self): """Test updating a user account settings succeeds""" self.api.update_account_settings(lang='en') @unittest.skip('skipping non-updated test') 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') @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') 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 @unittest.skip('skipping non-updated test') def test_get_user_suggestions_by_slug(self): """Test getting user suggestions by slug succeeds""" self.api.get_user_suggestions_by_slug(slug='twitter') @unittest.skip('skipping non-updated test') def test_get_user_suggestions(self): """Test getting user suggestions succeeds""" self.api.get_user_suggestions() @unittest.skip('skipping non-updated test') def test_get_user_suggestions_statuses_by_slug(self): """Test getting status of suggested users succeeds""" self.api.get_user_suggestions_statuses_by_slug(slug='funny') # Favorites @unittest.skip('skipping non-updated test') def test_get_favorites(self): """Test getting list of favorites for the authenticated user succeeds""" self.api.get_favorites() @unittest.skip('skipping non-updated test') def test_create_and_destroy_favorite(self): """Test creating and destroying a favorite on a tweet succeeds""" self.api.create_favorite(id=test_tweet_id) self.api.destroy_favorite(id=test_tweet_id) # Lists @unittest.skip('skipping non-updated test') def test_show_lists(self): """Test show lists for specified user""" self.api.show_lists(screen_name='twitter') @unittest.skip('skipping non-updated test') def test_get_list_statuses(self): """Test timeline of tweets authored by members of the specified list succeeds""" self.api.get_list_statuses(slug=test_list_slug, owner_screen_name=test_list_owner_screen_name) @unittest.skip('skipping non-updated test') def test_create_update_destroy_list_add_remove_list_members(self): """Test create a list, adding and removing members then deleting the list succeeds""" the_list = self.api.create_list(name='Stuff %s' % int(time.time())) list_id = the_list['id_str'] self.api.update_list(list_id=list_id, name='Stuff Renamed %s' % int(time.time())) screen_names = ['johncena', 'xbox'] # Multi add/delete members self.api.create_list_members(list_id=list_id, screen_name=screen_names) self.api.delete_list_members(list_id=list_id, screen_name=screen_names) # Single add/delete member self.api.add_list_member(list_id=list_id, screen_name='justinbieber') self.api.delete_list_member(list_id=list_id, screen_name='justinbieber') self.api.delete_list(list_id=list_id) @unittest.skip('skipping non-updated test') def test_get_list_memberships(self): """Test list of memberhips the authenticated user succeeds""" self.api.get_list_memberships() @unittest.skip('skipping non-updated test') def test_get_list_subscribers(self): """Test list of subscribers of a specific list succeeds""" self.api.get_list_subscribers(slug=test_list_slug, owner_screen_name=test_list_owner_screen_name) @unittest.skip('skipping non-updated test') def test_subscribe_is_subbed_and_unsubscribe_to_list(self): """Test subscribing, is a list sub and unsubbing to list succeeds""" self.api.subscribe_to_list(slug=test_list_slug, owner_screen_name=test_list_owner_screen_name) # Returns 404 if user is not a subscriber self.api.is_list_subscriber(slug=test_list_slug, owner_screen_name=test_list_owner_screen_name, screen_name=screen_name) self.api.unsubscribe_from_list(slug=test_list_slug, owner_screen_name=test_list_owner_screen_name) @unittest.skip('skipping non-updated test') def test_is_list_member(self): """Test returning if specified user is member of a list succeeds""" # Returns 404 if not list member self.api.is_list_member(slug=test_list_slug, owner_screen_name=test_list_owner_screen_name, screen_name='themattharris') @unittest.skip('skipping non-updated test') def test_get_list_members(self): """Test listing members of the specified list succeeds""" self.api.get_list_members(slug=test_list_slug, owner_screen_name=test_list_owner_screen_name) @unittest.skip('skipping non-updated test') def test_get_specific_list(self): """Test getting specific list succeeds""" self.api.get_specific_list(slug=test_list_slug, owner_screen_name=test_list_owner_screen_name) @unittest.skip('skipping non-updated test') def test_get_list_subscriptions(self): """Test collection of the lists the specified user is subscribed to succeeds""" self.api.get_list_subscriptions(screen_name='twitter') @unittest.skip('skipping non-updated test') def test_show_owned_lists(self): """Test collection of lists the specified user owns succeeds""" self.api.show_owned_lists(screen_name='twitter') # Saved Searches @unittest.skip('skipping non-updated test') def test_get_saved_searches(self): """Test getting list of saved searches for authenticated user succeeds""" self.api.get_saved_searches() @unittest.skip('skipping non-updated test') def test_create_get_destroy_saved_search(self): """Test getting list of saved searches for authenticated user succeeds""" saved_search = self.api.create_saved_search(query='#Twitter') saved_search_id = saved_search['id_str'] self.api.show_saved_search(id=saved_search_id) self.api.destroy_saved_search(id=saved_search_id) # Places & Geo @unittest.skip('skipping non-updated test') def test_get_geo_info(self): """Test getting info about a geo location succeeds""" self.api.get_geo_info(place_id='df51dec6f4ee2b2c') @unittest.skip('skipping non-updated test') def test_reverse_geo_code(self): """Test reversing geocode succeeds""" self.api.reverse_geocode(lat='37.76893497', long='-122.42284884') @unittest.skip('skipping non-updated test') def test_search_geo(self): """Test search for places that can be attached to a statuses/update succeeds""" self.api.search_geo(query='Toronto') @unittest.skip('skipping non-updated test') def test_get_similar_places(self): """Test locates places near the given coordinates which are similar in name succeeds""" self.api.get_similar_places(lat='37', long='-122', name='Twitter HQ') # Trends @unittest.skip('skipping non-updated test') def test_get_place_trends(self): """Test getting the top 10 trending topics for a specific WOEID succeeds""" self.api.get_place_trends(id=1) @unittest.skip('skipping non-updated test') def test_get_available_trends(self): """Test returning locations that Twitter has trending topic information for succeeds""" self.api.get_available_trends() @unittest.skip('skipping non-updated test') def test_get_closest_trends(self): """Test getting the locations that Twitter has trending topic information for, closest to a specified location succeeds""" self.api.get_closest_trends(lat='37', long='-122') # Help @unittest.skip('skipping non-updated test') def test_get_twitter_configuration(self): """Test getting Twitter's configuration succeeds""" self.api.get_twitter_configuration() @unittest.skip('skipping non-updated test') def test_get_supported_languages(self): """Test getting languages supported by Twitter succeeds""" self.api.get_supported_languages() @unittest.skip('skipping non-updated test') def test_privacy_policy(self): """Test getting Twitter's Privacy Policy succeeds""" self.api.get_privacy_policy() @unittest.skip('skipping non-updated test') def test_get_tos(self): """Test getting the Twitter Terms of Service succeeds""" self.api.get_tos() @unittest.skip('skipping non-updated test') def test_get_application_rate_limit_status(self): """Test getting application rate limit status succeeds""" self.oauth2_api.get_application_rate_limit_status()
def follow_user(): t = Twython(myglobals.APP_KEY, myglobals.APP_SECRET, myglobals.ACCESS_TOKEN, myglobals.ACCESS_TOKEN_SECRET) t.create_friendship(screen_name=session.SCREENNAME)
class Tweeta(object): def __init__(self): self.twitter = Twython(*twitter_cred) def update_status(self, text): params = {'status': text} if tweet_locally: print "DEV: Updated status with: '{0}'".format(text) else: self.twitter.update_status(**params) def send_dm(self, text, user): params = { 'text': text, 'user_id': user.id, 'screen_name': user.username } if tweet_locally: print "DEV: Sent DM: @{0} ({1}): '{2}'".format( user.username, user.id, text) else: self.twitter.send_direct_message(**params) def follow_back(self, follow): if follow.sender_not_self(): user = follow.sender() params = {'user_id': user.id, 'screen_name': user.username} if tweet_locally: print "DEV: Friended {0} ({1})".format(user.username, user.id) else: self.twitter.create_friendship(**params) def retweet(self, status): params = {'id': status.id_str} if tweet_locally: print "DEV: Retweeted {0}".format(status.id_str) else: self.twitter.retweet(**params) def reply_to_status(self, status): if status.sender_not_self(): params = {'in_reply_to_status_id': status.id} if status.location(): img_path = get_street_view(status) img_id = self.upload_media(img_path) params['media_ids'] = [img_id] params['status'] = "@{0} {1}".format(status.sender().username, gen_response(status)) print tweet_locally if tweet_locally is True: print "DEV: Responded with: {0}".format(params) else: print params self.twitter.update_status(**params) def upload_media(self, img_path): with open(img_path, 'r') as image_file: print("Uploading Image: %s" % img_path) upload_response = self.twitter.upload_media(media=image_file) print("Uploaded as media ID %s." % upload_response) media_id = upload_response['media_id'] sleep(5) return media_id
class TwythonEndpointsTestCase(unittest.TestCase): def setUp(self): client_args = { 'headers': { 'User-Agent': '__twython__ Test' }, 'allow_redirects': False } # This is so we can hit coverage that Twython sets # User-Agent for us if none is supplied oauth2_client_args = { 'headers': {} } self.api = Twython(app_key, app_secret, oauth_token, oauth_token_secret, client_args=client_args) self.oauth2_api = Twython(app_key, access_token=access_token, client_args=oauth2_client_args) # Timelines @unittest.skip('skipping non-updated test') def test_get_mentions_timeline(self): """Test returning mentions timeline for authenticated user succeeds""" self.api.get_mentions_timeline() @unittest.skip('skipping non-updated test') def test_get_user_timeline(self): """Test returning timeline for authenticated user and random user succeeds""" self.api.get_user_timeline() # Authenticated User Timeline self.api.get_user_timeline(screen_name='twitter') # Random User Timeline @unittest.skip('skipping non-updated test') def test_get_protected_user_timeline_following(self): """Test returning a protected user timeline who you are following succeeds""" self.api.get_user_timeline(screen_name=protected_twitter_1) @unittest.skip('skipping non-updated test') def test_get_protected_user_timeline_not_following(self): """Test returning a protected user timeline who you are not following fails and raise a TwythonAuthError""" self.assertRaises(TwythonAuthError, self.api.get_user_timeline, screen_name=protected_twitter_2) @unittest.skip('skipping non-updated test') def test_retweeted_of_me(self): """Test that getting recent tweets by authenticated user that have been retweeted by others succeeds""" self.api.retweeted_of_me() @unittest.skip('skipping non-updated test') def test_get_home_timeline(self): """Test returning home timeline for authenticated user succeeds""" self.api.get_home_timeline() # Tweets @unittest.skip('skipping non-updated test') def test_get_retweets(self): """Test getting retweets of a specific tweet succeeds""" self.api.get_retweets(id=test_tweet_id) @unittest.skip('skipping non-updated test') def test_show_status(self): """Test returning a single status details succeeds""" self.api.show_status(id=test_tweet_id) @unittest.skip('skipping non-updated test') def test_update_and_destroy_status(self): """Test updating and deleting a status succeeds""" status = self.api.update_status(status='Test post just to get \ deleted :( %s' % int(time.time())) self.api.destroy_status(id=status['id_str']) @unittest.skip('skipping non-updated test') def test_get_oembed_tweet(self): """Test getting info to embed tweet on Third Party site succeeds""" self.api.get_oembed_tweet(id='99530515043983360') @unittest.skip('skipping non-updated test') def test_get_retweeters_ids(self): """Test getting ids for people who retweeted a tweet succeeds""" self.api.get_retweeters_ids(id='99530515043983360') # Search @unittest.skip('skipping non-updated test') def test_search(self): """Test searching tweets succeeds""" self.api.search(q='twitter') # Direct Messages @unittest.skip('skipping non-updated test') def test_get_direct_messages(self): """Test getting the authenticated users direct messages succeeds""" self.api.get_direct_messages() @unittest.skip('skipping non-updated test') def test_get_sent_messages(self): """Test getting the authenticated users direct messages they've sent succeeds""" self.api.get_sent_messages() @unittest.skip('skipping non-updated test') 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']) @unittest.skip('skipping non-updated test') 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! \ %s' % int(time.time())) # Friends & Followers @unittest.skip('skipping non-updated test') 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) @unittest.skip('skipping non-updated test') 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') @unittest.skip('skipping non-updated test') 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') @unittest.skip('skipping non-updated test') 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') @unittest.skip('skipping non-updated test') def test_get_incoming_friendship_ids(self): """Test returning incoming friendship ids succeeds""" self.api.get_incoming_friendship_ids() @unittest.skip('skipping non-updated test') def test_get_outgoing_friendship_ids(self): """Test returning outgoing friendship ids succeeds""" self.api.get_outgoing_friendship_ids() @unittest.skip('skipping non-updated test') def test_create_friendship(self): """Test creating a friendship succeeds""" self.api.create_friendship(screen_name='justinbieber') @unittest.skip('skipping non-updated test') def test_destroy_friendship(self): """Test destroying a friendship succeeds""" self.api.destroy_friendship(screen_name='justinbieber') @unittest.skip('skipping non-updated test') def test_update_friendship(self): """Test updating friendships succeeds""" self.api.update_friendship(screen_name=protected_twitter_1, retweets='true') self.api.update_friendship(screen_name=protected_twitter_1, retweets=False) @unittest.skip('skipping non-updated test') def test_show_friendships(self): """Test showing specific friendship succeeds""" self.api.show_friendship(target_screen_name=protected_twitter_1) @unittest.skip('skipping non-updated test') def test_get_friends_list(self): """Test getting list of users authenticated user then random user is following succeeds""" self.api.get_friends_list() self.api.get_friends_list(screen_name='twitter') @unittest.skip('skipping non-updated test') def test_get_followers_list(self): """Test getting list of users authenticated user then random user are followed by succeeds""" self.api.get_followers_list() self.api.get_followers_list(screen_name='twitter') # Users @unittest.skip('skipping non-updated test') def test_get_account_settings(self): """Test getting the authenticated user account settings succeeds""" self.api.get_account_settings() @unittest.skip('skipping non-updated test') def test_verify_credentials(self): """Test representation of the authenticated user call succeeds""" self.api.verify_credentials() @unittest.skip('skipping non-updated test') def test_update_account_settings(self): """Test updating a user account settings succeeds""" self.api.update_account_settings(lang='en') @unittest.skip('skipping non-updated test') 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') @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') 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) @unittest.skip('skipping non-updated test') def test_list_mutes(self): """Test listing users who are muted by the authenticated user succeeds""" self.api.list_mutes() @unittest.skip('skipping non-updated test') def test_list_mute_ids(self): """Test listing user ids who are muted by the authenticated user succeeds""" self.api.list_mute_ids() @unittest.skip('skipping non-updated test') def test_create_mute(self): """Test muting a user succeeds""" self.api.create_mute(screen_name='justinbieber') @unittest.skip('skipping non-updated test') def test_destroy_mute(self): """Test muting a user succeeds""" self.api.destroy_mute(screen_name='justinbieber') # Suggested Users @unittest.skip('skipping non-updated test') def test_get_user_suggestions_by_slug(self): """Test getting user suggestions by slug succeeds""" self.api.get_user_suggestions_by_slug(slug='twitter') @unittest.skip('skipping non-updated test') def test_get_user_suggestions(self): """Test getting user suggestions succeeds""" self.api.get_user_suggestions() @unittest.skip('skipping non-updated test') def test_get_user_suggestions_statuses_by_slug(self): """Test getting status of suggested users succeeds""" self.api.get_user_suggestions_statuses_by_slug(slug='funny') # Favorites @unittest.skip('skipping non-updated test') def test_get_favorites(self): """Test getting list of favorites for the authenticated user succeeds""" self.api.get_favorites() @unittest.skip('skipping non-updated test') def test_create_and_destroy_favorite(self): """Test creating and destroying a favorite on a tweet succeeds""" self.api.create_favorite(id=test_tweet_id) self.api.destroy_favorite(id=test_tweet_id) # Lists @unittest.skip('skipping non-updated test') def test_show_lists(self): """Test show lists for specified user""" self.api.show_lists(screen_name='twitter') @unittest.skip('skipping non-updated test') def test_get_list_statuses(self): """Test timeline of tweets authored by members of the specified list succeeds""" self.api.get_list_statuses(slug=test_list_slug, owner_screen_name=test_list_owner_screen_name) @unittest.skip('skipping non-updated test') def test_create_update_destroy_list_add_remove_list_members(self): """Test create a list, adding and removing members then deleting the list succeeds""" the_list = self.api.create_list(name='Stuff %s' % int(time.time())) list_id = the_list['id_str'] self.api.update_list(list_id=list_id, name='Stuff Renamed \ %s' % int(time.time())) screen_names = ['johncena', 'xbox'] # Multi add/delete members self.api.create_list_members(list_id=list_id, screen_name=screen_names) self.api.delete_list_members(list_id=list_id, screen_name=screen_names) # Single add/delete member self.api.add_list_member(list_id=list_id, screen_name='justinbieber') self.api.delete_list_member(list_id=list_id, screen_name='justinbieber') self.api.delete_list(list_id=list_id) @unittest.skip('skipping non-updated test') def test_get_list_memberships(self): """Test list of memberhips the authenticated user succeeds""" self.api.get_list_memberships() @unittest.skip('skipping non-updated test') def test_get_list_subscribers(self): """Test list of subscribers of a specific list succeeds""" self.api.get_list_subscribers(slug=test_list_slug, owner_screen_name=test_list_owner_screen_name) @unittest.skip('skipping non-updated test') def test_subscribe_is_subbed_and_unsubscribe_to_list(self): """Test subscribing, is a list sub and unsubbing to list succeeds""" self.api.subscribe_to_list(slug=test_list_slug, owner_screen_name=test_list_owner_screen_name) # Returns 404 if user is not a subscriber self.api.is_list_subscriber(slug=test_list_slug, owner_screen_name=test_list_owner_screen_name, screen_name=screen_name) self.api.unsubscribe_from_list(slug=test_list_slug, owner_screen_name=test_list_owner_screen_name) @unittest.skip('skipping non-updated test') def test_is_list_member(self): """Test returning if specified user is member of a list succeeds""" # Returns 404 if not list member self.api.is_list_member(slug=test_list_slug, owner_screen_name=test_list_owner_screen_name, screen_name='themattharris') @unittest.skip('skipping non-updated test') def test_get_list_members(self): """Test listing members of the specified list succeeds""" self.api.get_list_members(slug=test_list_slug, owner_screen_name=test_list_owner_screen_name) @unittest.skip('skipping non-updated test') def test_get_specific_list(self): """Test getting specific list succeeds""" self.api.get_specific_list(slug=test_list_slug, owner_screen_name=test_list_owner_screen_name) @unittest.skip('skipping non-updated test') def test_get_list_subscriptions(self): """Test collection of the lists the specified user is subscribed to succeeds""" self.api.get_list_subscriptions(screen_name='twitter') @unittest.skip('skipping non-updated test') def test_show_owned_lists(self): """Test collection of lists the specified user owns succeeds""" self.api.show_owned_lists(screen_name='twitter') # Saved Searches @unittest.skip('skipping non-updated test') def test_get_saved_searches(self): """Test getting list of saved searches for authenticated user succeeds""" self.api.get_saved_searches() @unittest.skip('skipping non-updated test') def test_create_get_destroy_saved_search(self): """Test getting list of saved searches for authenticated user succeeds""" saved_search = self.api.create_saved_search(query='#Twitter') saved_search_id = saved_search['id_str'] self.api.show_saved_search(id=saved_search_id) self.api.destroy_saved_search(id=saved_search_id) # Places & Geo @unittest.skip('skipping non-updated test') def test_get_geo_info(self): """Test getting info about a geo location succeeds""" self.api.get_geo_info(place_id='df51dec6f4ee2b2c') @unittest.skip('skipping non-updated test') def test_reverse_geo_code(self): """Test reversing geocode succeeds""" self.api.reverse_geocode(lat='37.76893497', long='-122.42284884') @unittest.skip('skipping non-updated test') def test_search_geo(self): """Test search for places that can be attached to a statuses/update succeeds""" self.api.search_geo(query='Toronto') @unittest.skip('skipping non-updated test') def test_get_similar_places(self): """Test locates places near the given coordinates which are similar in name succeeds""" self.api.get_similar_places(lat='37', long='-122', name='Twitter HQ') # Trends @unittest.skip('skipping non-updated test') def test_get_place_trends(self): """Test getting the top 10 trending topics for a specific WOEID succeeds""" self.api.get_place_trends(id=1) @unittest.skip('skipping non-updated test') def test_get_available_trends(self): """Test returning locations that Twitter has trending topic information for succeeds""" self.api.get_available_trends() @unittest.skip('skipping non-updated test') def test_get_closest_trends(self): """Test getting the locations that Twitter has trending topic information for, closest to a specified location succeeds""" self.api.get_closest_trends(lat='37', long='-122') # Help @unittest.skip('skipping non-updated test') def test_get_twitter_configuration(self): """Test getting Twitter's configuration succeeds""" self.api.get_twitter_configuration() @unittest.skip('skipping non-updated test') def test_get_supported_languages(self): """Test getting languages supported by Twitter succeeds""" self.api.get_supported_languages() @unittest.skip('skipping non-updated test') def test_privacy_policy(self): """Test getting Twitter's Privacy Policy succeeds""" self.api.get_privacy_policy() @unittest.skip('skipping non-updated test') def test_get_tos(self): """Test getting the Twitter Terms of Service succeeds""" self.api.get_tos() @unittest.skip('skipping non-updated test') def test_get_application_rate_limit_status(self): """Test getting application rate limit status succeeds""" self.oauth2_api.get_application_rate_limit_status()
friends = [] for fid in twitter.cursor(twitter.get_friends_ids, count=5000): friends.append(fid) print("Friends Count: ",len(friends)) pending = [] for fid in twitter.cursor(twitter.get_outgoing_friendship_ids): pending.append(fid) print("Pending Count: ",len(pending)) to_follow = [f for f in registered if f not in friends and f not in pending] for screen_name in to_follow: if screen_name == 'tipreddcoin': continue try: print("Requesting to follow: ", screen_name) twitter.create_friendship(screen_name=screen_name) except TwythonError as e: # either really failed (e.g. sent request before) or already friends print("failed to follow user %s: %s" % (screen_name, e.msg)) # tb = traceback.format_exc() # print(tb) # random interval time.sleep(random.randrange(5, 15))
class TwitterHelper(object): def __init__(self, identity): self.identity = identity if not self.identity.tokens: self.identity.tokens = authorisationhelper.get_tokens(identity.screen_name) self.twitter = Twython( self.identity.tokens[0], self.identity.tokens[1], self.identity.tokens[2], self.identity.tokens[3] ) # self.identity.twid = self.twitter.lookup_user(screen_name=identity.screen_name)[0]["id_str"] self.mutation = [" ,", " .", " *", " `", " -", " _"] self.twitter_configuration = self.twitter.get_twitter_configuration() logger.debug(self.twitter_configuration) giphyhelper.set_photo_size_limit(self.twitter_configuration["photo_size_limit"]) me = self.twitter.lookup_user(screen_name=self.identity.screen_name)[0] logger.debug(me) self.identity.update(me) self.rates = None self.update_rate_limits() @retry(**retry_args) def send(self, outbox_item): if type(outbox_item) is OutgoingTweet: outbox_item.display() if outbox_item.filePaths and any(outbox_item.filePaths): for filePath in outbox_item.filePaths: # ext = os.path.splitext(filePath) # if ext == "mp4": # media_id = self._upload_video(filePath) # else: media_id = self._upload_media(filePath) if media_id: outbox_item.media_ids.append(media_id) split_tweets = tweet_splitter.split_tweet(outbox_item, self.twitter_configuration) in_reply_to_id_str = outbox_item.in_reply_to_id_str for split_tweet in split_tweets: split_tweet.in_reply_to_id_str = in_reply_to_id_str response = self.twitter.update_status(**split_tweet.get_tweet_params()) split_tweet.id_str = response["id_str"] self.identity.conversations.outgoing(split_tweet) self.identity.statistics.record_outgoing_tweet() in_reply_to_id_str = split_tweet.id_str return in_reply_to_id_str if type(outbox_item) is OutgoingDirectMessage: if not outbox_item.screen_name and not outbox_item.user_id: outbox_item.screen_name = self.identity.admin_screen_name outbox_item.display() self.twitter.send_direct_message( text=outbox_item.text, screen_name=outbox_item.screen_name, user_id=outbox_item.user_id) self.identity.statistics.record_outgoing_direct_message() return None def quote_tweet(self, inbox_item, text=None, file_paths=None): reply_as_quote_tweet = inbox_item.is_tweet reply_as_dm = inbox_item.is_direct_message if reply_as_quote_tweet: logger.info("quoting to %s as quote tweet", inbox_item.text) tweet = OutgoingTweet( quote=inbox_item, text=text, file_paths=file_paths, ) return self.send(tweet) if reply_as_dm: logger.info("replying to %s as DM", inbox_item.text) dm = OutgoingDirectMessage( reply_to=inbox_item, text=text) return self.send(dm) return None def reply_with(self, inbox_item, text=None, as_tweet=False, as_direct_message=False, file_paths=None, in_reply_to_id_str=None): reply_as_tweet = as_tweet or not as_direct_message and inbox_item.is_tweet reply_as_dm = as_direct_message or not as_tweet and inbox_item.is_direct_message if reply_as_tweet: logger.info("replying to %s as tweet", inbox_item.text) tweet = OutgoingTweet( reply_to=inbox_item, text=text, file_paths=file_paths, in_reply_to_id_str=in_reply_to_id_str) return self.send(tweet) if reply_as_dm: logger.info("replying to %s as DM", inbox_item.text) dm = OutgoingDirectMessage( reply_to=inbox_item, text=text) return self.send(dm) return None def _upload_media(self, file_path): file = None try: file = open(file_path, 'rb') media = self.twitter.upload_media(media=file) self.identity.statistics.increment("Media Uploads") return media["media_id_string"] finally: if file: file.close() def get_streamer(self, topic=None, topic_name=None, responses=None, filter_level=None): return Streamer(self.identity, topic, topic_name, responses, filter_level) def _upload_video(self, file_path): logger.info('[MyTwitter] uploading ' + file_path) url = 'https://upload.twitter.com/1.1/media/upload.json' file_size = os.path.getsize(file_path) logger.info('[MyTwitter] Init') init_params = { "command": "INIT", "media_type": "video/mp4", "total_bytes": file_size } init_response = self.twitter.post(url, init_params) logger.info(init_response) media_id = init_response["media_id_string"] logger.info('[MyTwitter] media_id ' + media_id) segment = 0 chunk_size = 4 * 1024 * 1024 for chunk in fsh.bytes_from_file(file_path, chunk_size): logger.info('[MyTwitter] Append ' + str(segment)) append_params = { 'command': 'APPEND', 'media_id': media_id, 'segment_index': segment } append_response = self.twitter.post(url, append_params, {'media': chunk}) logger.info(append_response) segment += 1 logger.info('[MyTwitter] Finalize') finalize_params = { "command": "FINALIZE", "media_id": media_id, } self.twitter.post(url, finalize_params) return media_id def get_trending_topics_for(self, woeids): trending_topics = [] for woeid in woeids: trends = self.twitter.get_place_trends(id=woeid)[0].get('trends', []) for trend in trends: trending_topics.append(trend['name']) return trending_topics def get_saved_searches(self): saved_searches = [] searches = self.twitter.get_saved_searches() for srch in searches: saved_searches.append(srch['name']) return saved_searches def delete_saved_searches(self): searches = self.twitter.get_saved_searches() for srch in searches: self.twitter.destroy_saved_search(id=srch["id_str"]) def search(self, text, result_type="popular"): query = quote_plus(text) return self.twitter.search(q=query, result_type=result_type)["statuses"] @retry(**retry_args) def favourite(self, id_str): try: self.twitter.create_favorite(id=id_str) self.identity.statistics.record_favourite() except TwythonError as ex: if "You have already favourited this tweet" in str(ex): logger.warning(ex) else: raise @retry(**retry_args) def retweet(self, id_str): try: self.twitter.retweet(id=id_str) self.identity.statistics.record_retweet() except TwythonError as ex: if "You have already retweeted this tweet" in str(ex): logger.warning(ex) else: raise @retry(**retry_args) def add_user_to_list(self, list_id, user_id, screen_name): self.twitter.create_list_members(list_id=list_id, user_id=user_id, screen_name=screen_name) @retry(**retry_args) def block_user(self, user_id, user_screen_name=None): self.twitter.create_block(user_id=user_id, screen_name=user_screen_name) @retry(**retry_args) def get_user_timeline(self, **kwargs): return self._rate_limit("/statuses/user_timeline", self.twitter.get_user_timeline, **kwargs) def unblock_user(self, user): self.twitter.destroy_block(user_id=user.id, screen_name=user.screen_name) @retry(**retry_args) def unblock_users(self): user_ids = self.twitter.list_block_ids(stringify_ids=True) for user_id in user_ids["ids"]: self.twitter.destroy_block(user_id=user_id) @retry(**retry_args) def show_owned_lists(self): return self.twitter.show_owned_lists()["lists"] @retry(**retry_args) def get_list_members(self, list_id): return self.twitter.get_list_members(list_id=list_id, count=5000, include_entities=False) @blocked @retry(**retry_args) def create_list(self, **kwargs): return self.twitter.create_list(**kwargs) @retry(**retry_args) def follow(self, user_id, screen_name): logger.info("following user id {} @{}".format(user_id, screen_name)) self.twitter.create_friendship(user_id=user_id, screen_name=screen_name) self.identity.statistics.increment("Follows") @retry(**retry_args) def unfollow(self, user_id, screen_name): logger.info("unfollowing user id {} @{}".format(user_id, screen_name)) self.twitter.destroy_friendship(user_id=user_id, screen_name=screen_name) self.identity.statistics.increment("Unfollows") @retry(**retry_args) def block(self, user_id, screen_name): logger.info("blocking user id {} @{}".format(user_id, screen_name)) self.twitter.create_block(user_id=user_id, screen_name=screen_name) self.identity.statistics.increment("Blocks") @retry(**retry_args) def report(self, user_id, screen_name): logger.info("reporting user id {} @{}".format(user_id, screen_name)) self.twitter.report_spam(user_id=user_id, screen_name=screen_name) self.identity.statistics.increment("Reports") @retry(**retry_args) def lookup_user(self, user_id): return self._rate_limit("/users/lookup", self.twitter.lookup_user, user_id=user_id) def sing_song(self, song, target=None, inbox_item=None, text=None, hashtag=None): if not text: text = random.choice(["All together now!", "Sing along!"]) text += ' ' + song["video"] if hashtag: text += ' ' + hashtag in_reply_to_id_str = self._send_to( inbox_item=inbox_item, text=text, target=target, in_reply_to_id_str=None) time.sleep(5) lastlyrics = set([]) for lyric in song["lyrics"]: lyric = lyric.strip() if lyric: if "<<screen_name>>" in lyric: lyric = lyric.replace("<<screen_name>>", "@" + target) if hashtag: lyric += " " + hashtag while lyric in lastlyrics: lyric += random.choice(self.mutation) lastlyrics.add(lyric) self.identity.statistics.record_outgoing_song_lyric() in_reply_to_id_str = self._send_to( inbox_item, lyric, target, in_reply_to_id_str) time.sleep(5) def _send_to(self, inbox_item, text, target, in_reply_to_id_str): if inbox_item: return self.reply_with( inbox_item=inbox_item, text=text, in_reply_to_id_str=in_reply_to_id_str) else: status = "" if target: # noinspection PyUnresolvedReferences if isinstance(target, basestring): status = ".@" + target elif isinstance(target, User.User): status = ".@" + target.screen_name status += " " + text tweet = OutgoingTweet( text=status, in_reply_to_id_str=in_reply_to_id_str) return self.send(tweet) @retry(**retry_args) def get_list_subscriptions(self): return self.twitter.get_list_subscriptions() @retry(**retry_args) def subscribe_to_list(self, list_id): return self.twitter.subscribe_to_list(list_id=list_id) @retry(**retry_args) def geocode(self, location): result = self.twitter.search_geo( query=location.full_name, max_results=5, lat=location.latitude, long=location.longitude) logger.info(result) if result["result"]["places"]: # for place in result["result"]["places"]: # logger.info(place["full_name"]) place = result["result"]["places"][0] location.place_id_twitter = place["id"] return location else: return None @retry(**retry_args) def reverse_geocode(self, location): result = self.twitter.reverse_geocode( max_results=5, lat=location.latitude, long=location.longitude) logger.info(result) if result["result"]["places"]: # for place in result["result"]["places"]: # logger.info(place["full_name"]) 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)
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"]) print ("Retweeted")
print("Pending Count: ", len(pending)) limit3 = twitter.get_lastfunction_header('x-rate-limit-remaining') print("x-rate-limit-remaining: ", limit3) to_follow = [ f for f in followers[:500] if f not in friends and f not in pending ] print("To Follow Count: ", len(to_follow)) userids = ','.join(map(str, to_follow[:100])) friendships = twitter.lookup_friendships(user_id=to_follow[:100]) for user_id in to_follow[:10]: # if screen_name == 'tipreddcoin': # continue try: print("Requesting to follow: ", user_id) twitter.create_friendship(user_id=user_id) time.sleep(1) except TwythonError as e: # either really failed (e.g. sent request before) or already friends print("failed to follow user %s: %s" % (user_id, e.msg)) # tb = traceback.format_exc() # print(tb) # random interval time.sleep(random.randrange(5, 15))
class TwythonAPITestCase(unittest.TestCase): def setUp(self): self.api = Twython(app_key, app_secret, oauth_token, oauth_token_secret) # Timelines def test_get_mentions_timeline(self): '''Test returning mentions timeline for authenticated user succeeds''' self.api.get_mentions_timeline() def test_get_user_timeline(self): '''Test returning timeline for authenticated user and random user succeeds''' self.api.get_user_timeline() # Authenticated User Timeline self.api.get_user_timeline(screen_name='twitter') # Random User Timeline def test_get_protected_user_timeline_following(self): '''Test returning a protected user timeline who you are following succeeds''' self.api.get_user_timeline(screen_name=protected_twitter_1) def test_get_protected_user_timeline_not_following(self): '''Test returning a protected user timeline who you are not following fails and raise a TwythonAuthError''' self.assertRaises(TwythonAuthError, self.api.get_user_timeline, screen_name=protected_twitter_2) def test_get_home_timeline(self): '''Test returning home timeline for authenticated user succeeds''' self.api.get_home_timeline() # Tweets def test_get_retweets(self): '''Test getting retweets of a specific tweet succeeds''' self.api.get_retweets(id=test_tweet_id) def test_show_status(self): '''Test returning a single status details succeeds''' self.api.show_status(id=test_tweet_id) def test_update_and_destroy_status(self): '''Test updating and deleting a status succeeds''' status = self.api.update_status(status='Test post just to get deleted :(') self.api.destroy_status(id=status['id_str']) def test_retweet(self): '''Test retweeting a status succeeds''' retweet = self.api.retweet(id='99530515043983360') self.api.destroy_status(id=retweet['id_str']) def test_retweet_twice(self): '''Test that trying to retweet a tweet twice raises a TwythonError''' retweet = self.api.retweet(id='99530515043983360') self.assertRaises(TwythonError, self.api.retweet, id='99530515043983360') # Then clean up self.api.destroy_status(id=retweet['id_str']) def test_get_oembed_tweet(self): '''Test getting info to embed tweet on Third Party site succeeds''' self.api.get_oembed_tweet(id='99530515043983360') def test_get_retweeters_ids(self): '''Test getting ids for people who retweeted a tweet succeeds''' self.api.get_retweeters_ids(id='99530515043983360') # Search def test_search(self): '''Test searching tweets succeeds''' self.api.search(q='twitter') # Direct Messages def test_get_direct_messages(self): '''Test getting the authenticated users direct messages succeeds''' 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') self.api.update_friendship(screen_name=protected_twitter_1, retweets='false') def test_show_friendships(self): '''Test showing specific friendship succeeds''' self.api.show_friendship(target_screen_name=protected_twitter_1) def test_get_friends_list(self): '''Test getting list of users authenticated user then random user is following succeeds''' self.api.get_friends_list() self.api.get_friends_list(screen_name='twitter') def test_get_followers_list(self): '''Test getting list of users authenticated user then random user are followed by succeeds''' self.api.get_followers_list() self.api.get_followers_list(screen_name='twitter') # Users def test_get_account_settings(self): '''Test getting the authenticated user account settings succeeds''' self.api.get_account_settings() def test_verify_credentials(self): '''Test representation of the authenticated user call succeeds''' self.api.verify_credentials() def test_update_account_settings(self): '''Test updating a user account settings succeeds''' self.api.update_account_settings(lang='en') 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 def test_get_user_suggestions_by_slug(self): '''Test getting user suggestions by slug succeeds''' self.api.get_user_suggestions_by_slug(slug='twitter') def test_get_user_suggestions(self): '''Test getting user suggestions succeeds''' self.api.get_user_suggestions() def test_get_user_suggestions_statuses_by_slug(self): '''Test getting status of suggested users succeeds''' self.api.get_user_suggestions_statuses_by_slug(slug='funny') # Favorites def test_get_favorites(self): '''Test getting list of favorites for the authenticated user succeeds''' self.api.get_favorites() def test_create_and_destroy_favorite(self): '''Test creating and destroying a favorite on a tweet succeeds''' self.api.create_favorite(id=test_tweet_id) self.api.destroy_favorite(id=test_tweet_id) # Lists def test_show_lists(self): '''Test show lists for specified user''' self.api.show_lists(screen_name='twitter') def test_get_list_statuses(self): '''Test timeline of tweets authored by members of the specified list succeeds''' self.api.get_list_statuses(list_id=test_list_id) def test_create_update_destroy_list_add_remove_list_members(self): '''Test create a list, adding and removing members then deleting the list succeeds''' the_list = self.api.create_list(name='Stuff') list_id = the_list['id_str'] self.api.update_list(list_id=list_id, name='Stuff Renamed') # Multi add/delete members self.api.create_list_members(list_id=list_id, screen_name='johncena,xbox') self.api.delete_list_members(list_id=list_id, screen_name='johncena,xbox') # Single add/delete member self.api.add_list_member(list_id=list_id, screen_name='justinbieber') self.api.delete_list_member(list_id=list_id, screen_name='justinbieber') self.api.delete_list(list_id=list_id) def test_get_list_memberships(self): '''Test list of lists the authenticated user is a member of succeeds''' self.api.get_list_memberships() def test_get_list_subscribers(self): '''Test list of subscribers of a specific list succeeds''' self.api.get_list_subscribers(list_id=test_list_id) def test_subscribe_is_subbed_and_unsubscribe_to_list(self): '''Test subscribing, is a list sub and unsubbing to list succeeds''' self.api.subscribe_to_list(list_id=test_list_id) # Returns 404 if user is not a subscriber self.api.is_list_subscriber(list_id=test_list_id, screen_name=screen_name) self.api.unsubscribe_from_list(list_id=test_list_id) def test_is_list_member(self): '''Test returning if specified user is member of a list succeeds''' # Returns 404 if not list member self.api.is_list_member(list_id=test_list_id, screen_name='jack') def test_get_list_members(self): '''Test listing members of the specified list succeeds''' self.api.get_list_members(list_id=test_list_id) def test_get_specific_list(self): '''Test getting specific list succeeds''' self.api.get_specific_list(list_id=test_list_id) def test_get_list_subscriptions(self): '''Test collection of the lists the specified user is subscribed to succeeds''' self.api.get_list_subscriptions(screen_name='twitter') def test_show_owned_lists(self): '''Test collection of lists the specified user owns succeeds''' self.api.show_owned_lists(screen_name='twitter') # Saved Searches def test_get_saved_searches(self): '''Test getting list of saved searches for authenticated user succeeds''' self.api.get_saved_searches() def test_create_get_destroy_saved_search(self): '''Test getting list of saved searches for authenticated user succeeds''' saved_search = self.api.create_saved_search(query='#Twitter') saved_search_id = saved_search['id_str'] self.api.show_saved_search(id=saved_search_id) self.api.destroy_saved_search(id=saved_search_id) # Places & Geo def test_get_geo_info(self): '''Test getting info about a geo location succeeds''' self.api.get_geo_info(place_id='df51dec6f4ee2b2c') def test_reverse_geo_code(self): '''Test reversing geocode succeeds''' self.api.reverse_geocode(lat='37.76893497', long='-122.42284884') def test_search_geo(self): '''Test search for places that can be attached to a statuses/update succeeds''' self.api.search_geo(query='Toronto') def test_get_similar_places(self): '''Test locates places near the given coordinates which are similar in name succeeds''' self.api.get_similar_places(lat='37', long='-122', name='Twitter HQ') # Trends def test_get_place_trends(self): '''Test getting the top 10 trending topics for a specific WOEID succeeds''' self.api.get_place_trends(id=1) def test_get_available_trends(self): '''Test returning locations that Twitter has trending topic information for succeeds''' self.api.get_available_trends() def test_get_closest_trends(self): '''Test getting the locations that Twitter has trending topic information for, closest to a specified location succeeds''' self.api.get_closest_trends(lat='37', long='-122')
from twython import Twython, TwythonError # Optionally accept user data from the command line (or elsewhere). # # Usage: follow_user.py ryanmcgrath import sys if len(sys.argv) >= 2: target = sys.argv[1] else: target = raw_input( "User to follow: " ) # For Python 3.x use: target = input("User to follow: ") # Requires Authentication as of Twitter API v1.1 twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET) try: twitter.create_friendship(screen_name=target, follow="true") except TwythonError as e: print(e)
def follow(data): twitter = Twython(os.getenv('APP_KEY'), os.getenv('APP_SECRET'), os.getenv('OAUTH_TOKEN'), os.getenv('OAUTH_TOKEN_SECRET'), client_args={'verify':False}) print "Bot: follow: %s %s" % ( data['user']['id_str'], data['user']['screen_name'] ) twitter.create_friendship( user_id=data['user']['id_str'] )
def create_friendship(oauth_token, oauth_token_secret, user_id): twitter = Twython(consumer_key, consumer_secret, oauth_token, oauth_token_secret) result = twitter.create_friendship(user_id=user_id) print("user_id: ", user_id, "was followed successfully") return result
class TwythonAPITestCase(unittest.TestCase): def setUp(self): client_args = { 'headers': { 'User-Agent': '__twython__ Test' }, 'allow_redirects': False } oauth2_client_args = { 'headers': { } # This is so we can hit coverage that Twython sets User-Agent for us if none is supplied } self.api = Twython(app_key, app_secret, oauth_token, oauth_token_secret, client_args=client_args) self.oauth2_api = Twython(app_key, access_token=access_token, client_args=oauth2_client_args) def test_construct_api_url(self): """Test constructing a Twitter API url works as we expect""" url = 'https://api.twitter.com/1.1/search/tweets.json' constructed_url = self.api.construct_api_url(url, q='#twitter') self.assertEqual( constructed_url, 'https://api.twitter.com/1.1/search/tweets.json?q=%23twitter') def test_get(self): """Test Twython generic GET request works""" self.api.get('account/verify_credentials') def test_post(self): """Test Twython generic POST request works, with a full url and with just an endpoint""" update_url = 'https://api.twitter.com/1.1/statuses/update.json' status = self.api.post( update_url, params={'status': 'I love Twython! %s' % int(time.time())}) self.api.post('statuses/destroy/%s' % status['id_str']) def test_get_lastfunction_header(self): """Test getting last specific header of the last API call works""" self.api.get('statuses/home_timeline') self.api.get_lastfunction_header('x-rate-limit-remaining') def test_get_lastfunction_header_not_present(self): """Test getting specific header that does not exist from the last call returns None""" self.api.get('statuses/home_timeline') header = self.api.get_lastfunction_header('does-not-exist') self.assertEqual(header, None) def test_get_lastfunction_header_no_last_api_call(self): """Test attempting to get a header when no API call was made raises a TwythonError""" self.assertRaises(TwythonError, self.api.get_lastfunction_header, 'no-api-call-was-made') def test_cursor(self): """Test looping through the generator results works, at least once that is""" search = self.api.cursor(self.api.search, q='twitter', count=1) counter = 0 while counter < 2: counter += 1 result = next(search) new_id_str = int(result['id_str']) if counter == 1: prev_id_str = new_id_str time.sleep( 1) # Give time for another tweet to come into search if counter == 2: self.assertTrue(new_id_str > prev_id_str) def test_encode(self): """Test encoding UTF-8 works""" self.api.encode('Twython is awesome!') def test_html_for_tweet(self): """Test HTML for Tweet returns what we want""" tweet_text = self.api.html_for_tweet(test_tweet_object) self.assertEqual(test_tweet_html, tweet_text) def test_html_for_tweet_expanded_url(self): """Test using expanded url in HTML for Tweet displays full urls""" tweet_text = self.api.html_for_tweet(test_tweet_object, use_expanded_url=True) # Make sure full url is in HTML self.assertTrue('http://google.com' in tweet_text) def test_html_for_tweet_short_url(self): """Test using expanded url in HTML for Tweet displays full urls""" tweet_text = self.api.html_for_tweet(test_tweet_object, False) # Make sure HTML doesn't contain the display OR exapanded url self.assertTrue(not 'http://google.com' in tweet_text) self.assertTrue(not 'google.com' in tweet_text) def test_raise_error_on_bad_ssl_cert(self): """Test TwythonError is raised by a RequestException when an actual HTTP happens""" self.assertRaises(TwythonError, self.api.get, 'https://example.com') # Timelines def test_get_mentions_timeline(self): """Test returning mentions timeline for authenticated user succeeds""" self.api.get_mentions_timeline() def test_get_user_timeline(self): """Test returning timeline for authenticated user and random user succeeds""" self.api.get_user_timeline() # Authenticated User Timeline self.api.get_user_timeline( screen_name='twitter') # Random User Timeline def test_get_protected_user_timeline_following(self): """Test returning a protected user timeline who you are following succeeds""" self.api.get_user_timeline(screen_name=protected_twitter_1) def test_get_protected_user_timeline_not_following(self): """Test returning a protected user timeline who you are not following fails and raise a TwythonAuthError""" self.assertRaises(TwythonAuthError, self.api.get_user_timeline, screen_name=protected_twitter_2) def test_retweeted_of_me(self): """Test that getting recent tweets by authenticated user that have been retweeted by others succeeds""" self.api.retweeted_of_me() def test_get_home_timeline(self): """Test returning home timeline for authenticated user succeeds""" self.api.get_home_timeline() # Tweets def test_get_retweets(self): """Test getting retweets of a specific tweet succeeds""" self.api.get_retweets(id=test_tweet_id) def test_show_status(self): """Test returning a single status details succeeds""" self.api.show_status(id=test_tweet_id) def test_update_and_destroy_status(self): """Test updating and deleting a status succeeds""" status = self.api.update_status( status='Test post just to get deleted :( %s' % int(time.time())) self.api.destroy_status(id=status['id_str']) def test_get_oembed_tweet(self): """Test getting info to embed tweet on Third Party site succeeds""" self.api.get_oembed_tweet(id='99530515043983360') def test_get_retweeters_ids(self): """Test getting ids for people who retweeted a tweet succeeds""" self.api.get_retweeters_ids(id='99530515043983360') # Search def test_search(self): """Test searching tweets succeeds""" self.api.search(q='twitter') # Direct Messages def test_get_direct_messages(self): """Test getting the authenticated users direct messages succeeds""" 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! %s' % int(time.time())) # 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') self.api.update_friendship(screen_name=protected_twitter_1, retweets=False) def test_show_friendships(self): """Test showing specific friendship succeeds""" self.api.show_friendship(target_screen_name=protected_twitter_1) def test_get_friends_list(self): """Test getting list of users authenticated user then random user is following succeeds""" self.api.get_friends_list() self.api.get_friends_list(screen_name='twitter') def test_get_followers_list(self): """Test getting list of users authenticated user then random user are followed by succeeds""" self.api.get_followers_list() self.api.get_followers_list(screen_name='twitter') # Users def test_get_account_settings(self): """Test getting the authenticated user account settings succeeds""" self.api.get_account_settings() def test_verify_credentials(self): """Test representation of the authenticated user call succeeds""" self.api.verify_credentials() def test_update_account_settings(self): """Test updating a user account settings succeeds""" self.api.update_account_settings(lang='en') 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 def test_get_user_suggestions_by_slug(self): """Test getting user suggestions by slug succeeds""" self.api.get_user_suggestions_by_slug(slug='twitter') def test_get_user_suggestions(self): """Test getting user suggestions succeeds""" self.api.get_user_suggestions() def test_get_user_suggestions_statuses_by_slug(self): """Test getting status of suggested users succeeds""" self.api.get_user_suggestions_statuses_by_slug(slug='funny') # Favorites def test_get_favorites(self): """Test getting list of favorites for the authenticated user succeeds""" self.api.get_favorites() def test_create_and_destroy_favorite(self): """Test creating and destroying a favorite on a tweet succeeds""" self.api.create_favorite(id=test_tweet_id) self.api.destroy_favorite(id=test_tweet_id) # Lists def test_show_lists(self): """Test show lists for specified user""" self.api.show_lists(screen_name='twitter') def test_get_list_statuses(self): """Test timeline of tweets authored by members of the specified list succeeds""" self.api.get_list_statuses( slug=test_list_slug, owner_screen_name=test_list_owner_screen_name) def test_create_update_destroy_list_add_remove_list_members(self): """Test create a list, adding and removing members then deleting the list succeeds""" the_list = self.api.create_list(name='Stuff %s' % int(time.time())) list_id = the_list['id_str'] self.api.update_list(list_id=list_id, name='Stuff Renamed %s' % int(time.time())) screen_names = ['johncena', 'xbox'] # Multi add/delete members self.api.create_list_members(list_id=list_id, screen_name=screen_names) self.api.delete_list_members(list_id=list_id, screen_name=screen_names) # Single add/delete member self.api.add_list_member(list_id=list_id, screen_name='justinbieber') self.api.delete_list_member(list_id=list_id, screen_name='justinbieber') self.api.delete_list(list_id=list_id) def test_get_list_memberships(self): """Test list of memberhips the authenticated user succeeds""" self.api.get_list_memberships() def test_get_list_subscribers(self): """Test list of subscribers of a specific list succeeds""" self.api.get_list_subscribers( slug=test_list_slug, owner_screen_name=test_list_owner_screen_name) def test_subscribe_is_subbed_and_unsubscribe_to_list(self): """Test subscribing, is a list sub and unsubbing to list succeeds""" self.api.subscribe_to_list( slug=test_list_slug, owner_screen_name=test_list_owner_screen_name) # Returns 404 if user is not a subscriber self.api.is_list_subscriber( slug=test_list_slug, owner_screen_name=test_list_owner_screen_name, screen_name=screen_name) self.api.unsubscribe_from_list( slug=test_list_slug, owner_screen_name=test_list_owner_screen_name) def test_is_list_member(self): """Test returning if specified user is member of a list succeeds""" # Returns 404 if not list member self.api.is_list_member(slug=test_list_slug, owner_screen_name=test_list_owner_screen_name, screen_name='themattharris') def test_get_list_members(self): """Test listing members of the specified list succeeds""" self.api.get_list_members( slug=test_list_slug, owner_screen_name=test_list_owner_screen_name) def test_get_specific_list(self): """Test getting specific list succeeds""" self.api.get_specific_list( slug=test_list_slug, owner_screen_name=test_list_owner_screen_name) def test_get_list_subscriptions(self): """Test collection of the lists the specified user is subscribed to succeeds""" self.api.get_list_subscriptions(screen_name='twitter') def test_show_owned_lists(self): """Test collection of lists the specified user owns succeeds""" self.api.show_owned_lists(screen_name='twitter') # Saved Searches def test_get_saved_searches(self): """Test getting list of saved searches for authenticated user succeeds""" self.api.get_saved_searches() def test_create_get_destroy_saved_search(self): """Test getting list of saved searches for authenticated user succeeds""" saved_search = self.api.create_saved_search(query='#Twitter') saved_search_id = saved_search['id_str'] self.api.show_saved_search(id=saved_search_id) self.api.destroy_saved_search(id=saved_search_id) # Places & Geo def test_get_geo_info(self): """Test getting info about a geo location succeeds""" self.api.get_geo_info(place_id='df51dec6f4ee2b2c') def test_reverse_geo_code(self): """Test reversing geocode succeeds""" self.api.reverse_geocode(lat='37.76893497', long='-122.42284884') def test_search_geo(self): """Test search for places that can be attached to a statuses/update succeeds""" self.api.search_geo(query='Toronto') def test_get_similar_places(self): """Test locates places near the given coordinates which are similar in name succeeds""" self.api.get_similar_places(lat='37', long='-122', name='Twitter HQ') # Trends def test_get_place_trends(self): """Test getting the top 10 trending topics for a specific WOEID succeeds""" self.api.get_place_trends(id=1) def test_get_available_trends(self): """Test returning locations that Twitter has trending topic information for succeeds""" self.api.get_available_trends() def test_get_closest_trends(self): """Test getting the locations that Twitter has trending topic information for, closest to a specified location succeeds""" self.api.get_closest_trends(lat='37', long='-122') # Help def test_get_twitter_configuration(self): """Test getting Twitter's configuration succeeds""" self.api.get_twitter_configuration() def test_get_supported_languages(self): """Test getting languages supported by Twitter succeeds""" self.api.get_supported_languages() def test_privacy_policy(self): """Test getting Twitter's Privacy Policy succeeds""" self.api.get_privacy_policy() def test_get_tos(self): """Test getting the Twitter Terms of Service succeeds""" self.api.get_tos() def test_get_application_rate_limit_status(self): """Test getting application rate limit status succeeds""" self.oauth2_api.get_application_rate_limit_status()
class Twitter: twitter = None def __init__(self): twitter_credential = self.importCredential() self.twitter = Twython( twitter_credential['api_key'], twitter_credential['api_secret_key'], twitter_credential['access_token'], twitter_credential['access_token_secret'] ) def importCredential(self): twitter_credential = {} with open('credentials.json') as f: credential = json.load(f) twitter_credential = credential['twitter'] return twitter_credential def getHomeTimeline(self, count=200): timeline = self.twitter.get_home_timeline(count=count) return timeline def getUserTimeline(self, screen_name, count=200): timeline = self.twitter.get_user_timeline(screen_name=screen_name, count=count) return timeline def postTweet(self, message): self.twitter.update_status(status=message) print("Tweeted: " + message) def replyTweet(self, message, tweet_id): selected_tweet = self.twitter.show_status(id=tweet_id) mention_tweet_owner = '@' + selected_tweet['user']['screen_name'] message = mention_tweet_owner + ' ' + message self.twitter.update_status(status=message, in_reply_to_status_id=tweet_id) print("Tweeted reply: " + message) def retweet(self, tweet_id): self.twitter.retweet(id=tweet_id) print(tweet_id + " Retweeted!") def getClosestTrend(self): locationResponse = requests.get('https://freegeoip.app/json/') location = locationResponse.json() locationTwitter = self.twitter.get_closest_trends(lat=location['latitude'], long=location['longitude']) trends = self.twitter.get_place_trends(id=int(locationTwitter[0]['woeid'])) trends = trends[0]['trends'] return trends def getWorldWideTrend(self): trends = self.twitter.get_place_trends(id=1, exclude="words") trends = trends[0]['trends'] return trends def selectHashtagFromTrend(self, trends): hashtagTrend = "" for trend in trends: if (trend['name'].find('#') != -1): hashtagTrend = trend['name'] break return hashtagTrend def likeTweet(self, tweet_id): self.twitter.create_favorite(id=tweet_id) print(tweet_id + " liked!") def getFollowersList(self, screen_name, cursor=-1): fetchCount = 5 followers = self.twitter.get_followers_list(screen_name=screen_name, count=fetchCount, cursor=cursor) return followers def followAccount(self, screen_name): self.twitter.create_friendship(screen_name=screen_name) print ("following : " + screen_name)
class Winston: def __init__(self): self.bot = Twython( app_key=get_secret("CONSUMER_KEY"), app_secret=get_secret("CONSUMER_SECRET"), oauth_token=get_secret("ACCESS_TOKEN_KEY"), oauth_token_secret=get_secret("ACCESS_TOKEN_SECRET")) self.potential_tweets = [ "@PlayOverwatch I didn't pay my taxes!", "I'm wanted in over 60 countries!", "Overwatch.", "Echo!", "@PlayOverwatch #LetWinstonWallRide", "@PlayOverwatch #LetWinstonWallClimb", "Please Delete Echo\n\nSincerely, Winston From Overwatch\n\n@PlayOverwatch", "Year of the Winston Event When? @PlayOverwatch", "Is This On?", "How Embarrassing!", "Winston From Overwatch.", "Is it too much to ask for some peanut butter covered toes? @PlayOverwatch", "I'm holding Sigma hostage in Paris.\nFor every hour Echo isn't nerfed, I will remove one of his toes.\n\n@PlayOverwatch", "My new year's resolutions: Less peanut butter, more... bananas.", "I'm feeling unstoppable!", "I have a crippling addiction to peanut butter." ] self.potential_tweets_with_images = [ ["Are You With Me? @PlayOverwatch", "winston_grin.jpg"], ["You won't like me when I'm angry.", "winston_angry.jpg"], ["Look out world! I'm on a rampage!", "winston_primal_rage.jpg"], ["Holy Shit.", "overwatch_meme.jpg"] ] def send_tweet(self, tweet_text): """Sends a tweet to Twitter""" self.bot.update_status(status=tweet_text) logger.info(f"Tweet Sent: '{tweet_text}'") def send_random_tweet(self): """Tweet something random from potential tweets""" result = random.choice([True, False]) if result: random_tweet = random.choice(self.potential_tweets) self.send_tweet(random_tweet) else: random_tweet_with_image = random.choice( self.potential_tweets_with_images) self.tweet_with_media(random_tweet_with_image) def tweet_with_media(self, text_and_media): """Tweet with media + optional text""" text = text_and_media[0] filename = text_and_media[1] path = f"./bot/media/{filename}" media = open(path, 'rb') try: response = self.bot.upload_media(media=media) self.bot.update_status(status=text, media_ids=[response['media_id']]) logger.info( f"Tweet Sent With Image: || Tweet: {text} || Image Name: {filename}" ) except TwythonError as error: print(error.msg) def follow_someone(self, username): """Follows someone based on given id""" self.bot.create_friendship(screen_name=username) logger.info(f"Followed User: "******"""Likes a tweet based on it's ID""" self.bot.create_favorite(id=tweet_id) logger.info(f"Liked Tweet, Tweet ID: " f'{tweet_id}')
class TwitterNetwork(CtbNetwork): def __init__(self, conf, ctb): CtbNetwork.__init__(self, "twitter") self.conf = conf self.ctb = ctb self.db = ctb.db self.user = conf.auth.user self.app_key = conf.auth.app_key self.app_secret = conf.auth.app_secret self.oauth_token = conf.auth.oauth_token self.oauth_token_secret = conf.auth.oauth_token_secret self.conn = None self.stream = None self.webhooks = None self.account_id = None self.last_db_msg_id = None self.last_db_msg_time = None @classmethod def _timestamp_utc(cls, dt): if isinstance(dt, basestring): dt = parse(dt) return calendar.timegm(dt.utctimetuple()) @classmethod def _timestamp_utc_now(cls): dt = datetime.utcnow() return calendar.timegm(dt.utctimetuple()) def get_account_id(self): # Function for fetching the bot's ID credentials = self.conn.request('account/verify_credentials') return credentials['id'] def get_user_id(self, name): # Function for fetching a users ID credentials = self.conn.lookup_user(screen_name=name) return credentials[0]['id'] def get_user_name(self, id): # Function for fetching a users ID credentials = self.conn.lookup_user(user_id=id) return credentials[0]['screen_name'] def get_last_msg_id(self): # Function to get last msg_id saved in DB sql = "SELECT msg_id FROM t_action WHERE created_utc=(SELECT MAX(created_utc) FROM t_action)" sqlrow = self.db.execute(sql).fetchone() return sqlrow['msg_id'] def get_last_db_action_time(self): # Function to get last action saved in DB sql = "SELECT created_utc, msg_id FROM t_action WHERE created_utc=(SELECT MAX(created_utc) FROM t_action)" sqlrow = self.db.execute(sql).fetchone() return sqlrow['created_utc'], sqlrow['msg_id'] def connect(self): """ Returns a Twitter stream object """ lg.debug('TwitterNetwork::connect(): connecting to Twitter...') self.conn = Twython(self.app_key, self.app_secret, self.oauth_token, self.oauth_token_secret) self.stream = TwitterStreamer(self.app_key, self.app_secret, self.oauth_token, self.oauth_token_secret, timeout=30) self.account_id = self.get_account_id() self.webhooks = TwitterWebHooks(self.conn, self.app_secret, self.account_id) self.conn.username = self.stream.username = self.webhooks.username = self.user self.stream.conn = self.conn self.stream.ctb = self.webhooks.ctb = self.ctb self.stream.last_event = self.stream.last_expiry = self.webhooks.last_event = self.webhooks.last_expiry = datetime.utcnow( ) def run_webhooks(self): lg.info("TwitterWebhooks::starting(): Start init") self.webhooks.run() def is_user_banned(self, user): return False def send_msg(self, user_to, subject, body, editor=None, msgobj=None): try: if msgobj: self.reply_msg(body, msgobj) else: lg.debug( "< TwitterNetwork::send_msg: sending direct message to %s: %s", user_to, body) id = self.get_user_id(user_to) event = { "event": { "type": "message_create", "message_create": { "target": { "recipient_id": id }, "message_data": { "text": body } } } } lg.debug(event) self.conn.send_direct_message(**event) lg.debug("< TwitterNetwork::send_msg to %s DONE", user_to) except TwythonError as e: lg.error("TwitterNetwork::send_msg: exception: %s", e) tb = traceback.format_exc() lg.error("TwitterNetwork::send_msg: traceback: %s", tb) return False else: return True def reply_msg(self, body, msgobj): try: if msgobj is None: pass elif msgobj.type == 'mention': body += ' #ReddCoin' lg.debug( "< TwitterNetwork::reply_msg: sending tweet to %s: %s", msgobj.author.name, body) self.conn.update_status(status=body[:280]) lg.debug("< TwitterNetwork::reply_msg to %s DONE", msgobj.author.name) elif msgobj.type == 'direct_message': lg.debug( "< TwitterNetwork::reply_msg: sending direct message to %s: %s", msgobj.author.name, body) id = self.get_user_id(msgobj.author.name) event = { "event": { "type": "message_create", "message_create": { "target": { "recipient_id": id }, "message_data": { "text": body } } } } lg.debug(event) self.conn.send_direct_message(**event) lg.debug("< TwitterNetwork::reply_msg to %s DONE", msgobj.author.name) except TwythonError as e: lg.error("TwitterNetwork::reply_msg: exception: %s", e) tb = traceback.format_exc() lg.error("TwitterNetwork::reply_msg: traceback: %s", tb) return False else: return True def _parse_mention(self, data): # ignore retweets if 'retweeted_status' in data: return None author_name = data['user']['screen_name'] if author_name == self.user or '@' + self.user not in data['text']: return None # we do allow the bot to issue commands msg = { 'created_utc': self._timestamp_utc_now(), 'author': { 'name': author_name }, 'type': 'mention' } msg['id'] = data['id_str'] + str( msg['created_utc'])[(30 - len(data['id_str'])):] text = data['text'] msg['body'] = text.replace('@' + self.user, '').strip() print(msg) action = ctb_action.eval_message(ctb_misc.DotDict(msg), self.ctb) return action def check_mentions(self, ctb): """ Evaluate new mentions in timeline """ lg.debug('> TwitterNetwork::check_mentions()') try: # Read the last timeline mentions from twitter since the last recorded event since_id = self.last_db_msg_id resp = self.conn.get_mentions_timeline(count=200, since_id=since_id) for tweet in resp: fields = ['created_at', 'id', 'user', 'entities', 'text'] if all(field in tweet for field in fields): # received a mention actions = self._parse_mention(tweet) if not actions: continue if not isinstance(actions, list): actions = [actions] for action in actions: if action: lg.info( "TwitterNetwork::check_mentions(): %s from %s", action.type, action.u_from.name) lg.debug( "TwitterNetwork::check_mentions(): comment body: <%s>", action.msg.body) action.do() except TwythonRateLimitError: lg.error( 'TwitterNetwork::check_mentions(): Twitter API Rate Limit Breached. Sleep 15m30s' ) time.sleep(15 * 60 + 30) lg.info("TwitterNetwork::check_mentions(): Web Hook endpoint starting") self.webhooks.run() def _parse_direct_message(self, event_data): recipient_id = event_data['message_create']['target']['recipient_id'] sender_id = event_data['message_create']['sender_id'] sender_screen_name = self.get_user_name(sender_id) message_text = event_data['message_create']['message_data']['text'] msg = { 'created_utc': self._timestamp_utc_now(), 'author': { 'name': sender_screen_name }, 'recipient_id': sender_id, 'type': 'direct_message' } msg['id'] = event_data['id'] + str( msg['created_utc'])[(30 - len(event_data['id'])):] text = event_data['message_create']['message_data']['text'] msg['body'] = text.replace('@' + self.user, '').strip() lg.debug(msg) action = ctb_action.eval_message(ctb_misc.DotDict(msg), self.ctb) return action def check_inbox(self, ctb): """ Evaluate new messages in inbox """ lg.debug('> TwitterNetwork::check_inbox()') try: if self.last_db_msg_time is None: self.last_db_msg_time, self.last_db_msg_id = self.get_last_db_action_time( ) #[self.last_db_msg_time, self.last_db_msg_id] since_time = self.last_db_msg_time resp = self.conn.get_direct_messages(count=200) for msg in resp['events']: msg_timestamp = int( msg['created_timestamp'] ) / 1000 # twitter timestamps in milliseconds if msg_timestamp > since_time: if msg['id'] != self.last_db_msg_id: if self.account_id != int( msg['message_create']['sender_id']): # received a direct message actions = self._parse_direct_message(msg) if not actions: continue if not isinstance(actions, list): actions = [actions] for action in actions: if action: lg.info( "TwitterNetwork::check_inbox(): %s from %s", action.type, action.u_from.name) lg.debug( "TwitterNetwork::check_inbox(): comment body: <%s>", action.msg.body) action.do() except TwythonError as e: lg.error("TwitterNetwork::check_inbox(): exception: %s", e) pass except TwythonRateLimitError: lg.warning( "TwitterNetwork::check_inbox(): Twitter API rate limit exceeded, sleeping for 15m30s seconds" ) time.sleep(15 * 60 + 30) pass except Exception as e: lg.error("TwitterNetwork::check_inbox(): %s", e) raise lg.debug("< TwitterNetwork::check_inbox() DONE") return True def invite(self, user): try: resp = self.conn.create_friendship(screen_name=user) except TwythonError as e: # either really failed (e.g. sent request before) or already friends lg.warning("TwitterNetwork::invite: failed to follow user %s: %s", user, e.msg) lg.error("TwitterNetwork::invite: exception: %s", e) tb = traceback.format_exc() lg.error("TwitterNetwork::invite: traceback: %s", tb) return False else: lg.debug( 'TwitterNetwork::invite(): just sent request to follow user %s', user) return True
def main(episodenumber, live_tweet, testmode): import sqlite3 as lite from twython import Twython import os import warnings warnings.filterwarnings("ignore") dir = os.path.dirname(__file__) filename = os.path.join(dir, '../tweets.db') con = lite.connect(filename) import twitterconfig twitter = Twython(twitterconfig.APP_KEY, twitterconfig.APP_SECRET, twitterconfig.OAUTH_TOKEN, twitterconfig.OAUTH_TOKEN_SECRET) top_retweets = '' striketweet = '#Tatort - Ins Schwarze getwittert: ' top_tweeters = [] with con: cur = con.cursor() command = 'SELECT * FROM tatorttweets WHERE lfd = ' + str(episodenumber) + ' ORDER BY retweet_count DESC LIMIT 10' cur.execute(command) rows = cur.fetchall() for row in rows: if testmode: print row[2] newtweet = striketweet + ' \n@' + row[2] if not ((len(newtweet) > 140) or (row[2] in top_tweeters)): striketweet = newtweet top_tweeters.append(row[2]) try: twitter.create_friendship(screen_name=row[2]) except Exception as e: if testmode: print e if testmode: print row[4] searchstring = '"' + row[4] + '"' response = twitter.search(q=searchstring, include_entities=1, count=100) for tweet in response['statuses']: if 'RT @' not in tweet['text'] and (row[2] == tweet['user']['screen_name']): oembed = twitter.get_oembed_tweet(id=tweet['id']) # print oembed['html'] try: twitter.create_favorite(id=tweet['id']) twitter.retweet(id=tweet['id']) except Exception as e: if testmode: print e top_retweets += oembed['html'].encode('utf-8') + " <br />\n" topretweetsfilename = os.path.join(dir, "../FlaskWebProject/templates/top_retweets/top_retweets_" + str(episodenumber) + ".txt") topretweetsfile = open(topretweetsfilename, "w") # print top_retweets print >> topretweetsfile, top_retweets topretweetsfile.close() # cmd = "scp -P 50001 " + topretweetsfilename + " [email protected]:../public/tatorttweets/FlaskWebProject/templates/top_retweets/top_retweets_" + str(episodenumber) + ".txt" # print cmd # os.system(cmd) if testmode: print if testmode: print striketweet if testmode: print len(striketweet) if live_tweet: try: twitter.update_status(status=striketweet) twitter.update_status(status="Die meist-retweeted #Tatort tweets: http://tatort.mash-it.net/" + str(episodenumber) + "#Strike") except Exception as e: if testmode: print e
"Cannot find specified user", "You have been blocked from following", ] sleep_seconds = 5 to_follow = list( set([ sn for sn in poets if sn and (sn not in i_follow) and ( sn not in followed) and (sn not in do_not_follow) ])) logger.info(f"Will attempt to follow {len(to_follow)} poets") counter = 0 for sn in to_follow: if sn: try: # follow='false' means don't turn on notifications result = twitter.create_friendship(screen_name=sn, follow="false") followed.append(sn) counter += 1 logger.info(f"followed {counter} / {len(to_follow)}: {sn}") # device='false' means turn off notifications # result = twitter.update_friendship(screen_name=sn, device='false') # logger.info(f'updated {counter} / {len(to_follow)}: {sn}') except TwythonError as e: logger.info(f"exception for {sn}: {e}") # remove the screenname from the list if it matches a valid reason if any([reason in str(e) for reason in exclude_reasons]): do_not_follow.append(sn) logger.info(f"Adding {sn} to do not follow list") elif any([reason in str(e) for reason in stop_reasons]): logger.info("Hit rate limit. Stopping.") break
twitter.verify_credentials() twitter.update_status(status="Test Twerter post.") # Post post = raw_input("Write your tweet: ") twitter.update_status(status=post) # Get timelines print twitter.get_user_timeline(screen_name = "name") print twitter.get_home_timeline(count = 5) # Search print twitter.search(q="linux", result_type="popular") # Follow twitter.create_friendship(screen_name = "LinuxUserMag") # Retweet twitter.retweet(id = "12345") # Favouriting twitter.create_favorite(id = "12345") print twitter.get_favorites() # Mentions print twitter.get_mentions_timeline(count="5") # Trending print twitter.get_place_trends(id="1") # Retrieve lists
class Twitter(object): """ Class for twitter use """ query_string = '#севастополь -украина OR северная OR катер OR SevastopolBoats OR sevboats :) since:%s lang:ru' weather_string = u'#погода в Севастополе на %s.' timelimit = 90 max_follow = 100 def __init__(self, auth=TWITTER_OAUTH_INFO): self.twitter = Twython(**auth) def post_tweet(self, message): """ Writes message into twitter stream """ return self.twitter.update_status(status=message, trim_user=True) def delete_tweet(self, tweet_id): """ Remove tweet from timeline """ return self.twitter.destroy_status(id=tweet_id, trim_user=True) def post_debug(self, message): """ Writes message into console to test """ print message return dict(id=0, id_str='0', text=message) def search(self, query=None, count=10): """ Search tweet with sevboats ref """ if query is None: since = (datetime.datetime.now() - datetime.timedelta(days=7)).date().strftime('%Y-%m-%d') query = self.query_string % since if 'since:%s' in self.query_string else self.query_string return self.twitter.search(q=query, count=count) def follow(self, user_id): """ Follow user by id """ try: return self.twitter.create_friendship(user_id=user_id, follow=True) except TwythonError: return dict(status='error', id_str=None) def unfollow(self, user_id): """ Un Follow user by id """ try: return self.twitter.destroy_friendship(user_id=user_id) except TwythonError: return dict(status='error', id_str=None) def follow_list(self, friends_ids): """ Follow user in search result """ friends = [] for user_id in friends_ids: friends.append(self.follow(user_id)['id_str']) return friends def unfollow_list(self, friends_ids): """ Un Follow user in ids list """ friends = [] for user_id in friends_ids: friends.append(self.unfollow(user_id)['id_str']) return friends def search_to_list(self, search_list=None): """ Follow user in search result """ if search_list is None: search_list = self.search() users_ids = [] for tweet in search_list['statuses']: users_ids.append(tweet['user']['id_str']) return users_ids def my_followers(self): """ Get list of my followers """ followers_ids = [] next_cursor = -1 while next_cursor != '0': cursor = next_cursor fids = self.twitter.get_followers_ids(cursor=cursor, stringify_ids=True, count=1000) followers_ids += fids['ids'] next_cursor = fids['next_cursor_str'] time.sleep(self.timelimit) return followers_ids def follow_search(self): """ Follow for all user in search results """ users_ids = self.search_to_list() self.follow_list(users_ids) return users_ids def follow_followers(self): """ Follow for all followers """ followers_ids = self.my_followers() friends_ids = self.i_follow() users_ids = [] for follower in followers_ids: if follower not in friends_ids: users_ids.append(follower) self.follow_list(users_ids[:self.max_follow]) return users_ids def i_follow(self): """ Get list of user i follow what """ friends_ids = [] next_cursor = -1 while next_cursor != '0': cursor = next_cursor fids = self.twitter.get_friends_ids(cursor=cursor, stringify_ids=True, count=1000) friends_ids += fids['ids'] next_cursor = fids['next_cursor_str'] time.sleep(self.timelimit) return friends_ids def post_image_weather(self): """ Create weather image and post to twitter """ # get weather image print 'start' weth = Weather() weather_img, date_title = weth.draw_img() # create stream print 'streem' image_io = StringIO() # weather_img.save(image_io, format='JPEG', quality=100, subsampling=0, optimize=True, progressive=True) weather_img.save(image_io, format='PNG') image_io.seek(0) # post tweet print 'post' return self.twitter.update_status_with_media(media=image_io, status=self.weather_string % date_title)
from twython import Twython, TwythonError # Optionally accept user data from the command line (or elsewhere). # # Usage: follow_user.py ryanmcgrath import sys if len(sys.argv) >= 2: target = sys.argv[1] else: target = raw_input("User to follow: ") # For Python 3.x use: target = input("User to follow: ") # Requires Authentication as of Twitter API v1.1 twitter = Twython(APP_KEY, APP_SECRET, OAUTH_TOKEN, OAUTH_TOKEN_SECRET) try: twitter.create_friendship(screen_name=target, follow="true") except TwythonError as e: print(e)
elif post['status']=='new': x="A new dataset \""+post['title']+"\" has been published: "+targeturl+"resource/"+post['id'] y=x="A new dataset \""+post['title']+"\" has been published: " print len(y)+22 #len is 37+title+22, 140-59 available for title (81) twitter.update_status(status=x) time.sleep(20) except: pass # In[ ]: #i follow people, run this line to follow and to support us! twitter.create_friendship(screen_name='chhsportalnews') twitter.create_friendship(screen_name='josephjlei') twitter.create_friendship(screen_name='kari_mah') # In[ ]: #final_json=json.dumps(final_list) #encode into json, not currently necessary but can be used to create a http accessible json endpoint # this block was used to learn datetime lib, disregard # # x=datetime.date(2015,1,1) # y=datetime.date(2015,1,2) # print x, y
# == Load Sets == lastrunFollowers = set([ int(follower) for follower in key.get_contents_as_string().decode().split("|") ]) currentFollowers = set(twitterAPI.get_followers_ids()["ids"]) # == Follow Back == # DESC: Follow everyone in current follower list who isn't in lastrun follower list toFollow = currentFollowers.difference(lastrunFollowers) for ID in toFollow: try: user = twitterAPI.show_user(user_id=ID) twitterAPI.create_friendship(user_id=ID) sys.stdout.write("Followed {} (@{}) back.\n".format( user["name"], user["screen_name"])) except: # Rate limit or 404 (should probably do special stuff here later) pass # == Unfollow Unfollowers == # DESC: Unfollow everyone in lastrun follower list who isn't in current follower list. toUnfollow = lastrunFollowers - currentFollowers for ID in toUnfollow: try: user = twitterAPI.show_user(user_id=ID) twitterAPI.destroy_friendship(user_id=ID)
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
class TweetToImage(TwythonStreamer): # Size of each "pixel" PIXEL = 25 # Initial dimensions of temp image DIMENSIONS = (7 * PIXEL, 7 * PIXEL) coords = None image = None image_io = None text = '' twitter = None twitter_user_id = None def build_image(self): """Builds an image from some text""" self.coords = [0, 0] self.image = gd.image(self.DIMENSIONS, True) # Build the temp images and fill with stop color filler = self.image.colorAllocate((0, 0, 0)) self.image.fill((0, 0), filler) self.set_pixels_by_text() self.save_image() def increment_coords(self): """Increment the current pixel coordinates wrapping at the width of DIMENSIONS""" self.coords[0] += (1 * self.PIXEL) if self.coords[0] >= self.DIMENSIONS[0]: self.coords[0] = 0 self.coords[1] += (1 * self.PIXEL) def instantiate_twitter(self): """Set up twitter""" self.twitter = Twython(keys.consumer_key, keys.consumer_secret, keys.access_token, keys.access_token_secret) self.twitter_user_id = self.twitter.verify_credentials()['id'] def is_followed_by(self, id): """Check if the given ID is following me""" f = self.twitter.get_followers_ids() if id in f['ids']: return True else: return False def load_text(self): """Load some text from somewhere for use in processing""" # Read file in as UTF-8 f = codecs.open('sample_tweet.json', 'r', encoding='utf-8') self.text = json.loads(f.read())['text'] f.close() def on_success(self, data): if 'text' in data and not data['in_reply_to_status_id']: found_me = False for mention in data['entities']['user_mentions']: if mention['id'] == self.twitter_user_id: found_me = True if found_me: self.tweet(data) elif random.choice(range(100)) < 10 and self.is_followed_by(data['user']['id']): self.tweet(data) else: print ' - Skipping tweet ' + data['text'].encode('utf-8') + ' from @' + data['user']['screen_name'] elif 'event' in data: if data['event'] == 'follow' and data['target']['screen_name'] == 'TweetToImage': print '--------------------------------------------------------------------------------' print data['source']['screen_name'] + ' followed me, following back...' time.sleep(2) self.twitter.create_friendship(screen_name=data['source']['screen_name'], follow=True) def on_error(self, status_code, data): print status_code def pad_text(self): """Pad text to 147 characters""" for i in range(147 - len(self.text)): self.text += ' ' def save_image(self): """Save image out to disk""" self.image_io = StringIO() self.image.writePng(self.image_io) self.image_io.seek(0) def set_pixels_by_text(self): """Run through text and generate an image from it""" i = 0 rgb = [0, 0, 0] # Get text from somewhere if not self.text: self.load_text() for c in self.text: # Every third character write out as a pixel where # RGB colors are the three previous character's # unicode values if i % 3 == 0 and i > 0: color = self.image.colorAllocate(tuple(rgb)) self.image.filledRectangle(self.coords, (self.coords[0] + self.PIXEL, self.coords[1] + self.PIXEL), color) self.increment_coords() rgb[i % 3] = ord(c) i += 1 def tweet(self, t): """Tweet""" time.sleep(2) print '--------------------------------------------------------------------------------' print 'Replying to @' + t['user']['screen_name'] print t['text'].encode('utf-8') self.text = t['text'].encode('utf-8') self.build_image() try: self.image_io.seek(0) self.twitter.update_profile_image(image=self.image_io) self.image_io.seek(0) except: print '*** Error uploading new profile image!' self.twitter.update_status_with_media(status='@' + t['user']['screen_name'] + ' :)', in_reply_to_status_id=t['id_str'], media=self.image_io)